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//!   POST /v1/completions        -> text_completion | SSE text_completion stream (raw prompt, no template) (auth)
13//!
14//! Two process-level limits bound one request's hold on a `--parallel` slot: `serve.max_tokens_cap`
15//! (tokens — see `clamp_max_tokens`) and `serve.request_timeout_secs` (wall clock — see
16//! `request_timeout`). Both are `serve.*` config, never read from the environment here.
17//!
18//! Every route but `/health` also passes the `Host` check (`host::host_gate`,
19//! `serve.allowed_hosts`), which guards a keyless loopback server against DNS rebinding.
20//!
21//! Delta mapping:
22//!   `Delta::Reasoning`  -> `delta.reasoning_content`
23//!   `Delta::Content`    -> `delta.content`
24//!   `Delta::ToolCall`   -> `delta.tool_calls[]`  (finish_reason "tool_calls")
25
26use std::{
27    convert::Infallible,
28    net::SocketAddr,
29    sync::{
30        atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
31        Arc,
32    },
33    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
34};
35
36use axum::{
37    extract::{rejection::JsonRejection, DefaultBodyLimit, Request, State},
38    http::{HeaderMap, StatusCode},
39    middleware::{self, Next},
40    response::{
41        sse::{Event, KeepAlive, Sse},
42        IntoResponse, Response,
43    },
44    routing::{get, post},
45    Json, Router,
46};
47use infr_core::config::Config;
48use infr_engine::{ChatMessage, Delta, ToolCall};
49use serde::{Deserialize, Serialize};
50use subtle::ConstantTimeEq;
51use tokio::sync::Semaphore;
52
53mod completions;
54mod host;
55mod logprobs;
56mod metrics;
57mod status;
58
59pub use logprobs::{ChatLogprobs, ChatTokenLogprob, ChatTokenLogprobAlt, LogprobStops, TokenText};
60pub use status::{DeviceMemory, GeneratorStatus};
61
62/// Why generation ended — the OpenAI `finish_reason`. The generator reports it; the handlers
63/// serialize it (a tool call still overrides to [`Finish::ToolCalls`] at the wire layer).
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum Finish {
66    /// EOS, or a `stop` sequence fired.
67    Stop,
68    /// The `max_tokens` / `max_completion_tokens` budget was exhausted.
69    Length,
70    /// A tool call was emitted.
71    ToolCalls,
72}
73
74impl Finish {
75    pub fn as_str(self) -> &'static str {
76        match self {
77            Finish::Stop => "stop",
78            Finish::Length => "length",
79            Finish::ToolCalls => "tool_calls",
80        }
81    }
82}
83
84/// Generation backend the server drives — it never knows the model/GPU underneath. Implemented by
85/// the CLI's per-arch adapters (`infr-cli`'s `ParallelGenerator` over `infr_llama::ParallelSeam` for
86/// the Vulkan seam; `SeamGenerator` wraps any `infr_llama::ChatModel` for the rest, including
87/// `DiffusionGemmaChat` — see `docs/diffusion-gemma.md`).
88///
89/// [`GenParams`] carries the request's PER-REQUEST sampling config (temperature/top_p/top_k/seed/
90/// penalties/stop/max_tokens). Every field is an `Option` whose `None` means "inherit the process
91/// default" — so a request that sends nothing generates EXACTLY as it did before this existed.
92///
93/// **`&self`, `Send + Sync`.** This is the whole concurrency contract: the server calls `chat` from
94/// N request tasks at once and the generator is responsible for its own slot allocation and GPU
95/// turn-taking. It used to be `&mut self` behind an `Arc<Mutex<_>>` the handlers held for an ENTIRE
96/// generation, which meant request #2 waited for request #1 to finish — head-of-line blocking, no
97/// parallelism. An implementation that genuinely cannot run concurrently (CPU / Metal / diffusion
98/// today) keeps an internal `Mutex` and is served with `--parallel 1`, which is honest rather than
99/// silently serialising a server the user asked to parallelise.
100pub trait ChatGenerator: Send + Sync {
101    /// Run one chat turn.
102    ///
103    /// * `tools` is the request's `tools` array as a borrowed [`serde_json::Value`] — passed by
104    ///   reference so the generator parses the ONE it was already given instead of a
105    ///   `Value`→string→`Value` round-trip (see audit finding 6).
106    /// * `cancel` is a PER-REQUEST abort latch. The server sets it when the client hangs up
107    ///   (streaming or not) or the request deadline fires; the generator must poll it in its
108    ///   prefill AND decode loops and stop promptly so the GPU slot is freed rather than held to
109    ///   `max_tokens`. An `Arc` so the generator can keep it for the whole call — a deadline that
110    ///   fires during prefill comes before any piece, so a copy made from a streaming callback is
111    ///   too late. It is ORed with the process-wide shutdown latch, never a replacement for it.
112    /// * Returns a [`ChatOutcome`] carrying the finish reason AND the real prompt/completion token
113    ///   counts so the handler can populate `usage` truthfully.
114    /// * A request whose prompt does not fit the context should fail with a
115    ///   [`ContextLengthExceeded`] error. The server answers it as a `400` on a non-streaming
116    ///   request and as a terminal SSE error frame carrying the same typed error on a streaming one
117    ///   (the `200` is already sent by then), so the client can act on it rather than retry it.
118    fn chat(
119        &self,
120        messages: &[ChatMessage],
121        tools: Option<&serde_json::Value>,
122        tool_choice: Option<&str>,
123        params: &GenParams,
124        cancel: &Arc<AtomicBool>,
125        on_delta: &mut dyn FnMut(Delta),
126    ) -> anyhow::Result<ChatOutcome>;
127
128    /// Continue `prompt` as raw text — no chat template, no reasoning/tool splitting — streaming the
129    /// decoded pieces to `on_text`. Backs `/v1/completions`; `cancel` and the return value behave as
130    /// in [`chat`](Self::chat). A prompt that comes to no tokens should fail with
131    /// [`ParamError::empty_prompt`], which the server answers as a `400` naming `prompt`, and an
132    /// over-long one with a [`ContextLengthExceeded`] naming `prompt`.
133    ///
134    /// Default: the model cannot serve raw completions, which the server answers as a `400`
135    /// naming `model` rather than a `500` that reads as a server fault.
136    fn complete(
137        &self,
138        _prompt: &str,
139        _params: &GenParams,
140        _cancel: &Arc<AtomicBool>,
141        _on_text: &mut dyn FnMut(&str),
142    ) -> anyhow::Result<ChatOutcome> {
143        Err(ParamError {
144            param: "model",
145            message: "this model does not support text completions".into(),
146        }
147        .into())
148    }
149
150    /// `prompt`'s token count and the model's usable prompt budget, counted before a slot is
151    /// taken so an over-long raw completion is refused instead of queued. `None` for a backend
152    /// that cannot count a raw prompt without generating it — its generator still reports the
153    /// overflow, and the server answers that as the same `400`.
154    fn prepare_completion(&self, _prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
155        Ok(None)
156    }
157
158    /// [`complete`](Self::complete) with per-token log probabilities. Default: refuse a request that
159    /// asked for them rather than return text without the promised data; backends that support the
160    /// dense seam override it. `on_text` still receives the generated text.
161    fn complete_with_logprobs(
162        &self,
163        prompt: &str,
164        params: &GenParams,
165        cancel: &Arc<AtomicBool>,
166        on_text: &mut dyn FnMut(&str),
167        _on_logprob: &mut dyn FnMut(infr_engine::TokenLogprob),
168    ) -> anyhow::Result<ChatOutcome> {
169        if params.logprobs {
170            return Err(ParamError {
171                param: "logprobs",
172                message: "logprobs: returning log probabilities is not supported by this backend"
173                    .into(),
174            }
175            .into());
176        }
177        self.complete(prompt, params, cancel, on_text)
178    }
179
180    /// Where this generator runs and how much room it has, read fresh on each call, for
181    /// `GET /status` and the device gauges in `/metrics`. Report `None` for what the backend
182    /// cannot see rather than a placeholder. It must not wait on a generation: both routes call it
183    /// while requests are running.
184    fn status(&self) -> GeneratorStatus;
185
186    /// Does this backend produce log probabilities? Checked before the response headers so a
187    /// request for them is a `400` naming the field, not a reply shaped as if it had them.
188    fn supports_logprobs(&self) -> bool {
189        false
190    }
191
192    /// How many token ids this generator's model has — the length of the logits row a
193    /// `logit_bias` is applied to — so a request's `logit_bias` may name only ids below it. The
194    /// server asks only for a request that carries a bias, and before the request reaches
195    /// [`chat`](Self::chat), so a bad id is a `400` on a streaming request too, where the `200`
196    /// goes out before generation starts. It is read on the request path, so return a value
197    /// computed once rather than counting the vocabulary each time.
198    fn vocab_size(&self) -> usize;
199
200    /// Ready a request before it waits for a slot, and before a stream's `200` goes out: render
201    /// its prompt, count it, build whatever it needs to generate, and hand all of that back as a
202    /// [`PreparedRequest`] the server passes to [`chat_prepared`](Self::chat_prepared), so the
203    /// work is done once per request.
204    ///
205    /// The server logs [`PreparedRequest::prompt_tokens`] on the arrival line and answers a
206    /// prompt longer than [`PreparedRequest::context_length`] with `400 context_length_exceeded`
207    /// — on a stream too, so the client gets a real `400` rather than a `200` and an error frame,
208    /// and an over-long prompt never takes a slot. An error is answered before the request is
209    /// queued, as [`chat`](Self::chat)'s would be: a [`ParamError`] or [`ContextLengthExceeded`]
210    /// is a `400`, anything else a `500`.
211    ///
212    /// Never wait on a generation here: it runs while other requests generate. The default,
213    /// `Ok(None)`, prepares nothing, and the server calls [`chat`](Self::chat) as it always has.
214    fn prepare(
215        &self,
216        _messages: &[ChatMessage],
217        _tools: Option<&serde_json::Value>,
218        _tool_choice: Option<&str>,
219        _params: &GenParams,
220    ) -> anyhow::Result<Option<PreparedRequest>> {
221        Ok(None)
222    }
223
224    /// Run a turn [`prepare`](Self::prepare) readied, with the same request it was prepared from.
225    /// A generator that implements `prepare` implements this too; the default ignores `prepared`
226    /// and calls [`chat`](Self::chat).
227    #[allow(clippy::too_many_arguments)]
228    fn chat_prepared(
229        &self,
230        prepared: PreparedRequest,
231        messages: &[ChatMessage],
232        tools: Option<&serde_json::Value>,
233        tool_choice: Option<&str>,
234        params: &GenParams,
235        cancel: &Arc<AtomicBool>,
236        on_delta: &mut dyn FnMut(Delta),
237    ) -> anyhow::Result<ChatOutcome> {
238        drop(prepared);
239        self.chat(messages, tools, tool_choice, params, cancel, on_delta)
240    }
241}
242
243/// A request a [`ChatGenerator`] has readied in [`prepare`](ChatGenerator::prepare): what the
244/// server reads before queueing it, plus the generator's own state for
245/// [`chat_prepared`](ChatGenerator::chat_prepared), which the server carries without looking at.
246pub struct PreparedRequest {
247    /// The rendered prompt, in tokens, exactly as generation will see it.
248    pub prompt_tokens: u32,
249    /// The longest prompt the model accepts — what OpenAI's error calls the model's "maximum
250    /// context length". `None` when the generator has no fixed limit or does not know it yet.
251    pub context_length: Option<u32>,
252    state: Box<dyn std::any::Any + Send>,
253}
254
255impl PreparedRequest {
256    /// A prepared request carrying `state` for the generator that made it.
257    pub fn new(
258        prompt_tokens: u32,
259        context_length: Option<u32>,
260        state: impl std::any::Any + Send,
261    ) -> Self {
262        Self {
263            prompt_tokens,
264            context_length,
265            state: Box::new(state),
266        }
267    }
268
269    /// The state [`Self::new`] was given, or `None` when it is not a `T` — a request prepared by
270    /// another generator, which the caller then treats as unprepared.
271    pub fn into_state<T: std::any::Any>(self) -> Option<T> {
272        self.state.downcast::<T>().ok().map(|b| *b)
273    }
274}
275
276impl std::fmt::Debug for PreparedRequest {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("PreparedRequest")
279            .field("prompt_tokens", &self.prompt_tokens)
280            .field("context_length", &self.context_length)
281            .finish_non_exhaustive()
282    }
283}
284
285/// One turn on `engine`: through [`ChatGenerator::chat_prepared`] when the request was prepared,
286/// else [`ChatGenerator::chat`].
287#[allow(clippy::too_many_arguments)]
288fn generate(
289    engine: &dyn ChatGenerator,
290    prepared: Option<PreparedRequest>,
291    messages: &[ChatMessage],
292    tools: Option<&serde_json::Value>,
293    tool_choice: Option<&str>,
294    params: &GenParams,
295    cancel: &Arc<AtomicBool>,
296    on_delta: &mut dyn FnMut(Delta),
297) -> anyhow::Result<ChatOutcome> {
298    match prepared {
299        Some(p) => engine.chat_prepared(p, messages, tools, tool_choice, params, cancel, on_delta),
300        None => engine.chat(messages, tools, tool_choice, params, cancel, on_delta),
301    }
302}
303
304/// What one [`ChatGenerator::chat`] call produced: why it ended, plus the real token counts the
305/// handler needs for a truthful `usage` block (`total = prompt + completion`). Counts are what the
306/// generator actually tokenized/emitted — never a `content.len()/4` estimate.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct ChatOutcome {
309    pub finish: Finish,
310    /// The WHOLE prompt, including any part served from a KV prefix cache — OpenAI's
311    /// `usage.prompt_tokens`, which clients budget context and cost from.
312    pub prompt_tokens: u32,
313    pub completion_tokens: u32,
314    /// How many of `prompt_tokens` were reused from a KV prefix cache rather than prefilled
315    /// (`usage.prompt_tokens_details.cached_tokens`). `0` for a generator with no prefix cache.
316    pub cached_tokens: u32,
317}
318
319/// The request's prompt does not fit the model's context. A [`ChatGenerator`] returns it (as the
320/// `anyhow` error) so the server can answer `400` with OpenAI's `context_length_exceeded` code:
321/// OpenAI clients retry a `5xx` unchanged, but treat this code as final and shorten the
322/// conversation instead.
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub struct ContextLengthExceeded {
325    /// What the client is told: which counts did not fit.
326    pub message: String,
327}
328
329impl ContextLengthExceeded {
330    /// A prompt of `prompt_tokens` that is longer than `context_length`, in OpenAI's own wording
331    /// (client-side error mappers match on it). `input` names the request field the prompt came
332    /// from: `messages` on the chat route, `prompt` on `/v1/completions`.
333    pub fn prompt_too_long(input: &str, context_length: usize, prompt_tokens: usize) -> Self {
334        Self {
335            message: format!(
336                "This model's maximum context length is {context_length} tokens. However, your \
337                 {input} resulted in {prompt_tokens} tokens. Please reduce the length of the \
338                 {input}."
339            ),
340        }
341    }
342
343    /// A prompt of `prompt_tokens` that fits, but not with the `reply_tokens` the reply was given
344    /// room for, in the same wording. Lowering the reply budget is suggested only when
345    /// `can_lower_reply`: a budget the client never chose, or one of zero, is nothing it can
346    /// lower. `input` is as for [`Self::prompt_too_long`].
347    pub fn reply_too_long(
348        input: &str,
349        context_length: usize,
350        prompt_tokens: usize,
351        reply_tokens: usize,
352        can_lower_reply: bool,
353    ) -> Self {
354        let advice = if can_lower_reply {
355            format!("Please reduce the length of the {input} or completion.")
356        } else {
357            format!("Please reduce the length of the {input}.")
358        };
359        Self {
360            message: format!(
361                "This model's maximum context length is {context_length} tokens. However, you \
362                 requested {} tokens ({prompt_tokens} in the {input}, {reply_tokens} in the \
363                 completion). {advice}",
364                prompt_tokens + reply_tokens
365            ),
366        }
367    }
368}
369
370impl std::fmt::Display for ContextLengthExceeded {
371    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372        f.write_str(&self.message)
373    }
374}
375
376impl std::error::Error for ContextLengthExceeded {}
377
378// ---------------------------------------------------------------------------
379// Request DTOs
380// ---------------------------------------------------------------------------
381
382/// Top-level chat completion request (OpenAI wire format).
383///
384/// Unknown fields are IGNORED (no `deny_unknown_fields`) — an OpenAI client sending `user`,
385/// `logprobs: false`, … must not 400. Known-but-invalid VALUES do 400, via
386/// [`GenParams::from_request`], and so do the known fields asking for a feature the server does
387/// not have (`n > 1`), rather than being answered as if they had been honoured.
388#[derive(Debug, Deserialize)]
389pub struct ChatRequest {
390    pub model: String,
391    pub messages: Vec<ChatMessageDto>,
392    #[serde(default)]
393    pub stream: bool,
394    #[serde(default)]
395    pub tools: Option<serde_json::Value>,
396    /// OpenAI `tool_choice`: `"auto"` | `"required"` | `"none"` | `{"type":"function","function":
397    /// {"name":..}}`. Normalised to a string (the function name for a named choice) by `tool_choice_str`.
398    #[serde(default)]
399    pub tool_choice: Option<serde_json::Value>,
400    /// `-1` means "not set": the server's default reply budget (`sampling.max_new`), NOT
401    /// llama.cpp's `n_predict: -1` "until the context is full" — an unbounded reply is what the
402    /// default budget exists to prevent.
403    #[serde(default, deserialize_with = "minus_one_is_unset")]
404    pub max_tokens: Option<u32>,
405    /// OpenAI's rename of `max_tokens`. Preferred when both are present.
406    #[serde(default, deserialize_with = "minus_one_is_unset")]
407    pub max_completion_tokens: Option<u32>,
408    #[serde(default)]
409    pub temperature: Option<f32>,
410    #[serde(default)]
411    pub top_p: Option<f32>,
412    /// Not in the OpenAI schema; llama.cpp/vLLM/Ollama all accept it and so do we.
413    #[serde(default)]
414    pub top_k: Option<i64>,
415    #[serde(default, deserialize_with = "minus_one_is_unset")]
416    pub seed: Option<u64>,
417    /// `"\n"` or `["\n", "END"]` (OpenAI: up to 4).
418    #[serde(default)]
419    pub stop: Option<serde_json::Value>,
420    #[serde(default)]
421    pub presence_penalty: Option<f32>,
422    #[serde(default)]
423    pub frequency_penalty: Option<f32>,
424    /// llama.cpp extension (1.0 = off).
425    #[serde(default)]
426    pub repeat_penalty: Option<f32>,
427    /// llama.cpp/vLLM extension (0 = off): drop tokens less likely than `min_p` times the top one.
428    #[serde(default)]
429    pub min_p: Option<f32>,
430    /// OpenAI `logit_bias`: `{"<token id>": bias}`. Kept as the client sent it so a malformed
431    /// map is a `400` naming the parameter, not a body-parse failure.
432    #[serde(default)]
433    pub logit_bias: Option<LogitBiasArg>,
434    /// OpenAI `n`: how many choices to return. Only one is supported. A raw value for the same
435    /// reason as `logit_bias`; see [`GenParams::from_request`].
436    #[serde(default)]
437    pub n: Option<serde_json::Value>,
438    /// OpenAI `logprobs`: include each generated token's log probability.
439    #[serde(default)]
440    pub logprobs: Option<bool>,
441    /// OpenAI `top_logprobs`: how many most likely alternatives to include per token, 0..=20.
442    /// Absent with `logprobs: true` means 20, as in llama.cpp. A raw value, as `n`.
443    #[serde(default)]
444    pub top_logprobs: Option<serde_json::Value>,
445    /// OpenAI `stream_options`; only `include_usage` is read.
446    #[serde(default)]
447    pub stream_options: Option<StreamOptions>,
448    /// OpenAI `response_format`, as sent; validated into [`GenParams::response_format`], so a
449    /// malformed one is a `400` naming the field rather than a body rejection.
450    #[serde(default)]
451    pub response_format: Option<serde_json::Value>,
452}
453
454/// What the reply must look like — a validated OpenAI `response_format`. `{"type":"text"}`, like an
455/// absent field, asks for nothing and never becomes a value.
456///
457/// Either kind is enforced by grammar: the reply CONTENT is one JSON value and nothing else, so a
458/// generator runs it with the model's reasoning off. `json_schema.strict` is accepted and changes
459/// nothing: the schema's keywords are enforced either way, and a keyword the grammar engine does
460/// not implement is a `400` rather than dropped.
461///
462/// Also a `400`, for the schema and for each tool's `parameters` alike: a `$ref` that is not a
463/// plain local pointer (`#` or `#/…`, no percent-encoding — `#/$defs/…` relative to a tool's
464/// own `parameters` works), and any `$id`, `$anchor`, `$dynamicRef`/`$dynamicAnchor` or
465/// `$recursiveRef`/`$recursiveAnchor`; a schema nested too deep (counting references followed),
466/// with too many references or JSON values, or too many distinct `multipleOf` steps; a step too
467/// fine or too large for the engine to match quickly, or two steps anywhere in one schema whose
468/// combination would be (checked pairwise whether or not they meet, so a few schemas are refused
469/// that could have compiled); and an integer bound the engine's arithmetic cannot hold.
470///
471/// The grammar is narrower than the schema in one respect, as llama.cpp's is: a number the schema
472/// leaves unbounded is limited in magnitude and in fraction digits (infr-llama's `NUMBER_LIMIT`
473/// and `NUMBER_STEP`, in its grammar module), and is not written in exponent form, so a model
474/// cannot spin a digit string out to `max_tokens`. Where the schema's own shape prevents that the
475/// number stays as the schema bounds it: in subschemas the engine intersects (`allOf`,
476/// applicators beside sibling keywords, a property matching a pattern property, definitions
477/// referenced from such places), and without the fraction limit where the range is narrower than
478/// its step or the schema's own `multipleOf` cannot combine with it. Bounds, `multipleOf`,
479/// `const` and `enum` the schema sets itself are kept. Strings, array lengths and nesting are not
480/// bounded, as in llama.cpp.
481#[derive(Debug, Clone, PartialEq)]
482pub enum ResponseFormat {
483    /// `{"type":"json_object"}`: one JSON object, of any shape.
484    JsonObject,
485    /// `{"type":"json_schema","json_schema":{"schema":{..}}}` — or llama.cpp's
486    /// `{"type":"json_object","schema":{..}}` — one JSON value matching the schema. A
487    /// `json_schema` without a schema (or with a `null` one) is any JSON value, the empty schema
488    /// `{}`, as OpenAI and llama.cpp read it.
489    JsonSchema(serde_json::Value),
490}
491
492impl ResponseFormat {
493    /// The JSON schema the reply must match.
494    pub fn schema(&self) -> serde_json::Value {
495        match self {
496            ResponseFormat::JsonObject => serde_json::json!({"type": "object"}),
497            ResponseFormat::JsonSchema(schema) => schema.clone(),
498        }
499    }
500
501    /// Validate a request's `response_format`: `Ok(None)` for none or `text`, a [`ParamError`]
502    /// for a shape or `type` this server does not do.
503    fn from_request(v: Option<&serde_json::Value>) -> Result<Option<Self>, ParamError> {
504        let bad = |message: String| ParamError {
505            param: "response_format",
506            message,
507        };
508        let Some(v) = v.filter(|v| !v.is_null()) else {
509            return Ok(None);
510        };
511        let kind = v
512            .get("type")
513            .and_then(serde_json::Value::as_str)
514            .ok_or_else(|| bad("response_format must be an object with a string `type`".into()))?;
515        // An absent or `null` schema is `None`; anything else must be a schema object.
516        let schema_at = |v: Option<&serde_json::Value>, path: &str| match v {
517            None | Some(serde_json::Value::Null) => Ok(None),
518            Some(s) if s.is_object() => Ok(Some(s.clone())),
519            _ => Err(bad(format!("{path} must be a JSON schema object"))),
520        };
521        match kind {
522            "text" => Ok(None),
523            "json_object" => Ok(Some(
524                match schema_at(v.get("schema"), "response_format.schema")? {
525                    Some(s) => Self::JsonSchema(s),
526                    None => Self::JsonObject,
527                },
528            )),
529            "json_schema" => {
530                let wrapper = v.get("json_schema").filter(|j| !j.is_null());
531                if wrapper.is_some_and(|j| !j.is_object()) {
532                    return Err(bad("response_format.json_schema must be an object".into()));
533                }
534                let schema = schema_at(
535                    wrapper.and_then(|j| j.get("schema")),
536                    "response_format.json_schema.schema",
537                )?;
538                Ok(Some(Self::JsonSchema(
539                    schema.unwrap_or_else(|| serde_json::json!({})),
540                )))
541            }
542            other => Err(bad(format!(
543                "response_format type must be \"text\", \"json_object\" or \"json_schema\", \
544                 got {other:?}"
545            ))),
546        }
547    }
548}
549
550/// A request's `logit_bias` as the client sent it: the object's entries in order with a repeated
551/// key kept (a JSON object map would silently merge it), or the JSON type sent instead of an
552/// object. `null` deserializes as an absent field.
553#[derive(Debug, Clone)]
554pub enum LogitBiasArg {
555    Entries(Vec<(String, serde_json::Value)>),
556    /// Not an object; the JSON type it was, for the `400`.
557    NotAnObject(&'static str),
558}
559
560impl<'de> Deserialize<'de> for LogitBiasArg {
561    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
562        struct V;
563        impl<'de> serde::de::Visitor<'de> for V {
564            type Value = LogitBiasArg;
565
566            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
567                f.write_str("a JSON value")
568            }
569
570            fn visit_map<A: serde::de::MapAccess<'de>>(
571                self,
572                mut m: A,
573            ) -> Result<Self::Value, A::Error> {
574                let mut entries = Vec::new();
575                while let Some(entry) = m.next_entry::<String, serde_json::Value>()? {
576                    entries.push(entry);
577                }
578                Ok(LogitBiasArg::Entries(entries))
579            }
580
581            fn visit_seq<A: serde::de::SeqAccess<'de>>(
582                self,
583                mut s: A,
584            ) -> Result<Self::Value, A::Error> {
585                while s.next_element::<serde::de::IgnoredAny>()?.is_some() {}
586                Ok(LogitBiasArg::NotAnObject("array"))
587            }
588
589            fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {
590                Ok(LogitBiasArg::NotAnObject("boolean"))
591            }
592
593            fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {
594                Ok(LogitBiasArg::NotAnObject("number"))
595            }
596
597            fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {
598                Ok(LogitBiasArg::NotAnObject("number"))
599            }
600
601            fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {
602                Ok(LogitBiasArg::NotAnObject("number"))
603            }
604
605            fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {
606                Ok(LogitBiasArg::NotAnObject("string"))
607            }
608        }
609        d.deserialize_any(V)
610    }
611}
612
613/// OpenAI `stream_options`. With `include_usage`, a streamed reply ends with one extra chunk that
614/// carries `usage` and an empty `choices` array, just before `[DONE]`.
615#[derive(Debug, Default, Deserialize)]
616pub struct StreamOptions {
617    #[serde(default)]
618    pub include_usage: bool,
619}
620
621/// An optional integer field where `-1` means "not set". llama.cpp-style clients send `-1` for
622/// `seed` (random) and `max_tokens` (no explicit budget); refusing it as a negative number would
623/// turn those requests into a `400`. Any other negative value is still an error.
624fn minus_one_is_unset<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
625where
626    D: serde::Deserializer<'de>,
627    T: TryFrom<u64>,
628{
629    use serde::de::Error;
630    match Option::<i128>::deserialize(d)? {
631        None | Some(-1) => Ok(None),
632        Some(v) => u64::try_from(v)
633            .ok()
634            .and_then(|v| T::try_from(v).ok())
635            .map(Some)
636            .ok_or_else(|| D::Error::custom(format!("{v} is out of range (use -1 for unset)"))),
637    }
638}
639
640/// The validated, per-request generation config handed to [`ChatGenerator::chat`]. `None` fields
641/// mean "the request didn't say" — the generator leaves the process default (`INFR_TEMP` /
642/// `INFR_TOP_K` / `INFR_TOP_P` / `INFR_MAX_NEW`) in charge for exactly those.
643#[derive(Debug, Clone, Default, PartialEq)]
644pub struct GenParams {
645    pub max_tokens: Option<u32>,
646    pub temperature: Option<f32>,
647    pub top_p: Option<f32>,
648    pub top_k: Option<usize>,
649    pub seed: Option<u64>,
650    pub presence_penalty: Option<f32>,
651    pub frequency_penalty: Option<f32>,
652    pub repeat_penalty: Option<f32>,
653    pub min_p: Option<f32>,
654    /// `(token id, bias)` pairs in ascending id order. Ids are checked against the model's
655    /// vocabulary by [`check_vocab`](Self::check_vocab), which needs the routed generator.
656    pub logit_bias: Vec<(u32, f32)>,
657    /// OpenAI `logprobs`: include each generated token's log probability in the reply.
658    pub logprobs: bool,
659    /// How many most likely alternatives to include per token. `0` with `logprobs` on reports
660    /// only the chosen token. Defaults to 20, OpenAI's upper bound, when `top_logprobs` is
661    /// absent, matching llama.cpp.
662    pub top_logprobs: usize,
663    /// Already normalised: empty strings dropped (an empty stop would fire on the first token).
664    pub stop: Vec<String>,
665    /// `None` for free text. Not sampling, but the same "what this request asked for" the rest of
666    /// this struct carries to the generator.
667    pub response_format: Option<ResponseFormat>,
668}
669
670/// An OpenAI-shaped 400: `{"error":{"message":..,"type":"invalid_request_error","param":..}}`.
671///
672/// Also an error a [`ChatGenerator`] returns (as the `anyhow` error) for a request it cannot
673/// honour — a `response_format` schema its grammar engine rejects, a constraint its backend cannot
674/// apply: the server answers it as this `400` (a terminal error frame when streaming), not a `500`.
675#[derive(Debug, Clone, PartialEq)]
676pub struct ParamError {
677    pub param: &'static str,
678    pub message: String,
679}
680
681impl std::fmt::Display for ParamError {
682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683        f.write_str(&self.message)
684    }
685}
686
687impl std::error::Error for ParamError {}
688
689impl ParamError {
690    /// A `/v1/completions` prompt that comes to no tokens at all — empty text on a model that adds
691    /// no BOS — which leaves the model nothing to continue from.
692    pub fn empty_prompt() -> Self {
693        Self {
694            param: "prompt",
695            message: "prompt is empty; send at least one token of text".into(),
696        }
697    }
698}
699
700/// OpenAI's upper bound for `top_logprobs`.
701const MAX_TOP_LOGPROBS: usize = 20;
702
703impl GenParams {
704    /// Validate + normalise the request's sampling fields. Out-of-range values are a 400, NEVER a
705    /// silent clamp and never a panic (OpenAI's own ranges: temperature 0..2, top_p 0..1,
706    /// presence/frequency -2..2, logit_bias -100..100, at most 4 stop sequences; min_p 0..1).
707    /// `n > 1` is a 400 too: the server returns one choice, and a reply shaped as if it had more
708    /// would be wrong.
709    pub fn from_request(req: &ChatRequest) -> Result<Self, ParamError> {
710        let unsupported = |param: &'static str, what: &str| ParamError {
711            param,
712            message: format!("{param}: {what} is not supported by this server"),
713        };
714        match whole_number("n", req.n.as_ref())? {
715            None | Some(1) => {}
716            Some(n) if n < 1 => {
717                return Err(ParamError {
718                    param: "n",
719                    message: format!("n must be >= 1, got {n}"),
720                })
721            }
722            Some(n) => return Err(unsupported("n", &format!("returning {n} choices"))),
723        }
724        let logprobs = req.logprobs.unwrap_or(false);
725        // llama.cpp's default when `logprobs` is true and `top_logprobs` is absent; an explicit 0
726        // asks for the chosen token's probability and no alternatives.
727        let top_logprobs = match whole_number("top_logprobs", req.top_logprobs.as_ref())? {
728            None if logprobs => MAX_TOP_LOGPROBS,
729            None | Some(0) => 0,
730            Some(k) if k < 0 => {
731                return Err(ParamError {
732                    param: "top_logprobs",
733                    message: format!("top_logprobs must be >= 0, got {k}"),
734                })
735            }
736            Some(k) if k > MAX_TOP_LOGPROBS as i64 => {
737                return Err(ParamError {
738                    param: "top_logprobs",
739                    message: format!("top_logprobs must be at most {MAX_TOP_LOGPROBS}, got {k}"),
740                })
741            }
742            Some(k) => k as usize,
743        };
744        if top_logprobs > 0 && !logprobs {
745            return Err(ParamError {
746                param: "top_logprobs",
747                message: "top_logprobs requires logprobs to be set to true".into(),
748            });
749        }
750
751        let rng = |param: &'static str,
752                   v: Option<f32>,
753                   lo: f32,
754                   hi: f32|
755         -> Result<Option<f32>, ParamError> {
756            match v {
757                Some(x) if !x.is_finite() || x < lo || x > hi => Err(ParamError {
758                    param,
759                    message: format!("{param} must be between {lo} and {hi}, got {x}"),
760                }),
761                other => Ok(other),
762            }
763        };
764
765        let top_k = match req.top_k {
766            // 0 = "no top-k" in llama.cpp; negative is meaningless.
767            Some(k) if k < 0 => {
768                return Err(ParamError {
769                    param: "top_k",
770                    message: format!("top_k must be >= 0, got {k}"),
771                })
772            }
773            Some(k) => Some(k as usize),
774            None => None,
775        };
776
777        let stop = match &req.stop {
778            None | Some(serde_json::Value::Null) => Vec::new(),
779            Some(serde_json::Value::String(s)) => vec![s.clone()],
780            Some(serde_json::Value::Array(a)) => {
781                let mut v = Vec::with_capacity(a.len());
782                for item in a {
783                    match item.as_str() {
784                        Some(s) => v.push(s.to_string()),
785                        None => {
786                            return Err(ParamError {
787                                param: "stop",
788                                message: "stop must be a string or an array of strings".into(),
789                            })
790                        }
791                    }
792                }
793                v
794            }
795            Some(_) => {
796                return Err(ParamError {
797                    param: "stop",
798                    message: "stop must be a string or an array of strings".into(),
799                })
800            }
801        };
802        if stop.len() > 4 {
803            return Err(ParamError {
804                param: "stop",
805                message: format!("at most 4 stop sequences are supported, got {}", stop.len()),
806            });
807        }
808        // An empty stop string would match at every position — drop it rather than dead-stop.
809        let stop: Vec<String> = stop.into_iter().filter(|s| !s.is_empty()).collect();
810
811        if let Some(p) = req.repeat_penalty {
812            if !p.is_finite() || p <= 0.0 {
813                return Err(ParamError {
814                    param: "repeat_penalty",
815                    message: format!("repeat_penalty must be > 0, got {p}"),
816                });
817            }
818        }
819
820        let logit_bias = parse_logit_bias(req.logit_bias.as_ref())?;
821
822        Ok(Self {
823            // OpenAI renamed `max_tokens` -> `max_completion_tokens`; the new name wins.
824            max_tokens: req.max_completion_tokens.or(req.max_tokens),
825            temperature: rng("temperature", req.temperature, 0.0, 2.0)?,
826            top_p: rng("top_p", req.top_p, 0.0, 1.0)?,
827            top_k,
828            seed: req.seed,
829            presence_penalty: rng("presence_penalty", req.presence_penalty, -2.0, 2.0)?,
830            frequency_penalty: rng("frequency_penalty", req.frequency_penalty, -2.0, 2.0)?,
831            repeat_penalty: req.repeat_penalty,
832            min_p: rng("min_p", req.min_p, 0.0, 1.0)?,
833            logit_bias,
834            logprobs,
835            top_logprobs,
836            stop,
837            response_format: ResponseFormat::from_request(req.response_format.as_ref())?,
838        })
839    }
840
841    /// The `logit_bias` ids against the routed model's vocabulary: an id at or past `vocab` names
842    /// no token, so the request is a 400 rather than a bias that silently does nothing.
843    pub fn check_vocab(&self, vocab: usize) -> Result<(), ParamError> {
844        match self.logit_bias.iter().find(|&&(t, _)| t as usize >= vocab) {
845            Some(&(t, _)) => Err(ParamError {
846                param: "logit_bias",
847                message: format!(
848                    "logit_bias names token {t}, but the model's vocabulary has {vocab} tokens"
849                ),
850            }),
851            None => Ok(()),
852        }
853    }
854}
855
856/// An integer count field (`n`, `top_logprobs`): absent or `null` is `None`, and a whole number
857/// is that integer — `1.0` reads as `1`, as OpenAI's own validation reads it. Anything else is a
858/// 400 naming `param`, where typing the field as an integer made it a body-parse failure that
859/// named nothing.
860fn whole_number(
861    param: &'static str,
862    v: Option<&serde_json::Value>,
863) -> Result<Option<i64>, ParamError> {
864    let Some(v) = v.filter(|v| !v.is_null()) else {
865        return Ok(None);
866    };
867    if let Some(i) = v.as_i64() {
868        return Ok(Some(i));
869    }
870    if let Some(u) = v.as_u64() {
871        // Past `i64`: still a count, and every caller rejects one this large.
872        return Ok(Some(i64::try_from(u).unwrap_or(i64::MAX)));
873    }
874    match v.as_f64() {
875        Some(f) if f.fract() == 0.0 && (i64::MIN as f64..=i64::MAX as f64).contains(&f) => {
876            Ok(Some(f as i64))
877        }
878        _ => Err(ParamError {
879            param,
880            message: format!("{param} must be an integer, got {v}"),
881        }),
882    }
883}
884
885/// OpenAI's bound on a `logit_bias` value, either sign.
886const LOGIT_BIAS_LIMIT: f64 = 100.0;
887
888/// OpenAI `logit_bias` (`{"<token id>": bias}`) as `(id, bias)` pairs sorted by id. Absent or
889/// `null` is no bias.
890///
891/// A key must be the id in canonical decimal (`"5"`, never `"+5"` or `"05"`), and an id may
892/// appear once: otherwise several spellings of one token would stack their biases past the
893/// validated range.
894fn parse_logit_bias(v: Option<&LogitBiasArg>) -> Result<Vec<(u32, f32)>, ParamError> {
895    let err = |message: String| ParamError {
896        param: "logit_bias",
897        message,
898    };
899    let entries = match v {
900        None => return Ok(Vec::new()),
901        Some(LogitBiasArg::Entries(e)) => e,
902        Some(LogitBiasArg::NotAnObject(t)) => {
903            return Err(err(format!(
904                "logit_bias must be an object mapping token ids to biases, got a {t}"
905            )))
906        }
907    };
908    let mut out = Vec::with_capacity(entries.len());
909    for (key, val) in entries {
910        let canonical = key.bytes().all(|b| b.is_ascii_digit())
911            && (key == "0" || (!key.is_empty() && !key.starts_with('0')));
912        let id: u32 = canonical
913            .then(|| key.parse().ok())
914            .flatten()
915            .ok_or_else(|| {
916                err(format!(
917                    "logit_bias key {key:?} is not a token id (a non-negative integer written \
918                     without sign or leading zeros)"
919                ))
920            })?;
921        let bias = val
922            .as_f64()
923            .ok_or_else(|| err(format!("logit_bias for token {id} must be a number")))?;
924        if !(-LOGIT_BIAS_LIMIT..=LOGIT_BIAS_LIMIT).contains(&bias) {
925            return Err(err(format!(
926                "logit_bias for token {id} must be between -{LOGIT_BIAS_LIMIT} and \
927                 {LOGIT_BIAS_LIMIT}, got {bias}"
928            )));
929        }
930        out.push((id, bias as f32));
931    }
932    out.sort_by_key(|&(id, _)| id);
933    if let Some(w) = out.windows(2).find(|w| w[0].0 == w[1].0) {
934        return Err(err(format!("logit_bias names token {} twice", w[0].0)));
935    }
936    Ok(out)
937}
938
939// ---------------------------------------------------------------------------
940// Stop sequences
941// ---------------------------------------------------------------------------
942
943/// Incremental stop-sequence matcher over the DECODED text stream.
944///
945/// The hard part is that a stop string need not align with token boundaries: `"\n\n"` may arrive as
946/// `"\n"` + `"\n"`, and `"END"` as `"E"` + `"ND"`. Two rules make that work:
947///
948/// 1. **Match on the accumulated tail**, not on the individual piece — so a split stop still fires.
949/// 2. **Hold back** the longest suffix of the emitted text that is a PREFIX of some stop string.
950///    Streaming clients must never see `"E"` from a token that turns out to begin `"END"`; if the
951///    next piece completes the stop, that `"E"` was never ours to send. The hold-back is bounded by
952///    `longest_stop - 1` bytes, so at most 3-4 bytes of latency in practice.
953///
954/// On a hit, the text BEFORE the stop string is emitted and the stop string itself is discarded
955/// (OpenAI does not include it in the completion).
956#[derive(Debug, Default)]
957pub struct StopMatcher {
958    stops: Vec<String>,
959    /// Text seen but not yet emitted (a possible stop prefix).
960    held: String,
961    hit: bool,
962}
963
964impl StopMatcher {
965    pub fn new(stops: Vec<String>) -> Self {
966        Self {
967            stops: stops.into_iter().filter(|s| !s.is_empty()).collect(),
968            held: String::new(),
969            hit: false,
970        }
971    }
972
973    pub fn is_active(&self) -> bool {
974        !self.stops.is_empty()
975    }
976
977    /// A stop sequence has fired: generation must halt and no further text may be emitted.
978    pub fn hit(&self) -> bool {
979        self.hit
980    }
981
982    /// Feed one decoded piece; returns the text that is now SAFE to emit (possibly empty).
983    pub fn push(&mut self, piece: &str) -> String {
984        if self.hit {
985            return String::new();
986        }
987        if self.stops.is_empty() {
988            return piece.to_string();
989        }
990        self.held.push_str(piece);
991
992        // 1. Full match anywhere in the held tail -> emit the head, drop the stop and the rest.
993        if let Some(cut) = self
994            .stops
995            .iter()
996            .filter_map(|s| self.held.find(s.as_str()))
997            .min()
998        {
999            self.hit = true;
1000            let out = self.held[..cut].to_string();
1001            self.held.clear();
1002            return out;
1003        }
1004
1005        // 2. No match: hold back the longest suffix that could still BECOME one.
1006        let hold = self.longest_partial_suffix();
1007        let split = self.held.len() - hold;
1008        let out = self.held[..split].to_string();
1009        self.held.drain(..split);
1010        out
1011    }
1012
1013    /// End of generation with no stop hit: whatever is still held was never a stop, so emit it.
1014    pub fn flush(&mut self) -> String {
1015        if self.hit {
1016            return String::new();
1017        }
1018        std::mem::take(&mut self.held)
1019    }
1020
1021    /// Length (bytes) of the longest suffix of `held` that is a proper prefix of some stop string.
1022    /// Always lands on a char boundary: a suffix of `held` equal to `stop[..n]` starts at `stop`'s
1023    /// first byte, which is a UTF-8 lead byte.
1024    fn longest_partial_suffix(&self) -> usize {
1025        let max = self
1026            .stops
1027            .iter()
1028            .map(|s| s.len())
1029            .max()
1030            .unwrap_or(0)
1031            .saturating_sub(1)
1032            .min(self.held.len());
1033        for n in (1..=max).rev() {
1034            let start = self.held.len() - n;
1035            if !self.held.is_char_boundary(start) {
1036                continue;
1037            }
1038            let tail = &self.held[start..];
1039            if self
1040                .stops
1041                .iter()
1042                .any(|s| s.as_bytes().starts_with(tail.as_bytes()))
1043            {
1044                return n;
1045            }
1046        }
1047        0
1048    }
1049}
1050
1051/// Normalise OpenAI `tool_choice` to a string the generator understands: `"auto"`/`"required"`/
1052/// `"none"` pass through; a `{"type":"function","function":{"name":N}}` object becomes `N`.
1053///
1054/// The caller has already handled ABSENT/`null` (that is "no choice" → `Ok(None)` at the call site).
1055/// This function is only reached for a PRESENT value, so an object that lacks a usable
1056/// `function.name` — or any non-string/non-object shape — is a MALFORMED forced-tool request and is
1057/// a 400 ([`ParamError`]), NOT a silent downgrade to "auto" (audit finding 6).
1058fn tool_choice_str(v: &serde_json::Value) -> Result<Option<String>, ParamError> {
1059    match v {
1060        serde_json::Value::String(s) => Ok(Some(s.clone())),
1061        serde_json::Value::Object(_) => v
1062            .get("function")
1063            .and_then(|f| f.get("name"))
1064            .and_then(|n| n.as_str())
1065            .map(|s| Some(s.to_owned()))
1066            .ok_or_else(|| ParamError {
1067                param: "tool_choice",
1068                message: "tool_choice object must have a string `function.name`".into(),
1069            }),
1070        _ => Err(ParamError {
1071            param: "tool_choice",
1072            message: "tool_choice must be \"auto\"/\"required\"/\"none\" or a function object"
1073                .into(),
1074        }),
1075    }
1076}
1077
1078/// The three `tool_choice` values that are POLICIES rather than tool names.
1079const TOOL_CHOICE_POLICIES: [&str; 3] = ["auto", "none", "required"];
1080
1081/// The request's `tools`, if any, are an array of function tools each with a string
1082/// `function.name` — the one field every use of a tool reads. A malformed tool is the request's
1083/// fault, refused here as a `400` naming `tools` rather than failing a grammar build later.
1084fn validate_tools(tools: Option<&serde_json::Value>) -> Result<(), ParamError> {
1085    let bad = |message: String| ParamError {
1086        param: "tools",
1087        message,
1088    };
1089    let tools = match tools {
1090        None | Some(serde_json::Value::Null) => return Ok(()),
1091        Some(serde_json::Value::Array(a)) => a,
1092        Some(_) => return Err(bad("tools must be an array".into())),
1093    };
1094    for (i, t) in tools.iter().enumerate() {
1095        if t.get("function")
1096            .and_then(|f| f.get("name"))
1097            .and_then(serde_json::Value::as_str)
1098            .is_none()
1099        {
1100            return Err(bad(format!("tools[{i}] has no string `function.name`")));
1101        }
1102    }
1103    Ok(())
1104}
1105
1106/// Cross-check a normalised `tool_choice` against the request's `tools`, which
1107/// [`tool_choice_str`] cannot do on its own — it never sees `tools`.
1108///
1109/// Two holes this closes, both of which used to produce ordinary unconstrained assistant text
1110/// (backlog B22). `OaiRenderer::tool_constraint` returns `Ok(None)` the moment `tools` is absent,
1111/// without ever looking at `tool_choice`, and `run_chat` reads that `None` as "no constraint
1112/// wanted":
1113///
1114/// - **A forced choice with no `tools`.** `"tool_choice":"required"` and no tools is a request the
1115///   server cannot honour — there is nothing to call — so it is a 400 rather than a silent
1116///   downgrade to free text. `"none"` is exempt: it asks for no tool call, which is satisfiable
1117///   with no tools, and `"auto"` means "your discretion".
1118/// - **A name that is not in `tools`.** A misspelled function name reached the generator as a
1119///   forced choice and then vanished. With `tools` present it is worse than nothing: the name
1120///   filter behind `OaiRenderer::tool_constraint` yields an empty array and
1121///   `forced_tool_call_grammar` builds `{"anyOf": []}`, a grammar that matches no output at all.
1122///
1123/// Same policy as the existing malformed-object 400s: a forced tool call the server cannot deliver
1124/// is an error, never a quiet fallback to "auto" (audit finding 6).
1125fn validate_tool_choice(
1126    tool_choice: Option<&str>,
1127    tools: Option<&serde_json::Value>,
1128) -> Result<(), ParamError> {
1129    let Some(choice) = tool_choice else {
1130        return Ok(());
1131    };
1132    if TOOL_CHOICE_POLICIES.contains(&choice) && choice != "required" {
1133        return Ok(());
1134    }
1135    // `tools` may be absent, `null`, or an empty array — all "no tools offered".
1136    let names: Vec<&str> = tools
1137        .and_then(|t| t.as_array())
1138        .map(|a| {
1139            a.iter()
1140                .filter_map(|t| t.get("function")?.get("name")?.as_str())
1141                .collect()
1142        })
1143        .unwrap_or_default();
1144    if names.is_empty() {
1145        return Err(ParamError {
1146            param: "tool_choice",
1147            message: format!(
1148                "tool_choice {choice:?} requires a non-empty `tools` array; none was supplied"
1149            ),
1150        });
1151    }
1152    if choice == "required" || names.contains(&choice) {
1153        return Ok(());
1154    }
1155    Err(ParamError {
1156        param: "tool_choice",
1157        message: format!(
1158            "tool_choice {choice:?} names no tool in `tools` (have: {})",
1159            names.join(", ")
1160        ),
1161    })
1162}
1163
1164/// A single chat message.  `content` may be a JSON string or a content-part array.
1165#[derive(Debug, Deserialize, Serialize)]
1166pub struct ChatMessageDto {
1167    pub role: String,
1168    #[serde(default)]
1169    pub content: Option<serde_json::Value>,
1170    /// Assistant's prior tool calls (OpenAI `[{id,type,function:{name,arguments}}]`), replayed on the
1171    /// next turn so the model sees its own calls.
1172    #[serde(default)]
1173    pub tool_calls: Option<serde_json::Value>,
1174    #[serde(default)]
1175    pub tool_call_id: Option<String>,
1176    #[serde(default)]
1177    pub name: Option<String>,
1178}
1179
1180// ---------------------------------------------------------------------------
1181// Response DTOs — /v1/models
1182// ---------------------------------------------------------------------------
1183
1184#[derive(Debug, Serialize)]
1185pub struct ModelsResponse {
1186    pub object: &'static str,
1187    pub data: Vec<ModelCard>,
1188}
1189
1190#[derive(Debug, Serialize)]
1191pub struct ModelCard {
1192    pub id: String,
1193    pub object: &'static str,
1194    pub owned_by: &'static str,
1195}
1196
1197// ---------------------------------------------------------------------------
1198// Response DTOs — /v1/chat/completions  (non-streaming)
1199// ---------------------------------------------------------------------------
1200
1201#[derive(Debug, Serialize)]
1202pub struct ChatCompletionResponse {
1203    pub id: String,
1204    pub object: &'static str,
1205    pub created: i64,
1206    pub model: String,
1207    pub choices: Vec<CompletionChoice>,
1208    pub usage: UsageInfo,
1209}
1210
1211#[derive(Debug, Serialize)]
1212pub struct CompletionChoice {
1213    pub index: u32,
1214    pub message: AssistantMessage,
1215    #[serde(skip_serializing_if = "Option::is_none")]
1216    pub logprobs: Option<ChatLogprobs>,
1217    pub finish_reason: String,
1218}
1219
1220#[derive(Debug, Serialize)]
1221pub struct AssistantMessage {
1222    pub role: &'static str,
1223    pub content: Option<String>,
1224    #[serde(skip_serializing_if = "Option::is_none")]
1225    pub reasoning_content: Option<String>,
1226    #[serde(skip_serializing_if = "Option::is_none")]
1227    pub tool_calls: Option<Vec<OAIToolCall>>,
1228}
1229
1230/// OpenAI-shaped tool call (used in both streaming and non-streaming responses).
1231#[derive(Debug, Clone, Serialize)]
1232pub struct OAIToolCall {
1233    pub index: usize,
1234    pub id: String,
1235    #[serde(rename = "type")]
1236    pub kind: &'static str,
1237    pub function: OAIFunction,
1238}
1239
1240#[derive(Debug, Clone, Serialize)]
1241pub struct OAIFunction {
1242    pub name: String,
1243    pub arguments: String,
1244}
1245
1246#[derive(Debug, Serialize)]
1247pub struct UsageInfo {
1248    pub prompt_tokens: u32,
1249    pub completion_tokens: u32,
1250    pub total_tokens: u32,
1251    pub prompt_tokens_details: PromptTokensDetails,
1252}
1253
1254#[derive(Debug, Serialize)]
1255pub struct PromptTokensDetails {
1256    pub cached_tokens: u32,
1257}
1258
1259impl UsageInfo {
1260    /// The `usage` block for one finished generation — shared by the non-streaming body and the
1261    /// streamed `include_usage` chunk, so the two cannot report different numbers.
1262    pub fn from_outcome(outcome: &ChatOutcome) -> Self {
1263        Self {
1264            prompt_tokens: outcome.prompt_tokens,
1265            completion_tokens: outcome.completion_tokens,
1266            total_tokens: outcome
1267                .prompt_tokens
1268                .saturating_add(outcome.completion_tokens),
1269            prompt_tokens_details: PromptTokensDetails {
1270                cached_tokens: outcome.cached_tokens,
1271            },
1272        }
1273    }
1274}
1275
1276// ---------------------------------------------------------------------------
1277// Response DTOs — /v1/chat/completions  (streaming chunks)
1278// ---------------------------------------------------------------------------
1279
1280#[derive(Debug, Serialize)]
1281pub struct ChatCompletionChunk {
1282    pub id: String,
1283    pub object: &'static str,
1284    pub created: i64,
1285    pub model: String,
1286    pub choices: Vec<ChunkChoice>,
1287    /// Only on the final `stream_options.include_usage` chunk.
1288    #[serde(skip_serializing_if = "Option::is_none")]
1289    pub usage: Option<UsageInfo>,
1290}
1291
1292#[derive(Debug, Serialize)]
1293pub struct ChunkChoice {
1294    pub index: u32,
1295    pub delta: DeltaPayload,
1296    #[serde(skip_serializing_if = "Option::is_none")]
1297    pub logprobs: Option<ChatLogprobs>,
1298    pub finish_reason: Option<String>,
1299}
1300
1301/// The `delta` field inside a streaming chunk.  Fields absent when `None`.
1302#[derive(Debug, Default, Serialize)]
1303pub struct DeltaPayload {
1304    #[serde(skip_serializing_if = "Option::is_none")]
1305    pub role: Option<String>,
1306    #[serde(skip_serializing_if = "Option::is_none")]
1307    pub content: Option<String>,
1308    #[serde(skip_serializing_if = "Option::is_none")]
1309    pub reasoning_content: Option<String>,
1310    #[serde(skip_serializing_if = "Option::is_none")]
1311    pub tool_calls: Option<Vec<OAIToolCall>>,
1312}
1313
1314// ---------------------------------------------------------------------------
1315// Observability
1316// ---------------------------------------------------------------------------
1317
1318/// Per-request id: a process-monotonic counter, NOT a timestamp.
1319///
1320/// It is deliberately not derived from the wall clock. Two requests admitted in the same
1321/// millisecond (routine under `--parallel N`) would collide on a `now()`-based id, and the whole
1322/// value of the id is that the arrival line and the completion line for ONE request can be joined
1323/// in a log that has N of them interleaved. It is also NOT the wire `id` ([`make_id`]): that one is
1324/// a client-facing `chatcmpl-…` string, and pinning a log key to a wire format is how the log
1325/// breaks when the wire format moves.
1326static REQ_SEQ: AtomicU64 = AtomicU64::new(1);
1327
1328fn next_req_id() -> u64 {
1329    REQ_SEQ.fetch_add(1, Ordering::Relaxed)
1330}
1331
1332/// The server-wide counters behind the periodic throughput line, and the two gauges behind
1333/// `active`/`queued`.
1334///
1335/// **Everything here is an atomic and nothing here is a lock.** The only counter touched from
1336/// inside a generation is [`Self::bump_gen`], one relaxed `fetch_add` per emitted delta — the
1337/// decode loop must not acquire anything, because it is holding the GPU baton for every other
1338/// sequence behind it (the same reason the SSE channel is unbounded).
1339///
1340/// The four `interval_*` counters are DRAINED (swapped to zero) by each report, which is what makes
1341/// the reported numbers cover the interval rather than the process lifetime. The periodic line
1342/// never reads a cumulative total: a total nobody drains is the thing that silently turns a rate
1343/// into an average-since-boot. The lifetime counters in [`Self::lifetime`] exist for `/metrics`
1344/// only, where the scraper takes the rate itself.
1345#[derive(Debug, Default)]
1346struct ServeStats {
1347    /// Prompt tokens PREFILLED in this interval. Folded once per request, at completion — the real
1348    /// count from [`ChatOutcome`], which is not knowable before the generator has tokenized.
1349    interval_prompt_tokens: AtomicU64,
1350    /// Tokens GENERATED in this interval, live. Incremented per delta while a generation runs (so a
1351    /// long request shows up in the intervals it spans, not only in the one it ends in) and
1352    /// RECONCILED at completion against `ChatOutcome::completion_tokens`, which is authoritative:
1353    /// a delta is a text piece and is only approximately a token (a think-tag boundary can split
1354    /// or merge one). The correction is signed, hence `i64`.
1355    interval_gen_tokens: AtomicI64,
1356    /// Requests that COMPLETED in this interval (success or failure).
1357    interval_completed: AtomicU64,
1358    /// Requests that FAILED in this interval — a subset of `interval_completed`.
1359    interval_failed: AtomicU64,
1360    /// Gauge: requests generating right now (holding a slot permit).
1361    active: AtomicU64,
1362    /// Gauge: requests admitted by the handler but still waiting for a slot permit.
1363    queued: AtomicU64,
1364    /// Which interval is currently open. Incremented by every [`Self::drain`].
1365    ///
1366    /// A completion's correction is only meaningful against the deltas it corrects, and those
1367    /// deltas may already have been drained and REPORTED. Stamping each request's live count with
1368    /// the window it landed in is what lets [`Self::fold_completion`] tell "still correctable" from
1369    /// "already published" (backlog B24).
1370    window: AtomicU64,
1371    /// Never-drained counters behind `/metrics`.
1372    lifetime: metrics::Lifetime,
1373}
1374
1375impl ServeStats {
1376    /// One decoded piece. The ONE call on the hot path — a single relaxed add.
1377    fn bump_gen(&self, n: i64) {
1378        self.interval_gen_tokens.fetch_add(n, Ordering::Relaxed);
1379    }
1380
1381    /// The interval currently accepting tokens.
1382    fn window(&self) -> u64 {
1383        self.window.load(Ordering::Relaxed)
1384    }
1385
1386    /// Fold one finished request's exact tallies in, once.
1387    ///
1388    /// **The correction is clamped to what this request still has in the OPEN window.** Deltas are
1389    /// only an estimate of tokens (a think-tag boundary can split or merge one), so completion
1390    /// reconciles against `ChatOutcome`'s authoritative count. But a retraction cannot reach a
1391    /// window that has already been drained and logged, and subtracting it from the current one
1392    /// takes the tokens out of whatever OTHER request is generating now — which is how a −1 from
1393    /// request A turned request B's three real tokens into two (B24, proved).
1394    ///
1395    /// So a negative correction is applied only against `rec.deltas_in_window`, and only while
1396    /// `rec.window` is still open. Anything older stays as it was reported: an interval line is a
1397    /// statement about a window that has closed, and the honest move is to leave it alone rather
1398    /// than to bill the difference to somebody else. A POSITIVE correction is always applied — it
1399    /// is new information about tokens nobody has counted yet, the same shape as `prompt_tokens`
1400    /// arriving at completion.
1401    fn fold_completion(&self, rec: &ReqRecord) {
1402        self.interval_prompt_tokens
1403            .fetch_add(u64::from(rec.prompt_tokens), Ordering::Relaxed);
1404        let correction = i64::from(rec.gen_tokens) - rec.deltas as i64;
1405        if correction > 0 {
1406            self.bump_gen(correction);
1407        } else if correction < 0 && rec.window == self.window() {
1408            // Retract at most what this request itself put into the window that is still open.
1409            let retractable = rec.deltas_in_window.min(i64::MAX as u64) as i64;
1410            self.bump_gen(-correction.abs().min(retractable));
1411        }
1412        self.interval_completed.fetch_add(1, Ordering::Relaxed);
1413        self.lifetime.fold_completion(rec);
1414    }
1415
1416    /// Fold one request that ended in an error. Its partial deltas are already counted; there is no
1417    /// [`ChatOutcome`] to reconcile against, so nothing is corrected.
1418    fn fold_failure(&self) {
1419        self.interval_completed.fetch_add(1, Ordering::Relaxed);
1420        self.interval_failed.fetch_add(1, Ordering::Relaxed);
1421        self.lifetime.fold_failure();
1422    }
1423
1424    /// Take the interval counters (resetting them to zero) and sample the gauges. `elapsed` is the
1425    /// REAL time since the last drain, not the nominal period — a tick that ran late must not
1426    /// inflate the rate it reports.
1427    fn drain(&self, elapsed: Duration) -> StatsWindow {
1428        // Close the current window BEFORE taking the counters: from here on, a completion whose
1429        // deltas landed in the old window can no longer retract them (see `fold_completion`).
1430        self.window.fetch_add(1, Ordering::Relaxed);
1431        StatsWindow {
1432            elapsed,
1433            prompt_tokens: self.interval_prompt_tokens.swap(0, Ordering::Relaxed),
1434            gen_tokens: self.interval_gen_tokens.swap(0, Ordering::Relaxed).max(0) as u64,
1435            completed: self.interval_completed.swap(0, Ordering::Relaxed),
1436            failed: self.interval_failed.swap(0, Ordering::Relaxed),
1437            active: self.active.load(Ordering::Relaxed),
1438            queued: self.queued.load(Ordering::Relaxed),
1439            busy_slots: 0,
1440            total_slots: 0,
1441        }
1442    }
1443}
1444
1445/// One interval's drained counters — the whole input to one periodic log line.
1446#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1447struct StatsWindow {
1448    elapsed: Duration,
1449    prompt_tokens: u64,
1450    gen_tokens: u64,
1451    completed: u64,
1452    failed: u64,
1453    active: u64,
1454    queued: u64,
1455    /// Slot permits held across every hosted model — KV slot occupancy.
1456    busy_slots: u64,
1457    /// Slot permits in existence across every hosted model (the sum of `--parallel N`).
1458    total_slots: u64,
1459}
1460
1461impl StatsWindow {
1462    /// Was there anything to report? An interval in which the server did nothing at all emits NO
1463    /// line — the periodic report is activity-only, deliberately not a heartbeat, so an idle server
1464    /// leaves a clean log. A request that is mid-generation counts as activity (`active > 0`) even
1465    /// when it has produced no token yet, so a long single request still reports every interval it
1466    /// spans.
1467    fn has_activity(&self) -> bool {
1468        self.prompt_tokens > 0
1469            || self.gen_tokens > 0
1470            || self.completed > 0
1471            || self.active > 0
1472            || self.queued > 0
1473    }
1474
1475    /// Prompt tokens ingested per WALL second of the interval.
1476    ///
1477    /// This is the server's aggregate ingest throughput, NOT one model's prefill speed: the
1478    /// denominator is the interval, including the time the server spent decoding or idle. The
1479    /// per-request completion line carries the other number (that request's `prompt_tokens / TTFT`),
1480    /// and the two are supposed to differ — one answers "how much is this box doing", the other
1481    /// "how fast is this model".
1482    fn prefill_tps(&self) -> f64 {
1483        per_second(self.prompt_tokens, self.elapsed)
1484    }
1485
1486    /// Tokens generated per WALL second of the interval — aggregate across every in-flight request.
1487    /// Same scope note as [`Self::prefill_tps`].
1488    fn decode_tps(&self) -> f64 {
1489        per_second(self.gen_tokens, self.elapsed)
1490    }
1491}
1492
1493/// `n` per second over `d`. A zero (or absurdly small) window yields 0.0 rather than an infinity —
1494/// a log line reading `inf` is worse than one reading 0.
1495fn per_second(n: u64, d: Duration) -> f64 {
1496    let secs = d.as_secs_f64();
1497    if secs > 0.0 {
1498        n as f64 / secs
1499    } else {
1500        0.0
1501    }
1502}
1503
1504/// RAII gauge for [`ServeStats::queued`]: a request waiting for a slot permit. Dropped the moment
1505/// the permit is acquired (or the acquire fails during shutdown).
1506///
1507/// A guard rather than a matching `fetch_sub` because there are three ways out of the wait — got
1508/// the permit, the semaphore closed, the task was dropped — and a gauge that leaks on one of them
1509/// reads as a permanently-queued request forever after.
1510struct QueuedGuard(Arc<ServeStats>);
1511
1512impl QueuedGuard {
1513    fn new(stats: Arc<ServeStats>) -> Self {
1514        stats.queued.fetch_add(1, Ordering::Relaxed);
1515        Self(stats)
1516    }
1517}
1518
1519impl Drop for QueuedGuard {
1520    fn drop(&mut self) {
1521        self.0.queued.fetch_sub(1, Ordering::Relaxed);
1522    }
1523}
1524
1525/// RAII gauge for [`ServeStats::active`]: a request holding a slot permit and generating. Moved
1526/// INTO the blocking task alongside the permit, so it is released on exactly the same events the
1527/// permit is — including an unwinding panic inside the decode closure.
1528struct ActiveGuard(Arc<ServeStats>);
1529
1530impl ActiveGuard {
1531    fn new(stats: Arc<ServeStats>) -> Self {
1532        stats.active.fetch_add(1, Ordering::Relaxed);
1533        Self(stats)
1534    }
1535}
1536
1537impl Drop for ActiveGuard {
1538    fn drop(&mut self) {
1539        self.0.active.fetch_sub(1, Ordering::Relaxed);
1540    }
1541}
1542
1543/// The per-request tally kept INSIDE the generation, as plain locals in the blocking task. It is
1544/// folded into [`ServeStats`] once, at completion — the request's own timing needs no sharing, and
1545/// making it shared would put a second atomic (or worse) on the decode path for nothing.
1546#[derive(Debug)]
1547struct ReqTally {
1548    started: Instant,
1549    /// When the FIRST delta arrived: the boundary between prefill and decode. `None` means the
1550    /// generation produced nothing.
1551    first_delta: Option<Instant>,
1552    /// Text deltas seen (content + reasoning). Reconciled against the real token count at the end.
1553    deltas: u64,
1554    /// The [`ServeStats`] window `deltas_in_window` is counted against.
1555    window: u64,
1556    /// Deltas this request has contributed to `window` — i.e. how much of the still-open interval
1557    /// is this request's, and therefore the most a completion correction may retract from it (B24).
1558    deltas_in_window: u64,
1559}
1560
1561impl ReqTally {
1562    fn new() -> Self {
1563        Self {
1564            started: Instant::now(),
1565            first_delta: None,
1566            deltas: 0,
1567            window: 0,
1568            deltas_in_window: 0,
1569        }
1570    }
1571
1572    /// Called from the generator's `on_delta` callback for a TEXT delta. A few increments, one
1573    /// relaxed atomic load and one relaxed atomic add — no lock, no allocation, nothing that can
1574    /// block the decode loop.
1575    ///
1576    /// The load is what keeps `deltas_in_window` honest across a drain: a reporter tick between two
1577    /// deltas moves the window, and this request's share of the new one restarts at zero. The load
1578    /// and the add are not atomic together, so a drain landing exactly between them can misplace a
1579    /// single token; that is one token on an interval line, and closing it would mean a lock on the
1580    /// decode path, which is the one thing this whole structure exists to avoid.
1581    fn on_text_delta(&mut self, stats: &ServeStats) {
1582        if self.first_delta.is_none() {
1583            self.first_delta = Some(Instant::now());
1584        }
1585        let w = stats.window();
1586        if w != self.window {
1587            self.window = w;
1588            self.deltas_in_window = 0;
1589        }
1590        self.deltas += 1;
1591        self.deltas_in_window += 1;
1592        stats.bump_gen(1);
1593    }
1594
1595    /// Close the tally out against the generator's authoritative counts.
1596    fn finish(&self, outcome: ChatOutcome, finish: Finish) -> ReqRecord {
1597        let total = self.started.elapsed();
1598        // TTFT is the prefill boundary. With no delta at all (an empty completion) there is no
1599        // boundary to draw, so the whole request counts as prefill and decode time is zero.
1600        let prefill = self
1601            .first_delta
1602            .map_or(total, |t| t.saturating_duration_since(self.started));
1603        ReqRecord {
1604            // The tokens this request actually PREFILLED: what its prefill time was spent on, and
1605            // what the throughput counters have always summed. A cached prefix cost nothing.
1606            prompt_tokens: outcome.prompt_tokens.saturating_sub(outcome.cached_tokens),
1607            gen_tokens: outcome.completion_tokens,
1608            deltas: self.deltas,
1609            window: self.window,
1610            deltas_in_window: self.deltas_in_window,
1611            prefill,
1612            decode: total.saturating_sub(prefill),
1613            total,
1614            finish,
1615        }
1616    }
1617}
1618
1619/// One finished request, as the completion log line and [`ServeStats::fold_completion`] see it.
1620#[derive(Debug, Clone, Copy)]
1621struct ReqRecord {
1622    prompt_tokens: u32,
1623    gen_tokens: u32,
1624    deltas: u64,
1625    /// The stats window this request's last deltas landed in — see [`ServeStats::fold_completion`].
1626    window: u64,
1627    /// How many of `deltas` were counted into `window`.
1628    deltas_in_window: u64,
1629    /// Time to the first delta — the prefill.
1630    prefill: Duration,
1631    /// From the first delta to the end — the decode.
1632    decode: Duration,
1633    total: Duration,
1634    finish: Finish,
1635}
1636
1637impl ReqRecord {
1638    /// THIS request's prefill speed: prompt tokens over its time-to-first-delta. A per-request
1639    /// number, unlike [`StatsWindow::prefill_tps`].
1640    fn prefill_tps(&self) -> f64 {
1641        per_second(u64::from(self.prompt_tokens), self.prefill)
1642    }
1643
1644    /// THIS request's decode speed: generated tokens over the time after the first delta.
1645    fn decode_tps(&self) -> f64 {
1646        per_second(u64::from(self.gen_tokens), self.decode)
1647    }
1648}
1649
1650/// Emit one request's completion line at INFO. The counterpart to the arrival line
1651/// ([`log_request_start`]), joined to it by `req`.
1652fn log_request_done(req_id: u64, model: &str, stream: bool, rec: &ReqRecord) {
1653    tracing::info!(
1654        req = req_id,
1655        model,
1656        stream,
1657        prompt_tokens = rec.prompt_tokens,
1658        gen_tokens = rec.gen_tokens,
1659        prefill_tps = format_args!("{:.1}", rec.prefill_tps()),
1660        decode_tps = format_args!("{:.1}", rec.decode_tps()),
1661        total_ms = format_args!("{:.0}", rec.total.as_secs_f64() * 1000.0),
1662        finish = rec.finish.as_str(),
1663        "request done"
1664    );
1665}
1666
1667/// One request's arrival, as its start line reports it.
1668struct RequestStart<'a> {
1669    /// The route that generates; two exist and the log line names which.
1670    route: &'a str,
1671    model: &'a str,
1672    messages: usize,
1673    prompt_chars: usize,
1674    prompt_tokens: Option<u32>,
1675    max_tokens: Option<u32>,
1676    stream: bool,
1677}
1678
1679/// Emit one request's arrival line at INFO.
1680///
1681/// `prompt_tokens` is the rendered prompt's real count from [`ChatGenerator::prepare`], and
1682/// absent for a generator that cannot count before generating — `prompt_chars`, the size of the
1683/// messages, is the proxy that is always there. The completion line carries the count
1684/// [`ChatOutcome`] reports either way.
1685///
1686/// **No prompt text, ever.** Counts only. Putting user prompt text into an operator's logs is a
1687/// privacy decision that has been made in the negative — do not add a preview here, not even
1688/// truncated, not even behind a flag.
1689fn log_request_start(req_id: u64, start: RequestStart<'_>) {
1690    let RequestStart {
1691        route,
1692        model,
1693        messages,
1694        prompt_chars,
1695        prompt_tokens,
1696        max_tokens,
1697        stream,
1698    } = start;
1699    tracing::info!(
1700        req = req_id,
1701        route,
1702        model,
1703        messages,
1704        prompt_chars,
1705        // Left off the line, rather than printed as a placeholder, when the generator cannot count.
1706        prompt_tokens,
1707        max_tokens = ?max_tokens,
1708        stream,
1709        "request start"
1710    );
1711}
1712
1713/// The configured period for the periodic throughput line, or `None` when it is switched OFF.
1714///
1715/// `serve.stats_interval_secs` (`INFR_SERVE_STATS_SECS`), where `0` means "no periodic line" —
1716/// the same "0 disables" grammar as [`request_timeout`], and for the same reason: an operator
1717/// piping this server's logs somewhere expensive needs a way to say no from the environment, over
1718/// a config file that said yes.
1719fn stats_interval(cfg: &Config) -> Option<Duration> {
1720    let secs = cfg.serve.stats_interval_secs;
1721    (secs > 0).then(|| Duration::from_secs(secs))
1722}
1723
1724/// The periodic throughput reporter: drain the interval counters every `period` and, IF anything
1725/// happened, log one line.
1726///
1727/// **Shutdown.** It polls the same process-wide latch [`shutdown_latched`] does, at the same 50 ms
1728/// granularity, so a Ctrl-C ends it at the next poll rather than up to a full period later — and it
1729/// is a plain tokio task, which cannot hold the process open by itself: when `serve_state` returns
1730/// the runtime drops and the task goes with it. It emits one FINAL drain on the way out so the
1731/// tokens generated in the last partial interval are not silently dropped.
1732async fn stats_reporter(state: AppState, period: Duration) {
1733    const POLL: Duration = Duration::from_millis(50);
1734    let mut last = Instant::now();
1735    loop {
1736        tokio::time::sleep(POLL).await;
1737        let shutting_down = infr_core::shutdown::shutdown_requested();
1738        if !shutting_down && last.elapsed() < period {
1739            continue;
1740        }
1741        let mut window = state.stats.drain(last.elapsed());
1742        (window.busy_slots, window.total_slots) = state.slot_occupancy();
1743        last = Instant::now();
1744        if window.has_activity() {
1745            tracing::info!(
1746                interval_s = format_args!("{:.1}", window.elapsed.as_secs_f64()),
1747                prefill_tps = format_args!("{:.1}", window.prefill_tps()),
1748                decode_tps = format_args!("{:.1}", window.decode_tps()),
1749                gen_tokens = window.gen_tokens,
1750                prompt_tokens = window.prompt_tokens,
1751                completed = window.completed,
1752                failed = window.failed,
1753                active = window.active,
1754                queued = window.queued,
1755                kv_slots = format_args!("{}/{}", window.busy_slots, window.total_slots),
1756                "serve stats"
1757            );
1758        }
1759        if shutting_down {
1760            return;
1761        }
1762    }
1763}
1764
1765// ---------------------------------------------------------------------------
1766// App state
1767// ---------------------------------------------------------------------------
1768
1769/// One hosted model: its wire id, its generator, and its OWN admission semaphore.
1770///
1771/// `engine` is an `Option<Arc<dyn ChatGenerator>>` so an entry can exist without a live model (the
1772/// headless test/`/v1/models` state). It is an `Arc`, NOT an `Arc<Mutex<_>>`: generation runs
1773/// concurrently and the generator synchronises itself (see [`ChatGenerator`]'s `&self` contract).
1774///
1775/// `slots` is PER-MODEL admission control — one permit per KV slot (`--parallel N`). A request
1776/// takes a permit for the whole of its generation and returns it at the end, so at most N generate
1777/// concurrently on THAT model and the N+1'th QUEUES (tokio's semaphore is FIFO) rather than being
1778/// rejected. Per-model (not global) is the point of the multi-model server: a model on the discrete
1779/// GPU and a model on the iGPU each admit their own N independently — one busy model never starves
1780/// another that lives on a different device.
1781#[derive(Clone)]
1782struct ModelEntry {
1783    id: Arc<str>,
1784    engine: Option<Arc<dyn ChatGenerator>>,
1785    slots: Arc<Semaphore>,
1786    /// How many permits `slots` was created with (`--parallel N`, floored at 1). `Semaphore` reports
1787    /// how many are AVAILABLE but not how many exist, and occupancy is the difference — so the
1788    /// capacity has to be remembered here or the periodic line cannot say `2/4`.
1789    capacity: usize,
1790    /// Admission to [`ChatGenerator::prepare`], with as many permits as `slots`. Preparation —
1791    /// template render, tokenization, grammar compile — runs on a blocking thread before a request
1792    /// queues for a slot, so without a bound a burst of requests would be that many threads
1793    /// competing with generation. The model can generate no more than `capacity` requests at
1794    /// once, so preparing more than that at once only prepares work that must wait anyway.
1795    prepares: Arc<Semaphore>,
1796}
1797
1798impl ModelEntry {
1799    fn new(id: &str, engine: Option<Arc<dyn ChatGenerator>>, n_parallel: usize) -> Self {
1800        let capacity = n_parallel.max(1);
1801        Self {
1802            id: Arc::from(id),
1803            engine,
1804            slots: Arc::new(Semaphore::new(capacity)),
1805            capacity,
1806            prepares: Arc::new(Semaphore::new(capacity)),
1807        }
1808    }
1809
1810    /// Slot permits held right now: what the semaphore is NOT handing out, which is exactly the
1811    /// set of this model's generations in flight.
1812    fn busy(&self) -> usize {
1813        self.capacity - self.slots.available_permits().min(self.capacity)
1814    }
1815}
1816
1817/// Shared server state — a non-empty, ordered set of hosted `ModelEntry`s. A request is routed to
1818/// the entry whose `id` matches its `model` field; an unknown/empty `model` falls to the DEFAULT
1819/// (the first entry). The single-model server is just the one-entry case, so its behaviour — and the
1820/// hot path — is byte-identical to before this became multi-model.
1821#[derive(Clone)]
1822pub struct AppState {
1823    /// Invariant: non-empty. `models[0]` is the default route.
1824    models: Arc<Vec<ModelEntry>>,
1825    /// The resolved process configuration. The handler reads `serve.api_key` and
1826    /// `serve.max_tokens_cap` off it instead of the environment; it is an EXPLICIT constructor
1827    /// parameter on every entry point that can host a real model, so an embedder cannot silently
1828    /// end up with auth disabled by forgetting to pass one.
1829    cfg: Arc<Config>,
1830    /// Server-wide request/throughput counters (B10). Shared with the periodic reporter task
1831    /// [`stats_reporter`] that `serve_state` spawns; a state built for tests simply has no reporter
1832    /// draining it.
1833    stats: Arc<ServeStats>,
1834    /// When this state was built, for `/status`'s uptime.
1835    started: Instant,
1836    /// The address the listener is bound to, which the `Host` check (`host::host_gate`) reads.
1837    /// `None` for a router served some other way, which is then checked only when
1838    /// `serve.allowed_hosts` is set.
1839    bind: Option<SocketAddr>,
1840}
1841
1842impl AppState {
1843    /// Wrap a single loaded generator for production use with `n_parallel` concurrent slots — the
1844    /// single-model server (the overwhelming common case). Equivalent to a one-entry
1845    /// [`multi`](Self::multi).
1846    pub fn new(
1847        generator: Arc<dyn ChatGenerator>,
1848        model_id: impl Into<String>,
1849        n_parallel: usize,
1850        cfg: Arc<Config>,
1851    ) -> Self {
1852        Self {
1853            models: Arc::new(vec![ModelEntry::new(
1854                &model_id.into(),
1855                Some(generator),
1856                n_parallel,
1857            )]),
1858            cfg,
1859            stats: Arc::default(),
1860            started: Instant::now(),
1861            bind: None,
1862        }
1863    }
1864
1865    /// Host SEVERAL models at once, each with its OWN generator and per-model slot count. Each
1866    /// `(model_id, generator, n_parallel)` becomes a routable entry; the FIRST is the default route
1867    /// (used for a request with an unknown or empty `model`). This is the multi-device host: pass a
1868    /// generator pinned to each physical GPU and the server routes by model name — see `infr multi`.
1869    ///
1870    /// Panics if `entries` is empty (the state invariant is a non-empty model set); the CLI never
1871    /// calls it with none.
1872    pub fn multi(entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>, cfg: Arc<Config>) -> Self {
1873        assert!(
1874            !entries.is_empty(),
1875            "AppState::multi needs at least one model"
1876        );
1877        let models = entries
1878            .into_iter()
1879            .map(|(id, gen, n)| ModelEntry::new(&id, Some(gen), n))
1880            .collect();
1881        Self {
1882            models: Arc::new(models),
1883            cfg,
1884            stats: Arc::default(),
1885            started: Instant::now(),
1886            bind: None,
1887        }
1888    }
1889
1890    /// No-engine state — for /health, /v1/models, and serialisation tests. Takes the config too,
1891    /// so an auth/cap test drives `serve.*` through a `Config` value rather than the environment
1892    /// (R7).
1893    pub fn headless(model_id: impl Into<String>, cfg: Arc<Config>) -> Self {
1894        Self {
1895            models: Arc::new(vec![ModelEntry::new(&model_id.into(), None, 1)]),
1896            cfg,
1897            stats: Arc::default(),
1898            started: Instant::now(),
1899            bind: None,
1900        }
1901    }
1902
1903    /// KV slot occupancy across every hosted model: `(busy, total)` permits.
1904    fn slot_occupancy(&self) -> (u64, u64) {
1905        self.models.iter().fold((0, 0), |(busy, total), m| {
1906            (busy + m.busy() as u64, total + m.capacity as u64)
1907        })
1908    }
1909
1910    /// Route a request's `model` field to a hosted entry: an exact id match, else the default
1911    /// (first) entry — mirroring OpenAI servers, which never 404 on the model name. Returns a clone
1912    /// of the entry's `Arc` handles (cheap) so the caller owns them across the `spawn_blocking`.
1913    fn route(&self, requested: &str) -> ModelEntry {
1914        self.models
1915            .iter()
1916            .find(|m| &*m.id == requested)
1917            .unwrap_or(&self.models[0])
1918            .clone()
1919    }
1920}
1921
1922// ---------------------------------------------------------------------------
1923// Router
1924// ---------------------------------------------------------------------------
1925
1926/// Build the axum [`Router`].  Extracted so tests can call it with a [`AppState::headless`] state.
1927///
1928/// The `Host` check is layered over every route but `/health`, which is added after it: a layer
1929/// wraps only the routes already on the router.
1930pub fn build_router(state: AppState) -> Router {
1931    let body_limit = max_body_bytes(&state.cfg);
1932    Router::new()
1933        .route("/v1/models", get(models_handler))
1934        .route("/metrics", get(metrics::metrics_handler))
1935        .route("/status", get(status::status_handler))
1936        .route(
1937            "/v1/chat/completions",
1938            post(chat_completions_handler)
1939                .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
1940        )
1941        .route(
1942            "/v1/completions",
1943            post(completions::completions_handler)
1944                .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
1945        )
1946        .layer(middleware::from_fn_with_state(
1947            state.clone(),
1948            host::host_gate,
1949        ))
1950        .route("/health", get(health_handler))
1951        .layer(DefaultBodyLimit::max(body_limit))
1952        .with_state(state)
1953}
1954
1955/// [`auth_gate`] as a layer, for the route that takes a body. A handler's extractors all run
1956/// before its first statement, so a check inside the handler comes AFTER the JSON body has been
1957/// buffered and parsed; an unauthenticated client could make the server do that work up to the
1958/// body limit, or hold the request open by never finishing its body. As a layer it runs on the
1959/// headers alone.
1960async fn require_auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
1961    if let Some(denied) = auth_gate(&state.cfg, req.headers()) {
1962        return denied;
1963    }
1964    next.run(req).await
1965}
1966
1967// ---------------------------------------------------------------------------
1968// Server entry point
1969// ---------------------------------------------------------------------------
1970
1971/// Start the OpenAI-compatible server bound to `addr`, serving `engine` under `model_id` with
1972/// `n_parallel` concurrent generation slots (`--parallel N`).
1973pub async fn serve(
1974    generator: Arc<dyn ChatGenerator>,
1975    model_id: String,
1976    addr: SocketAddr,
1977    n_parallel: usize,
1978    cfg: Arc<Config>,
1979) -> anyhow::Result<()> {
1980    serve_state(AppState::new(generator, model_id, n_parallel, cfg), addr).await
1981}
1982
1983/// Start the server hosting SEVERAL models at once, each routed by its `model_id` and admitted with
1984/// its own `n_parallel` slot count (`entries[0]` is the default route). This is the multi-device
1985/// host (`infr multi`): each generator can be pinned to a different physical GPU, and the server
1986/// dispatches a request to the generator for the model it names. Graceful shutdown drains EVERY
1987/// model's in-flight requests before any backend drops (the axum layer stops accepting, then each
1988/// generation returns at its next abort poll — see `shutdown_latched`); when `serve_multi`
1989/// returns, the runtime drops and every backend's device is destroyed in turn.
1990pub async fn serve_multi(
1991    entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>,
1992    addr: SocketAddr,
1993    cfg: Arc<Config>,
1994) -> anyhow::Result<()> {
1995    serve_state(AppState::multi(entries, cfg), addr).await
1996}
1997
1998/// Bind + run the axum server over a fully-built [`AppState`] (single- or multi-model). The one
1999/// place the listener, the graceful-shutdown latch, and `axum::serve` live.
2000async fn serve_state(mut state: AppState, addr: SocketAddr) -> anyhow::Result<()> {
2001    host::check_allowed_hosts(&state.cfg)?;
2002    let n_models = state.models.len();
2003    let listener = tokio::net::TcpListener::bind(addr).await?;
2004    // The bound address, not the requested one: with port 0 only the listener knows the port a
2005    // client's `Host` will name.
2006    state.bind = Some(listener.local_addr()?);
2007    // The periodic throughput reporter (B10), unless `serve.stats_interval_secs` is 0. It reads the
2008    // SAME shutdown latch the drain path does, and it is aborted here as well: whichever way the
2009    // server ends, no task is left ticking.
2010    let reporter = stats_interval(&state.cfg)
2011        .map(|period| tokio::spawn(stats_reporter(state.clone(), period)));
2012    let router = build_router(state);
2013    tracing::info!(%addr, %n_models, "infr-server listening");
2014    let served = axum::serve(listener, router)
2015        .with_graceful_shutdown(shutdown_latched())
2016        .await;
2017    if let Some(h) = reporter {
2018        h.abort();
2019    }
2020    served?;
2021    Ok(())
2022}
2023
2024/// Resolves once the process-wide shutdown latch is set (SIGINT/SIGTERM — see
2025/// [`infr_core::shutdown`]), which is `axum`'s cue to stop accepting connections and let the
2026/// in-flight ones finish. The requests themselves see the SAME latch through the decode loop's
2027/// abort poll, so each one stops issuing new GPU work at its next token/chunk boundary, drains what
2028/// it already submitted, and returns what it had — then `serve` returns, the runtime drops, the
2029/// engine drops, and the Vulkan device is destroyed properly. No `process::exit` anywhere on this
2030/// path: exiting under a live submit is the bug this whole mechanism exists to prevent.
2031///
2032/// A POLL (50 ms) rather than `tokio::signal::ctrl_c`, on purpose: the CLI already owns SIGINT and
2033/// SIGTERM via `sigaction`, and `tokio::signal` would install its OWN handler over the top of it —
2034/// last writer wins, and the loser's semantics (in this case, "drain the GPU") silently vanish. One
2035/// handler, one latch, everything downstream reads the latch.
2036async fn shutdown_latched() {
2037    while !infr_core::shutdown::shutdown_requested() {
2038        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2039    }
2040    tracing::info!("shutdown requested — draining in-flight requests");
2041}
2042
2043// ---------------------------------------------------------------------------
2044// Handlers
2045// ---------------------------------------------------------------------------
2046
2047/// Deliberately UNAUTHENTICATED, even when `serve.api_key` is configured. A load balancer, a
2048/// container orchestrator or an uptime probe has to reach this without holding the operator's
2049/// bearer token, and the response is a bare 200 with no body: it discloses nothing about the model
2050/// set, the config, or the machine. Every route that DOES disclose something is gated — see
2051/// [`auth_gate`].
2052async fn health_handler() -> StatusCode {
2053    StatusCode::OK
2054}
2055
2056/// The hosted model list — GATED by the same bearer check as `/v1/chat/completions`.
2057///
2058/// This endpoint enumerates every model id the process is serving. With `serve.api_key` set the
2059/// operator has said the server is not open to whoever can reach the port, and an unauthenticated
2060/// caller must not be able to inventory what is hosted (which names to try, how many devices are
2061/// behind it, which private fine-tune is loaded) — that is reconnaissance, and it used to be free.
2062///
2063/// Returns a [`Response`] rather than `Json<ModelsResponse>` purely so the 401 can share the body
2064/// shape the chat handler returns; the 200 body is byte-identical to what it has always been.
2065/// With auth DISABLED (the default) [`auth_gate`] returns `None` and this is the same open endpoint
2066/// as before — the localhost experience does not change.
2067async fn models_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
2068    if let Some(denied) = auth_gate(&state.cfg, &headers) {
2069        return denied;
2070    }
2071    Json(ModelsResponse {
2072        object: "list",
2073        data: state
2074            .models
2075            .iter()
2076            .map(|m| ModelCard {
2077                id: m.id.to_string(),
2078                object: "model",
2079                owned_by: "local",
2080            })
2081            .collect(),
2082    })
2083    .into_response()
2084}
2085
2086/// Bearer auth for this route is [`require_auth`], layered in front of it by [`build_router`].
2087async fn chat_completions_handler(
2088    State(state): State<AppState>,
2089    body: Result<Json<ChatRequest>, JsonRejection>,
2090) -> Response {
2091    let Json(req) = match body {
2092        Ok(j) => j,
2093        Err(e) => return body_rejection(e),
2094    };
2095    let mut params = match GenParams::from_request(&req) {
2096        Ok(p) => p,
2097        Err(e) => return param_error(Some(e.param), e.message),
2098    };
2099    // Cap an absurd explicit budget so one request can't pin a slot forever. Unset stays unset.
2100    params.max_tokens = clamp_max_tokens(params.max_tokens, max_tokens_cap(&state.cfg));
2101    let messages: Vec<ChatMessage> = req.messages.iter().map(dto_to_engine).collect();
2102    // Pass the request's `tools` array THROUGH as a Value (moved into the blocking task) — no
2103    // Value→string→Value round-trip (audit finding 6).
2104    let tools: Option<serde_json::Value> = req.tools.clone();
2105    // A PRESENT-but-malformed forced tool_choice is a 400, not a silent downgrade to "auto".
2106    let tool_choice: Option<String> = match req.tool_choice.as_ref() {
2107        None | Some(serde_json::Value::Null) => None,
2108        Some(v) => match tool_choice_str(v) {
2109            Ok(tc) => tc,
2110            Err(e) => return param_error(Some(e.param), e.message),
2111        },
2112    };
2113    // …and a WELL-FORMED forced choice the server cannot honour is a 400 too: the constraint
2114    // builder ignores `tool_choice` entirely when `tools` is absent, so without this the request
2115    // would quietly generate ordinary text instead (B22).
2116    if let Err(e) = validate_tools(tools.as_ref())
2117        .and_then(|()| validate_tool_choice(tool_choice.as_deref(), tools.as_ref()))
2118    {
2119        return param_error(Some(e.param), e.message);
2120    }
2121
2122    // Route to the hosted model named in the request (exact id), else the default (first) entry.
2123    // The response `model` field echoes the entry ACTUALLY served, not the raw request string, so a
2124    // client that omitted/mis-named the model sees which one answered.
2125    let entry = state.route(&req.model);
2126    if params.logprobs {
2127        if let Some(engine) = &entry.engine {
2128            if !engine.supports_logprobs() {
2129                return param_error(
2130                    Some("logprobs"),
2131                    "logprobs: returning log probabilities is not supported by this backend".into(),
2132                );
2133            }
2134        }
2135    }
2136    // `logit_bias` ids depend on the model, so they are checked only once it is known, and only
2137    // when there are any. No engine (a headless state) answers 500 further on, whatever the ids.
2138    if let (false, Some(engine)) = (params.logit_bias.is_empty(), &entry.engine) {
2139        if let Err(e) = params.check_vocab(engine.vocab_size()) {
2140            return param_error(Some(e.param), e.message);
2141        }
2142    }
2143    let model_id = entry.id.to_string();
2144    let ctx = ReqCtx {
2145        id: next_req_id(),
2146        cid: make_id(),
2147        model_id,
2148        created: unix_ts(),
2149        // Resolved HERE, once, so both paths see the same policy and neither reaches for the config
2150        // from inside a blocking task. `None` (the default) = no deadline, exactly as before.
2151        deadline: request_timeout(&state.cfg),
2152        keep_alive: sse_keep_alive(&state.cfg),
2153        stream: req.stream,
2154        include_usage: req.stream_options.as_ref().is_some_and(|o| o.include_usage),
2155        stats: state.stats.clone(),
2156    };
2157    let prompt_chars = messages.iter().map(|m| m.content.len()).sum();
2158    let n_messages = messages.len();
2159
2160    // Prepare the request before queueing for a slot and before a stream's `200`: the arrival
2161    // line gets the real prompt count, and an over-long or unservable request is refused here
2162    // instead of after it waited for a slot (or, streamed, as an error frame after a `200`).
2163    let (messages, tools, tool_choice, params, prepared) = match entry.engine.clone() {
2164        None => (messages, tools, tool_choice, params, Ok(None)),
2165        Some(engine) => {
2166            let joined = prepare_bounded(&entry, &ctx, move || {
2167                let prepared =
2168                    engine.prepare(&messages, tools.as_ref(), tool_choice.as_deref(), &params);
2169                (messages, tools, tool_choice, params, prepared)
2170            })
2171            .await;
2172            match joined {
2173                Ok(parts) => parts,
2174                Err(resp) => return *resp,
2175            }
2176        }
2177    };
2178    let prompt_tokens = prepared
2179        .as_ref()
2180        .ok()
2181        .and_then(|p| p.as_ref().map(|p| p.prompt_tokens));
2182    let (prepared, refused) = match prepared {
2183        Err(e) => (None, Some(e)),
2184        Ok(Some(PreparedRequest {
2185            prompt_tokens,
2186            context_length: Some(max),
2187            ..
2188        })) if prompt_tokens > max => (
2189            None,
2190            Some(
2191                ContextLengthExceeded::prompt_too_long(
2192                    CHAT_INPUT,
2193                    max as usize,
2194                    prompt_tokens as usize,
2195                )
2196                .into(),
2197            ),
2198        ),
2199        Ok(p) => (p, None),
2200    };
2201    log_request_start(
2202        ctx.id,
2203        RequestStart {
2204            route: "/v1/chat/completions",
2205            model: &ctx.model_id,
2206            messages: n_messages,
2207            prompt_chars,
2208            prompt_tokens,
2209            max_tokens: params.max_tokens,
2210            stream: ctx.stream,
2211        },
2212    );
2213    if let Some(e) = refused {
2214        ctx.stats.fold_failure();
2215        tracing::warn!(req = ctx.id, error = %e, "request refused before generation");
2216        return error_response(&e, CHAT_INPUT);
2217    }
2218
2219    if ctx.stream {
2220        streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
2221    } else {
2222        non_streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
2223    }
2224}
2225
2226/// Everything about one in-flight request that is not its messages: identity (the log's `req` and
2227/// the wire's `chatcmpl-…`), the reply framing, the deadline policy, and the shared counters.
2228///
2229/// It exists because [`streaming`] and [`non_streaming`] took nine positional arguments and the
2230/// instrumentation wanted three more — at which point the next `String` inserted in the wrong slot
2231/// is a bug the compiler cannot see.
2232#[derive(Clone)]
2233struct ReqCtx {
2234    /// Log-only, monotonic. See [`next_req_id`].
2235    id: u64,
2236    /// The client-facing completion id (`chatcmpl-…`).
2237    cid: String,
2238    /// The model that ACTUALLY answered, echoed on the wire.
2239    model_id: String,
2240    created: i64,
2241    deadline: Option<Duration>,
2242    /// How long a stream may go quiet before a keep-alive comment; `None` sends none.
2243    keep_alive: Option<Duration>,
2244    stream: bool,
2245    /// `stream_options.include_usage`: end the stream with a `usage` chunk.
2246    include_usage: bool,
2247    stats: Arc<ServeStats>,
2248}
2249
2250// ---------------------------------------------------------------------------
2251// Admission and the generation runners both routes share
2252// ---------------------------------------------------------------------------
2253
2254/// The request field a chat request's prompt comes from, which an over-long prompt's `400` names.
2255const CHAT_INPUT: &str = "messages";
2256
2257/// Run `f` — a request's preparation: template render, tokenization, prompt count — on a blocking
2258/// thread, admitted by the model's preparation bound ([`ModelEntry::prepares`]). Every route that
2259/// readies a request before it queues goes through here, so they share one bound. A failure is
2260/// already the response, counted and logged.
2261async fn prepare_bounded<T: Send + 'static>(
2262    entry: &ModelEntry,
2263    ctx: &ReqCtx,
2264    f: impl FnOnce() -> T + Send + 'static,
2265) -> Result<T, Box<Response>> {
2266    // A client that hangs up while waiting here drops this future, and its place in the queue
2267    // with it; the permit is held for exactly the preparation.
2268    let Ok(permit) = entry.prepares.clone().acquire_owned().await else {
2269        ctx.stats.fold_failure();
2270        return Err(Box::new(json_error(
2271            StatusCode::SERVICE_UNAVAILABLE,
2272            "server shutting down".into(),
2273        )));
2274    };
2275    tokio::task::spawn_blocking(move || {
2276        let _permit = permit;
2277        f()
2278    })
2279    .await
2280    .map_err(|e| {
2281        ctx.stats.fold_failure();
2282        tracing::warn!(req = ctx.id, error = %e, "request preparation failed");
2283        Box::new(json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
2284    })
2285}
2286
2287/// A generation slot held on one model: its permit and the `active` gauge, released together.
2288///
2289/// MOVED into the blocking task and dropped when it ends: a slot is held for exactly the
2290/// generation, the next queued request is admitted the moment it frees, and the gauge — released
2291/// on the same events, an unwinding panic included — can never disagree with it.
2292struct Slot {
2293    _permit: tokio::sync::OwnedSemaphorePermit,
2294    _active: ActiveGuard,
2295}
2296
2297/// Wait for a free slot ON THIS MODEL. With `--parallel N`, the (N+1)'th concurrent request to
2298/// this model queues HERE — in the async runtime, holding no thread — and is admitted FIFO as soon
2299/// as one of that model's generations finishes. A different model's slots are independent. The
2300/// guard is what the periodic line's `queued` counts; it drops however the wait ends.
2301async fn acquire_slot(entry: &ModelEntry, ctx: &ReqCtx) -> Result<Slot, Box<Response>> {
2302    let stats = &ctx.stats;
2303    let queued = QueuedGuard::new(stats.clone());
2304    let Ok(permit) = entry.slots.clone().acquire_owned().await else {
2305        stats.fold_failure();
2306        tracing::warn!(req = ctx.id, "rejected — server shutting down");
2307        return Err(Box::new(json_error(
2308            StatusCode::SERVICE_UNAVAILABLE,
2309            "server shutting down".into(),
2310        )));
2311    };
2312    drop(queued);
2313    Ok(Slot {
2314        _permit: permit,
2315        _active: ActiveGuard::new(stats.clone()),
2316    })
2317}
2318
2319/// The non-streaming generation both routes share: wait for a slot, run `job` on a blocking thread
2320/// holding it with the routed engine and the request's abort latch, and wait for it under the
2321/// deadline. Returns what `job` produced and whether the deadline cut it short. A failure is
2322/// already the response, counted and logged; `input` is the request field an over-long prompt's
2323/// error names.
2324async fn run_unary<T: Send + 'static>(
2325    entry: &ModelEntry,
2326    ctx: &ReqCtx,
2327    input: &'static str,
2328    job: impl FnOnce(&dyn ChatGenerator, &Arc<AtomicBool>) -> anyhow::Result<T> + Send + 'static,
2329) -> Result<(T, bool), Box<Response>> {
2330    let req_id = ctx.id;
2331    let slot = acquire_slot(entry, ctx).await?;
2332    let engine_arc = entry.engine.clone();
2333
2334    // Per-request abort latch. It lives OUT here, not inside the closure, so the deadline below can
2335    // reach it: the generator polls it in its decode loop, and that poll is the only way to stop a
2336    // `spawn_blocking` task early.
2337    let cancel = Arc::new(AtomicBool::new(false));
2338    let cancel_blk = cancel.clone();
2339    // A client that hangs up is noticed by hyper, which DROPS the handler future — and with it
2340    // this guard, which latches the abort so the generation stops and frees its slot instead of
2341    // running to `max_tokens` for nobody. On a normal return it latches a generation that has
2342    // already ended, which nothing reads.
2343    let _hangup = CancelOnDrop(cancel.clone());
2344
2345    let mut handle = tokio::task::spawn_blocking(move || -> anyhow::Result<T> {
2346        let _slot = slot;
2347        let Some(engine) = engine_arc else {
2348            anyhow::bail!("no engine loaded");
2349        };
2350        job(&*engine, &cancel_blk)
2351    });
2352
2353    // The deadline, and the ONE thing about it that is easy to get wrong.
2354    //
2355    // `tokio::time::timeout(d, handle).await` returning `Err` and being propagated to the client is
2356    // NOT a fix: the blocking task is not cancellable, so it would keep decoding, keep holding its
2357    // `OwnedSemaphorePermit`, and the `--parallel` slot — the entire reason for having a deadline —
2358    // would stay occupied while we reported failure. So the timeout is used only to WAKE US: on
2359    // expiry we latch the abort flag the generator polls and then go back to awaiting the SAME
2360    // join. The task ends at its next token boundary, the permit drops, and we still have every
2361    // delta it produced before then, which is what the client gets.
2362    //
2363    // No watchdog TASK on this path (unlike [`run_streamed`]): the handler is already awaiting the
2364    // join, so the timer can live inside its own future. Nothing to spawn means nothing to tear
2365    // down — the `Timeout` future is dropped by the `.await` that resolves it, whichever way it
2366    // went, and a request that finishes in 5 ms under an hour-long deadline leaves nothing behind.
2367    let mut deadline_hit = false;
2368    let joined = match ctx.deadline {
2369        None => handle.await,
2370        Some(d) => match tokio::time::timeout(d, &mut handle).await {
2371            Ok(joined) => joined,
2372            Err(_elapsed) => {
2373                deadline_hit = true;
2374                cancel.store(true, Ordering::Relaxed);
2375                tracing::warn!(
2376                    req = req_id,
2377                    timeout_s = d.as_secs(),
2378                    "request deadline hit — returning the partial completion"
2379                );
2380                handle.await
2381            }
2382        },
2383    };
2384    match joined.map_err(anyhow::Error::from).and_then(|r| r) {
2385        Ok(out) => Ok((out, deadline_hit)),
2386        Err(e) => {
2387            ctx.stats.fold_failure();
2388            tracing::warn!(req = req_id, error = %e, "request failed");
2389            Err(Box::new(error_response(&e, input)))
2390        }
2391    }
2392}
2393
2394/// One streamed generation's end of the SSE channel, handed by [`run_streamed`] to the route's job
2395/// on its blocking thread.
2396struct StreamJob {
2397    tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
2398    /// The request's abort latch, which the generator polls.
2399    cancel: Arc<AtomicBool>,
2400    /// Set by the deadline watchdog. Separate from `cancel` because `cancel` is ALSO latched by a
2401    /// client disconnect, and the finish chunk must not report a timeout as a hangup or vice versa.
2402    deadline_hit: Arc<AtomicBool>,
2403    /// Closes the stream exactly once, however the job ends — see [`DoneGuard`].
2404    done: DoneGuard,
2405    /// The routed model's generator; `None` on a headless state.
2406    engine: Option<Arc<dyn ChatGenerator>>,
2407}
2408
2409impl StreamJob {
2410    /// Send one frame. A failed send means the receiver (the client's stream) is gone: latch the
2411    /// abort so the decode loop stops at its next poll and returns the slot.
2412    fn send(&self, ev: Event) {
2413        if self.tx.send(Ok(ev)).is_err() {
2414            self.cancel.store(true, Ordering::Relaxed);
2415        }
2416    }
2417
2418    /// The finish reason to report for a generation that ended with `finish`. The generator saw
2419    /// only an abort when the deadline fired and reports `Stop`, so the deadline relabels it
2420    /// "length" — the budget ran out, the model did not finish.
2421    fn finish(&self, finish: Finish) -> Finish {
2422        if self.deadline_hit.load(Ordering::Relaxed) {
2423            Finish::Length
2424        } else {
2425            finish
2426        }
2427    }
2428
2429    /// Report a failed generation as the stream's terminal frame. A mid-stream failure is NOT a
2430    /// clean `stop` — the error frame lets the client tell this apart from success (matching the
2431    /// non-streaming 500). `[DONE]` still follows, via `DoneGuard` (audit finding 1). A request's
2432    /// own fault carries the same typed error the non-streaming path answers with a 400, so a
2433    /// client can tell it from a crash; `input` is the field an over-long prompt's error names.
2434    fn fail(&mut self, e: &anyhow::Error, input: &'static str) {
2435        match request_error_body(e, input) {
2436            Some(body) => self.done.fail_with(body, &e.to_string()),
2437            None => self.done.fail(&e.to_string()),
2438        }
2439    }
2440}
2441
2442/// The streaming generation both routes share: wait for a slot, then hand `job` a [`StreamJob`]
2443/// on a blocking thread holding it, and answer with the SSE stream the job writes into.
2444async fn run_streamed(
2445    entry: &ModelEntry,
2446    ctx: &ReqCtx,
2447    job: impl FnOnce(StreamJob) + Send + 'static,
2448) -> Response {
2449    // UNBOUNDED on purpose. The generator's `on_delta` callback is invoked from inside the decode
2450    // loop — which, under `--parallel N`, is holding the GPU baton. A bounded channel would make a
2451    // slow (or stalled) SSE client apply backpressure straight into that callback, so ONE
2452    // non-draining client would block the GPU step it is inside of and stall every OTHER sequence
2453    // behind it: precisely the head-of-line blocking this whole change exists to remove. Decoupling
2454    // the socket from the decode loop costs a queue whose depth is bounded anyway by `max_tokens`
2455    // (a few thousand short strings, worst case), which is the right trade.
2456    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
2457
2458    // Same per-model admission gate as the non-streaming path. Taken BEFORE the SSE response is
2459    // returned, so a queued client simply waits for its first byte rather than being handed an
2460    // open-but-silent stream.
2461    let slot = match acquire_slot(entry, ctx).await {
2462        Ok(slot) => slot,
2463        Err(resp) => return *resp,
2464    };
2465
2466    // Per-request abort latch: set when the client disconnects and polled by the generator's
2467    // decode loop so it stops promptly and frees the GPU slot instead of running to `max_tokens`
2468    // into a dead socket (audit finding 2). A failed send ([`StreamJob::send`]) notices the
2469    // hang-up only at the next delta; [`cancel_on_hangup`] notices it as it happens — during a
2470    // long prefill, or while the stop matcher holds output back, no delta is being sent at all.
2471    let cancel = Arc::new(AtomicBool::new(false));
2472    let hangup_done = cancel_on_hangup(&tx, cancel.clone());
2473
2474    // Wall-clock deadline. Unlike the non-streaming path, nothing here awaits the generation's join
2475    // — the SSE response is returned as soon as the stream exists — so the timer needs its own
2476    // task, and that task needs an off switch. [`arm_deadline`] hands back a sender whose DROP is
2477    // that switch; it is moved into the blocking closure below, so the watchdog dies with the
2478    // generation (normally or by panic) instead of accumulating one sleeper per request.
2479    let deadline_hit = Arc::new(AtomicBool::new(false));
2480    let done_tx = ctx
2481        .deadline
2482        .map(|d| arm_deadline(d, cancel.clone(), deadline_hit.clone()));
2483
2484    let engine = entry.engine.clone();
2485    let (req_id, stats) = (ctx.id, ctx.stats.clone());
2486    tokio::task::spawn_blocking(move || {
2487        // Held for exactly this generation; freed for the next queued request on return. The
2488        // `active` gauge is released by the same return (or unwind).
2489        let _slot = slot;
2490        // Disarms the deadline watchdog when this task ends — see [`arm_deadline`]. `None` when no
2491        // deadline was configured, in which case there is no watchdog to disarm.
2492        let _done_tx = done_tx;
2493        // Likewise ends the hang-up watcher, whose sender clone would otherwise hold the stream
2494        // open.
2495        let _hangup_done = hangup_done;
2496        // The job owns the `DoneGuard`, which closes the stream exactly once however the job ends.
2497        // It emits `[DONE]` always, and — unless `settled()` says a terminal frame already went
2498        // out — reports the generation as a failure. Both matter on an unwinding panic, which
2499        // skips the job's own error handling (B23).
2500        let done = DoneGuard {
2501            tx: tx.clone(),
2502            req_id,
2503            stats,
2504            settled: false,
2505        };
2506        job(StreamJob {
2507            tx,
2508            cancel,
2509            deadline_hit,
2510            done,
2511            engine,
2512        });
2513    });
2514
2515    // Bridge the mpsc receiver to an async Stream for axum's Sse.
2516    let stream = futures_util::stream::unfold(rx, |mut rx| async move {
2517        rx.recv().await.map(|item| (item, rx))
2518    });
2519
2520    let sse = Sse::new(stream);
2521    match ctx.keep_alive {
2522        Some(d) => sse.keep_alive(KeepAlive::new().interval(d)).into_response(),
2523        None => sse.into_response(),
2524    }
2525}
2526
2527// ---------------------------------------------------------------------------
2528// Non-streaming path
2529// ---------------------------------------------------------------------------
2530
2531async fn non_streaming(
2532    entry: ModelEntry,
2533    prepared: Option<PreparedRequest>,
2534    messages: Vec<ChatMessage>,
2535    tools: Option<serde_json::Value>,
2536    tool_choice: Option<String>,
2537    params: GenParams,
2538    ctx: ReqCtx,
2539) -> Response {
2540    let cid_blk = ctx.cid.clone();
2541    let stats_blk = ctx.stats.clone();
2542    let want_logprobs = params.logprobs;
2543
2544    let ran = run_unary(&entry, &ctx, CHAT_INPUT, move |engine, cancel| {
2545        let mut reasoning = String::new();
2546        let mut content = String::new();
2547        let mut tool_calls: Vec<OAIToolCall> = Vec::new();
2548        let mut logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
2549        // Per-request tally: plain locals, folded into the shared counters once at the end.
2550        let mut tally = ReqTally::new();
2551
2552        let outcome = generate(
2553            engine,
2554            prepared,
2555            &messages,
2556            tools.as_ref(),
2557            tool_choice.as_deref(),
2558            &params,
2559            cancel,
2560            &mut |delta| match delta {
2561                Delta::Reasoning(t) => {
2562                    tally.on_text_delta(&stats_blk);
2563                    reasoning.push_str(&t);
2564                }
2565                Delta::Content(t) => {
2566                    tally.on_text_delta(&stats_blk);
2567                    content.push_str(&t);
2568                }
2569                Delta::ToolCall { name, arguments } => {
2570                    let idx = tool_calls.len();
2571                    tool_calls.push(OAIToolCall {
2572                        index: idx,
2573                        id: tool_call_id(&cid_blk, idx),
2574                        kind: "function",
2575                        function: OAIFunction { name, arguments },
2576                    });
2577                }
2578                Delta::Logprob(t) => logprobs.push(t),
2579            },
2580        )?;
2581
2582        Ok((reasoning, content, tool_calls, logprobs, outcome, tally))
2583    })
2584    .await;
2585    let ((reasoning, content, tool_calls, logprobs, outcome, tally), deadline_hit) = match ran {
2586        Ok(ran) => ran,
2587        Err(resp) => return *resp,
2588    };
2589    let ReqCtx {
2590        id: req_id,
2591        cid,
2592        model_id,
2593        created,
2594        stream,
2595        stats,
2596        ..
2597    } = ctx;
2598
2599    // A deadline hit is a TRUNCATION, not a failure: the client keeps the partial reply (a 500
2600    // would throw away work it can use) and `finish_reason` says "length", which is OpenAI's
2601    // reason for a completion that ran out of budget.
2602    //
2603    // It has to be decided here because the generator cannot know. From inside the decode loop,
2604    // the latch we set is indistinguishable from any other abort, so it reports a clean
2605    // `Finish::Stop` — and "stop" tells the client the model finished its thought, which would be
2606    // a lie. Only the handler that armed the deadline knows it fired.
2607    //
2608    // A tool call still wins, as it does for every other reason: the call was emitted whole, and a
2609    // client that gets `tool_calls` can act on it.
2610    let finish = if !tool_calls.is_empty() {
2611        Finish::ToolCalls
2612    } else if deadline_hit {
2613        Finish::Length
2614    } else {
2615        outcome.finish
2616    };
2617    // Fold the request's tallies in ONCE, here, and log its completion line.
2618    let rec = tally.finish(outcome, finish);
2619    stats.fold_completion(&rec);
2620    log_request_done(req_id, &model_id, stream, &rec);
2621    Json(ChatCompletionResponse {
2622        id: cid,
2623        object: "chat.completion",
2624        created,
2625        model: model_id,
2626        choices: vec![CompletionChoice {
2627            index: 0,
2628            message: AssistantMessage {
2629                role: "assistant",
2630                content: if content.is_empty() {
2631                    None
2632                } else {
2633                    Some(content.clone())
2634                },
2635                reasoning_content: if reasoning.is_empty() {
2636                    None
2637                } else {
2638                    Some(reasoning)
2639                },
2640                tool_calls: if tool_calls.is_empty() {
2641                    None
2642                } else {
2643                    Some(tool_calls)
2644                },
2645            },
2646            logprobs: want_logprobs.then(|| ChatLogprobs::from_tokens(&logprobs)),
2647            finish_reason: finish.as_str().into(),
2648        }],
2649        usage: UsageInfo::from_outcome(&outcome),
2650    })
2651    .into_response()
2652}
2653
2654// ---------------------------------------------------------------------------
2655// Streaming path (SSE)
2656// ---------------------------------------------------------------------------
2657
2658async fn streaming(
2659    entry: ModelEntry,
2660    prepared: Option<PreparedRequest>,
2661    messages: Vec<ChatMessage>,
2662    tools: Option<serde_json::Value>,
2663    tool_choice: Option<String>,
2664    params: GenParams,
2665    ctx: ReqCtx,
2666) -> Response {
2667    // The job's own copy: it runs on the blocking thread, past this borrow of `ctx`.
2668    let ReqCtx {
2669        id: req_id,
2670        cid,
2671        model_id,
2672        created,
2673        stream,
2674        include_usage,
2675        stats,
2676        ..
2677    } = ctx.clone();
2678
2679    run_streamed(&entry, &ctx, move |mut job| {
2680        // First chunk: role delta (mirrors the Python shim's opening chunk).
2681        job.send(sse_chunk(
2682            &cid,
2683            &model_id,
2684            created,
2685            DeltaPayload {
2686                role: Some("assistant".into()),
2687                ..Default::default()
2688            },
2689            None,
2690            None,
2691        ));
2692
2693        let Some(engine) = job.engine.clone() else {
2694            // `fail` sends the error frame, folds the statistic and logs; `DoneGuard` then
2695            // closes the stream with `[DONE]`.
2696            job.done.fail("no engine loaded");
2697            return;
2698        };
2699
2700        let mut tc_index = 0usize;
2701        let mut saw_tool_call = false;
2702        // Log probabilities wait here for the content delta they belong to. The splitter emits
2703        // each answer token's entry just before the delta carrying its text, so a chunk carries
2704        // both together.
2705        let mut pending_logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
2706        // Per-request tally: plain locals inside the generation, folded in once below.
2707        let mut tally = ReqTally::new();
2708
2709        let res = generate(
2710            &*engine,
2711            prepared,
2712            &messages,
2713            tools.as_ref(),
2714            tool_choice.as_deref(),
2715            &params,
2716            &job.cancel,
2717            &mut |delta| {
2718                let payload = match delta {
2719                    Delta::Logprob(t) => {
2720                        pending_logprobs.push(t);
2721                        return;
2722                    }
2723                    Delta::Reasoning(t) => {
2724                        tally.on_text_delta(&stats);
2725                        DeltaPayload {
2726                            reasoning_content: Some(t),
2727                            ..Default::default()
2728                        }
2729                    }
2730                    Delta::Content(t) => {
2731                        tally.on_text_delta(&stats);
2732                        DeltaPayload {
2733                            content: Some(t),
2734                            ..Default::default()
2735                        }
2736                    }
2737                    Delta::ToolCall { name, arguments } => {
2738                        let tc = OAIToolCall {
2739                            index: tc_index,
2740                            id: tool_call_id(&cid, tc_index),
2741                            kind: "function",
2742                            function: OAIFunction { name, arguments },
2743                        };
2744                        tc_index += 1;
2745                        saw_tool_call = true;
2746                        DeltaPayload {
2747                            tool_calls: Some(vec![tc]),
2748                            ..Default::default()
2749                        }
2750                    }
2751                };
2752                let logprobs = if pending_logprobs.is_empty() {
2753                    None
2754                } else {
2755                    Some(ChatLogprobs::from_tokens(&std::mem::take(
2756                        &mut pending_logprobs,
2757                    )))
2758                };
2759                job.send(sse_chunk(&cid, &model_id, created, payload, logprobs, None));
2760            },
2761        );
2762
2763        match res {
2764            Ok(outcome) => {
2765                // Same honesty rule as the non-streaming path: a deadline is "length", and a
2766                // tool call still wins.
2767                let finish = if saw_tool_call {
2768                    Finish::ToolCalls
2769                } else {
2770                    job.finish(outcome.finish)
2771                };
2772                // Finish chunk: empty delta + finish_reason. Entries a generator emitted with no
2773                // text after them ride here rather than being lost.
2774                let last_logprobs = if pending_logprobs.is_empty() {
2775                    None
2776                } else {
2777                    Some(ChatLogprobs::from_tokens(&pending_logprobs))
2778                };
2779                job.send(sse_chunk(
2780                    &cid,
2781                    &model_id,
2782                    created,
2783                    DeltaPayload::default(),
2784                    last_logprobs,
2785                    Some(finish.as_str().into()),
2786                ));
2787                if include_usage {
2788                    job.send(sse_usage_chunk(&cid, &model_id, created, &outcome));
2789                }
2790                // Fold the request's tallies in ONCE, here, and log its completion line. The
2791                // finish chunk above IS this stream's terminal frame, so the guard must not
2792                // also report a failure when it drops.
2793                let rec = tally.finish(outcome, finish);
2794                stats.fold_completion(&rec);
2795                log_request_done(req_id, &model_id, stream, &rec);
2796                job.done.settled();
2797            }
2798            Err(e) => job.fail(&e, CHAT_INPUT),
2799        }
2800        // `DoneGuard` drops with the job (or on an unwinding panic). It sends `[DONE]`, and if
2801        // nothing above settled the stream it first reports the request as failed (B23).
2802    })
2803    .await
2804}
2805
2806// ---------------------------------------------------------------------------
2807// Private helpers
2808// ---------------------------------------------------------------------------
2809
2810/// Closes the SSE stream exactly once when it drops, from the normal end of the generation OR from
2811/// an unwinding panic inside the decode closure.
2812///
2813/// Two jobs, and the second one exists because the first was not enough:
2814///
2815/// 1. `[DONE]` is ALWAYS the final frame. A strict SSE client blocks until it sees the sentinel, so
2816///    a swallowed panic must never leave it unsent (audit finding 1).
2817/// 2. A generation that never reached its terminal frame is reported AS A FAILURE — error frame,
2818///    `fold_failure`, and a `warn!` carrying the `req` id.
2819///
2820/// The streaming path discards its `spawn_blocking` join handle, so a panic in
2821/// `ChatGenerator::chat` unwinds past the `match res` and the `Err` arm never runs. Before this
2822/// guard owned the failure path, the wire showed the role chunk and then `[DONE]` with no error
2823/// frame and no terminal `finish_reason` — indistinguishable from a short success — while
2824/// `interval_failed` AND `interval_completed` both stayed zero, so the throughput line under-
2825/// reported the failure and the completion at once (backlog B23, proved).
2826///
2827/// [`Self::settled`] is what separates the two cases. Every path that produces its own terminal
2828/// frame calls it; anything that unwinds or returns early does not, and the guard speaks for it.
2829/// A flag rather than `std::thread::panicking()` because an early `return` is not a panic and still
2830/// leaves the stream unterminated.
2831struct DoneGuard {
2832    tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
2833    /// The request id, so the failure this guard reports joins its `request start` line.
2834    req_id: u64,
2835    stats: Arc<ServeStats>,
2836    /// Set by [`Self::settled`] once a terminal frame is out and the tallies are folded.
2837    settled: bool,
2838}
2839
2840impl DoneGuard {
2841    /// The generation reached a terminal frame and folded its own tallies — the guard should send
2842    /// nothing but `[DONE]`.
2843    fn settled(&mut self) {
2844        self.settled = true;
2845    }
2846
2847    /// Report this request as failed, exactly once: terminal error frame, `fold_failure`, `warn!`.
2848    ///
2849    /// The ONE place a streaming failure is recorded, so the wire frame, the statistic and the log
2850    /// line cannot drift apart or be emitted twice. Called explicitly by the paths that know why
2851    /// they failed, and by [`Drop`] for the paths that never got the chance.
2852    fn fail(&mut self, msg: &str) {
2853        self.fail_with(error_body(msg, "server_error"), msg);
2854    }
2855
2856    /// [`Self::fail`] with an error body other than the generic `server_error` one; `msg` is what
2857    /// the log line says.
2858    fn fail_with(&mut self, body: serde_json::Value, msg: &str) {
2859        if self.settled {
2860            return;
2861        }
2862        self.settled = true;
2863        // A failed send just means the client is already gone; the accounting still has to be
2864        // right, so the fold and the log are NOT conditional on it.
2865        let _ = self.tx.send(Ok(sse_error_event(&body)));
2866        self.stats.fold_failure();
2867        tracing::warn!(req = self.req_id, error = msg, "request failed");
2868    }
2869}
2870
2871impl Drop for DoneGuard {
2872    fn drop(&mut self) {
2873        self.fail("internal error: generation ended without a terminal frame");
2874        let _ = self.tx.send(Ok(Event::default().data("[DONE]")));
2875    }
2876}
2877
2878/// The OpenAI error envelope — `{"error": {"message": .., "type": ..}}` — that every failure this
2879/// server reports is wrapped in, whether it leaves as an HTTP body or as an SSE frame.
2880///
2881/// This is a WIRE format: clients (the OpenAI SDKs, `curl | jq .error.message`) match on the outer
2882/// key and on `type`, and two tests pin the shape. It was spelled out inline at three call sites,
2883/// two of which were character-for-character identical; the third ([`param_error`]) adds `param` and
2884/// `code` on top rather than being a different envelope. Building the common two fields here means
2885/// a renamed key cannot reach only some of the responses.
2886fn error_body(msg: &str, ty: &str) -> serde_json::Value {
2887    serde_json::json!({"error": {"message": msg, "type": ty}})
2888}
2889
2890/// A terminal SSE error frame: `data: {"error":{...}}`. Distinguishable from a normal
2891/// `chat.completion.chunk` and from `[DONE]`, so a client can tell a mid-stream failure apart from a
2892/// clean completion (audit finding 1).
2893fn sse_error_event(body: &serde_json::Value) -> Event {
2894    Event::default().data(body.to_string())
2895}
2896
2897/// Serialize a delta payload into an SSE event carrying a `chat.completion.chunk`.
2898fn sse_chunk(
2899    cid: &str,
2900    model: &str,
2901    created: i64,
2902    delta: DeltaPayload,
2903    logprobs: Option<ChatLogprobs>,
2904    finish_reason: Option<String>,
2905) -> Event {
2906    let chunk = ChatCompletionChunk {
2907        id: cid.to_owned(),
2908        object: "chat.completion.chunk",
2909        created,
2910        model: model.to_owned(),
2911        choices: vec![ChunkChoice {
2912            index: 0,
2913            delta,
2914            logprobs,
2915            finish_reason,
2916        }],
2917        usage: None,
2918    };
2919    Event::default()
2920        .json_data(chunk)
2921        .expect("ChatCompletionChunk always serializes")
2922}
2923
2924/// The `stream_options.include_usage` chunk: the whole request's `usage`, and an empty `choices`
2925/// array, sent after the finish chunk and before `[DONE]`.
2926fn sse_usage_chunk(cid: &str, model: &str, created: i64, outcome: &ChatOutcome) -> Event {
2927    let chunk = ChatCompletionChunk {
2928        id: cid.to_owned(),
2929        object: "chat.completion.chunk",
2930        created,
2931        model: model.to_owned(),
2932        choices: Vec::new(),
2933        usage: Some(UsageInfo::from_outcome(outcome)),
2934    };
2935    Event::default()
2936        .json_data(chunk)
2937        .expect("ChatCompletionChunk always serializes")
2938}
2939
2940fn json_error(status: StatusCode, msg: String) -> Response {
2941    (status, Json(error_body(&msg, "server_error"))).into_response()
2942}
2943
2944/// An `invalid_request_error` — the request is at fault and resending it unchanged will not help.
2945/// `param` names the offending field and `code` is OpenAI's machine-readable reason, where there
2946/// is one (`null` otherwise).
2947///
2948/// Two fields on top of the shared [`error_body`], and they are deliberately absent from the
2949/// server-error responses rather than emitted as nulls there: `param` only means something when a
2950/// specific request field is at fault, and OpenAI's own 5xx bodies carry neither. `code` is
2951/// present even when null because SDKs read `error.code` on a 4xx. Appending them keeps the key
2952/// order (`message`, `type`, `param`, `code`) the responses have always had; `serde_json`'s
2953/// `preserve_order` makes that order observable on the wire.
2954fn invalid_request(
2955    status: StatusCode,
2956    param: Option<&str>,
2957    code: Option<&str>,
2958    msg: String,
2959) -> Response {
2960    (status, Json(invalid_request_body(param, code, &msg))).into_response()
2961}
2962
2963/// The body of [`invalid_request`], for the SSE error frame as well as the HTTP response.
2964fn invalid_request_body(param: Option<&str>, code: Option<&str>, msg: &str) -> serde_json::Value {
2965    let mut body = error_body(msg, "invalid_request_error");
2966    body["error"]["param"] = serde_json::json!(param);
2967    body["error"]["code"] = serde_json::json!(code);
2968    body
2969}
2970
2971/// The over-long-prompt error, identical on both paths: a `400` body, or a streamed error frame.
2972/// `input` is the request field the prompt came from — `messages`, or a raw completion's `prompt`.
2973fn context_length_body(c: &ContextLengthExceeded, input: &str) -> serde_json::Value {
2974    invalid_request_body(Some(input), Some("context_length_exceeded"), &c.message)
2975}
2976
2977/// The `400` body for a generator error that is the request's fault — an over-long prompt, or a
2978/// [`ParamError`] the generator could not honour — or `None` for a failure of the server's own.
2979/// `input` is as for [`context_length_body`].
2980fn request_error_body(e: &anyhow::Error, input: &str) -> Option<serde_json::Value> {
2981    if let Some(c) = e.downcast_ref::<ContextLengthExceeded>() {
2982        return Some(context_length_body(c, input));
2983    }
2984    e.downcast_ref::<ParamError>()
2985        .map(|p| invalid_request_body(Some(p.param), None, &p.message))
2986}
2987
2988/// A generator error as an HTTP response: its typed body with a `400`, else a `500`.
2989fn error_response(e: &anyhow::Error, input: &str) -> Response {
2990    match request_error_body(e, input) {
2991        Some(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
2992        None => json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
2993    }
2994}
2995
2996/// A body the JSON extractor refused. Malformed JSON and wrong field types are a `400` (not axum's
2997/// default `422`, which no OpenAI client expects); a body over the size limit keeps its `413` and a
2998/// missing JSON content type its `415`, because those say something a client can fix differently.
2999fn body_rejection(e: JsonRejection) -> Response {
3000    let status = match e.status() {
3001        s @ (StatusCode::PAYLOAD_TOO_LARGE | StatusCode::UNSUPPORTED_MEDIA_TYPE) => s,
3002        _ => StatusCode::BAD_REQUEST,
3003    };
3004    invalid_request(status, None, None, e.body_text())
3005}
3006
3007/// OpenAI-shaped 400 for a bad request parameter (`invalid_request_error`, with the offending
3008/// `param` named). NOT a clamp and NOT a panic — see [`GenParams::from_request`].
3009fn param_error(param: Option<&str>, msg: String) -> Response {
3010    invalid_request(StatusCode::BAD_REQUEST, param, None, msg)
3011}
3012
3013/// Process-monotonic tie-breaker so two requests in the SAME millisecond (routine under
3014/// `--parallel N`) never mint the same completion `id` — which also keeps the tool-call ids
3015/// [`tool_call_id`] derives from it distinct (audit finding 4).
3016static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
3017
3018fn make_id() -> String {
3019    let ms = SystemTime::now()
3020        .duration_since(UNIX_EPOCH)
3021        .unwrap_or_default()
3022        .as_millis();
3023    let seq = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
3024    format!("chatcmpl-{ms}-{seq}")
3025}
3026
3027/// Length of a tool-call id, and its alphabet below: the shape Mistral's chat template demands of
3028/// every replayed `tool_calls[].id` (it `raise_exception`s on anything else), which OpenAI clients
3029/// treat as an opaque string. One shape for every model keeps a replayed id valid whichever
3030/// template renders the next turn.
3031const TOOL_CALL_ID_LEN: usize = 9;
3032const TOOL_CALL_ID_ALPHABET: &[u8] =
3033    b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
3034
3035/// The wire id of the `idx`-th tool call in completion `cid`: a hash of the pair, spelled in
3036/// [`TOOL_CALL_ID_ALPHABET`]. Deterministic, so the streaming and non-streaming paths agree, and
3037/// distinct across completions because `cid` is (see [`make_id`]).
3038fn tool_call_id(cid: &str, idx: usize) -> String {
3039    use std::hash::{DefaultHasher, Hash, Hasher};
3040    let mut h = DefaultHasher::new();
3041    (cid, idx).hash(&mut h);
3042    let mut n = h.finish();
3043    let base = TOOL_CALL_ID_ALPHABET.len() as u64;
3044    (0..TOOL_CALL_ID_LEN)
3045        .map(|_| {
3046            let c = TOOL_CALL_ID_ALPHABET[(n % base) as usize] as char;
3047            n /= base;
3048            c
3049        })
3050        .collect()
3051}
3052
3053/// Default ceiling for `max_tokens`/`max_completion_tokens` when `INFR_MAX_TOKENS_CAP` is unset —
3054/// generous (128k) but finite, so one request cannot pin a slot for an absurd budget.
3055const DEFAULT_MAX_TOKENS_CAP: u32 = 131_072;
3056
3057/// The configured `max_tokens` ceiling: `serve.max_tokens_cap` (`INFR_MAX_TOKENS_CAP`) if a
3058/// positive integer, else [`DEFAULT_MAX_TOKENS_CAP`]. Read per-request off the borrowed `Config`
3059/// the [`AppState`] owns (this used to be a per-request `std::env::var`).
3060///
3061/// The `> 0` guard stays HERE, at the accessor (R5): the env layer already drops a non-positive
3062/// `INFR_MAX_TOKENS_CAP`, but a config FILE can name the same field, and "must be a positive
3063/// integer, else the default" is this knob's grammar whatever layer supplied it.
3064fn max_tokens_cap(cfg: &Config) -> u32 {
3065    let cap = cfg.serve.max_tokens_cap;
3066    if cap > 0 {
3067        cap
3068    } else {
3069        DEFAULT_MAX_TOKENS_CAP
3070    }
3071}
3072
3073/// Clamp an explicit `max_tokens` to `cap`. `None` (unset) passes through untouched — the generator
3074/// keeps applying its own `INFR_MAX_NEW` default, so behaviour is unchanged for requests that don't
3075/// ask for a budget. Only an absurdly large EXPLICIT value is capped (audit finding 5).
3076fn clamp_max_tokens(requested: Option<u32>, cap: u32) -> Option<u32> {
3077    requested.map(|v| v.min(cap))
3078}
3079
3080/// The configured request body limit: `serve.max_body_bytes` if positive, else the default (the
3081/// env layer drops a zero, and this guard gives a config FILE's zero the same meaning).
3082fn max_body_bytes(cfg: &Config) -> usize {
3083    let n = match cfg.serve.max_body_bytes {
3084        0 => Config::default().serve.max_body_bytes,
3085        n => n,
3086    };
3087    usize::try_from(n).unwrap_or(usize::MAX)
3088}
3089
3090/// The configured SSE keep-alive interval, or `None` when `serve.sse_keepalive_secs` is `0`.
3091fn sse_keep_alive(cfg: &Config) -> Option<Duration> {
3092    let secs = cfg.serve.sse_keepalive_secs;
3093    (secs > 0).then(|| Duration::from_secs(secs).min(MAX_SSE_KEEPALIVE))
3094}
3095
3096/// The longest keep-alive interval honoured. axum arms the timer as `Instant::now() + interval`,
3097/// which panics on overflow for an interval near `u64::MAX` seconds; a quiet stream is never
3098/// worth keeping open longer than this anyway.
3099const MAX_SSE_KEEPALIVE: Duration = Duration::from_secs(24 * 60 * 60);
3100
3101/// The configured per-request wall-clock deadline, or `None` for "unbounded" — which is the
3102/// DEFAULT (`serve.request_timeout_secs` = 0) and today's behaviour.
3103///
3104/// `0` and unset are the same thing on purpose: the knob's whole grammar is "seconds, or 0 for no
3105/// deadline", so an operator can disarm a deadline a config file set by exporting
3106/// `INFR_REQUEST_TIMEOUT_SECS=0` — a `None`-only spelling could not express that from the
3107/// environment (see the env layer's note on why this knob is NOT `.filter(|v| v > 0)`).
3108///
3109/// Why a deadline exists at all: nothing else bounds how long one request may occupy a `--parallel`
3110/// slot. `max_tokens_cap` bounds TOKENS, and its 128k default is many hours on a slow model. Why it
3111/// is OFF by default: firing mid-generation truncates a legitimate long reply, and only the operator
3112/// knows their model's token rate.
3113fn request_timeout(cfg: &Config) -> Option<Duration> {
3114    let secs = cfg.serve.request_timeout_secs;
3115    (secs > 0).then(|| Duration::from_secs(secs))
3116}
3117
3118/// Arm a wall-clock deadline over a generation that OUTLIVES the handler — i.e. the streaming path,
3119/// where the SSE response is returned immediately and the `spawn_blocking` task keeps producing
3120/// into a channel with nobody awaiting its join.
3121///
3122/// **It sets the generator's abort latch; it does not cancel anything.** `spawn_blocking` tasks are
3123/// NOT cancellable: `tokio::time::timeout` around a `JoinHandle` only stops the caller waiting —
3124/// the blocking thread runs on, still holding its `OwnedSemaphorePermit`, so the slot the deadline
3125/// exists to reclaim is exactly the thing that is not reclaimed. Latching `cancel` instead drives
3126/// the mechanism the decode loop already polls (see [`ChatGenerator::chat`]): the generator stops at
3127/// its next token boundary, returns normally, and the permit drops on the way out.
3128///
3129/// `hit` is a SECOND flag rather than a re-read of `cancel`, because `cancel` is also latched by a
3130/// client disconnect — the finish reason must say "the budget ran out", not "the socket died". It
3131/// is stored BEFORE `cancel` so a decode loop that observes the abort and returns instantly still
3132/// finds the label set.
3133///
3134/// **Teardown.** The returned [`oneshot::Sender`](tokio::sync::oneshot::Sender) is the "generation
3135/// finished" signal: move it into the blocking task and let it DROP there. A dropped sender
3136/// resolves the receiver (with `Err`), the `select!` takes that arm, and the watchdog task ends —
3137/// so a server that has served a million requests holds zero sleeping tasks. Drop is the right
3138/// trigger rather than an explicit `send`: it also fires while UNWINDING from a panic inside the
3139/// decode closure, which an explicit send at the end of the happy path would skip, leaking one task
3140/// per panicking request. (`JoinHandle::abort` would work too, but the handler would then have to
3141/// own and remember to abort a handle across two exit paths; a value whose destructor IS the signal
3142/// cannot be forgotten.)
3143fn arm_deadline(
3144    d: Duration,
3145    cancel: Arc<AtomicBool>,
3146    hit: Arc<AtomicBool>,
3147) -> tokio::sync::oneshot::Sender<()> {
3148    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
3149    tokio::spawn(async move {
3150        tokio::select! {
3151            _ = tokio::time::sleep(d) => {
3152                hit.store(true, Ordering::Relaxed);
3153                cancel.store(true, Ordering::Relaxed);
3154                tracing::warn!(timeout_s = d.as_secs(), "request deadline hit — aborting generation");
3155            }
3156            _ = done_rx => {}
3157        }
3158    });
3159    done_tx
3160}
3161
3162/// Latch `cancel` the moment the streaming client hangs up, i.e. when the SSE receiver `tx` feeds
3163/// is dropped — not at the next delta, which may be a whole prefill away.
3164///
3165/// Same teardown shape as [`arm_deadline`]: the returned sender is the "generation finished"
3166/// signal, moved into the blocking task and dropped there (also on unwind). The watcher holds a
3167/// clone of `tx`, and the SSE stream only ends once every sender is gone, so it MUST end with the
3168/// generation or a finished stream would never close.
3169fn cancel_on_hangup(
3170    tx: &tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
3171    cancel: Arc<AtomicBool>,
3172) -> tokio::sync::oneshot::Sender<()> {
3173    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
3174    let tx = tx.clone();
3175    tokio::spawn(async move {
3176        tokio::select! {
3177            _ = tx.closed() => cancel.store(true, Ordering::Relaxed),
3178            _ = done_rx => {}
3179        }
3180    });
3181    done_tx
3182}
3183
3184/// Latches its flag when dropped — the non-streaming handler's hang-up signal (see [`non_streaming`]).
3185struct CancelOnDrop(Arc<AtomicBool>);
3186
3187impl Drop for CancelOnDrop {
3188    fn drop(&mut self) {
3189        self.0.store(true, Ordering::Relaxed);
3190    }
3191}
3192
3193/// Optional bearer-token gate. `expected` is the configured API key (`INFR_API_KEY`), or `None`
3194/// when auth is DISABLED — in which case every request is allowed (default; preserves existing
3195/// localhost usage). When a key IS configured, the request must carry
3196/// `Authorization: Bearer <key>` with a matching token (audit finding 5).
3197///
3198/// The token comparison is CONSTANT TIME ([`subtle::ConstantTimeEq`]), not `==`. `str`/`[u8]`
3199/// equality bails out at the first differing byte, so the time to answer a request grows with how
3200/// many leading bytes of the key the attacker guessed right. Against a server reachable over a
3201/// network that is a byte-at-a-time oracle: guess byte 0 (256 tries), keep the value that answers
3202/// measurably slower, move to byte 1 — the key falls in time linear in its length instead of
3203/// exponential. `ct_eq` folds `|=` over the XOR of every byte pair and only then collapses the
3204/// accumulator to a `Choice`, so the answer costs the same whether the token differs in the first
3205/// byte or the last. It is used rather than a hand-rolled loop because "no early exit" also has to
3206/// survive the optimizer, which is exactly what `subtle` is written (and volatile-fenced) to do.
3207///
3208/// LENGTH IS STILL LEAKED — `ct_eq` short-circuits when the slices differ in length, so a wrong
3209/// token of the wrong length is rejected faster than a wrong token of the right one. That is an
3210/// ACCEPTED trade, not an oversight: an attacker learns only how many bytes to send, which does
3211/// not narrow the search of the CONTENT in any useful way (a 32-byte random key still has 32 bytes
3212/// of entropy to guess), and the alternatives — hashing both sides first, or padding to a fixed
3213/// buffer — buy nothing an operator can spend. What must not leak is a per-byte signal, and that
3214/// is what the fold removes.
3215fn authorize(expected: Option<&str>, auth_header: Option<&str>) -> bool {
3216    match expected {
3217        None => true,
3218        Some(key) => auth_header
3219            .and_then(|h| {
3220                h.strip_prefix("Bearer ")
3221                    .or_else(|| h.strip_prefix("bearer "))
3222            })
3223            .map(str::trim)
3224            .is_some_and(|tok| bool::from(tok.as_bytes().ct_eq(key.as_bytes()))),
3225    }
3226}
3227
3228/// The optional bearer gate every PROTECTED route runs first: `Some(401)` when the request must be
3229/// refused, `None` when it may proceed.
3230///
3231/// Enforced ONLY when `serve.api_key` (`INFR_API_KEY`) is configured; with no key this returns
3232/// `None` for everything, so the default localhost server stays open exactly as it was.
3233///
3234/// It exists as ONE function because the gate is a policy, not a line of handler code: when
3235/// `/v1/models` was left ungated, an unauthenticated caller could still enumerate every hosted
3236/// model id off a server whose operator had set a key. A second handler spelling the check inline
3237/// is how that happens again, and a third would drift on the message or the status. The 401 body is
3238/// the shared [`error_body`] envelope, so it deserializes the same as every other failure this
3239/// server reports.
3240///
3241/// `/health` deliberately does NOT call this — see [`health_handler`].
3242fn auth_gate(cfg: &Config, headers: &HeaderMap) -> Option<Response> {
3243    let key = configured_api_key(cfg)?;
3244    let auth = headers.get("authorization").and_then(|v| v.to_str().ok());
3245    // OpenAI's own 401: the request is at fault (`invalid_request_error`), not the server.
3246    (!authorize(Some(key), auth)).then(|| {
3247        invalid_request(
3248            StatusCode::UNAUTHORIZED,
3249            None,
3250            Some("invalid_api_key"),
3251            "missing or invalid Authorization bearer token".into(),
3252        )
3253    })
3254}
3255
3256/// The configured API key, or `None` when `serve.api_key` (`INFR_API_KEY`) is unset OR EMPTY —
3257/// auth disabled.
3258///
3259/// The empty-string filter is load-bearing and is NOT the `is_ok()` presence grammar every other
3260/// knob uses: `INFR_API_KEY=` means "no auth", not "auth with the empty key". The env
3261/// layer already maps an empty value to `Some(None)`; the filter is kept here as well so a config
3262/// FILE saying `api_key = ""` means the same thing (this used to read the `INFR_API_KEY`
3263/// variable from the process environment and apply the same filter).
3264fn configured_api_key(cfg: &Config) -> Option<&str> {
3265    cfg.serve
3266        .api_key
3267        .as_deref()
3268        .filter(|k: &&str| !k.is_empty())
3269}
3270
3271fn unix_ts() -> i64 {
3272    SystemTime::now()
3273        .duration_since(UNIX_EPOCH)
3274        .unwrap_or_default()
3275        .as_secs() as i64
3276}
3277
3278/// Flatten a DTO `content` field (string OR content-part array) to a plain `String`.
3279///
3280/// Mirrors the Python shim's `normalize_messages`: only `"text"` parts are kept.
3281pub fn flatten_content(v: &Option<serde_json::Value>) -> String {
3282    match v {
3283        None | Some(serde_json::Value::Null) => String::new(),
3284        Some(serde_json::Value::String(s)) => s.clone(),
3285        Some(serde_json::Value::Array(parts)) => parts
3286            .iter()
3287            .filter_map(|p| {
3288                if p.get("type")?.as_str()? == "text" {
3289                    p.get("text")?.as_str().map(str::to_owned)
3290                } else {
3291                    None
3292                }
3293            })
3294            .collect::<Vec<_>>()
3295            .join(""),
3296        Some(other) => other.to_string(),
3297    }
3298}
3299
3300fn dto_to_engine(dto: &ChatMessageDto) -> ChatMessage {
3301    ChatMessage {
3302        role: dto.role.clone(),
3303        content: flatten_content(&dto.content),
3304        tool_calls: dto.tool_calls.as_ref().and_then(parse_oai_tool_calls),
3305        tool_call_id: dto.tool_call_id.clone(),
3306        name: dto.name.clone(),
3307    }
3308}
3309
3310/// Convert an inbound OpenAI `tool_calls` array (`[{function:{name, arguments}}]`, where `arguments`
3311/// is a JSON STRING) into engine [`ToolCall`]s with `arguments` parsed to a `Value`. Returns `None`
3312/// if the field isn't a non-empty array of valid calls.
3313fn parse_oai_tool_calls(v: &serde_json::Value) -> Option<Vec<ToolCall>> {
3314    let arr = v.as_array()?;
3315    let calls: Vec<ToolCall> = arr
3316        .iter()
3317        .filter_map(|c| {
3318            let f = c.get("function")?;
3319            let name = f.get("name")?.as_str()?.to_owned();
3320            let arguments = match f.get("arguments") {
3321                Some(serde_json::Value::String(s)) => {
3322                    serde_json::from_str(s).unwrap_or(serde_json::Value::String(s.clone()))
3323                }
3324                Some(other) => other.clone(),
3325                None => serde_json::Value::Object(serde_json::Map::new()),
3326            };
3327            let id = c.get("id").and_then(|v| v.as_str()).map(str::to_owned);
3328            Some(ToolCall {
3329                name,
3330                arguments,
3331                id,
3332            })
3333        })
3334        .collect();
3335    (!calls.is_empty()).then_some(calls)
3336}
3337
3338// ---------------------------------------------------------------------------
3339// Tests
3340// ---------------------------------------------------------------------------
3341
3342#[cfg(test)]
3343mod tests {
3344    use super::*;
3345    use axum::{body::Body, http::Request};
3346    use http_body_util::BodyExt;
3347    use tower::ServiceExt;
3348
3349    /// Router backed by a headless state — no Engine, so /health and /v1/models work
3350    /// but /v1/chat/completions would return 500.  That's fine: we never call it here.
3351    fn test_router() -> Router {
3352        build_router(AppState::headless(
3353            "test-model",
3354            Arc::new(Config::default()),
3355        ))
3356    }
3357
3358    // --- HTTP endpoint tests (no Engine required) ---------------------------
3359
3360    #[tokio::test]
3361    async fn test_health_returns_200() {
3362        let resp = test_router()
3363            .oneshot(
3364                Request::builder()
3365                    .uri("/health")
3366                    .body(Body::empty())
3367                    .unwrap(),
3368            )
3369            .await
3370            .unwrap();
3371        assert_eq!(resp.status(), StatusCode::OK);
3372    }
3373
3374    #[tokio::test]
3375    async fn test_models_returns_200_with_expected_shape() {
3376        let resp = test_router()
3377            .oneshot(
3378                Request::builder()
3379                    .uri("/v1/models")
3380                    .body(Body::empty())
3381                    .unwrap(),
3382            )
3383            .await
3384            .unwrap();
3385        assert_eq!(resp.status(), StatusCode::OK);
3386
3387        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3388        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3389
3390        assert_eq!(json["object"], "list");
3391        let card = &json["data"][0];
3392        assert_eq!(card["id"], "test-model");
3393        assert_eq!(card["object"], "model");
3394        assert_eq!(card["owned_by"], "local");
3395    }
3396
3397    /// The vocabulary every test generator reports, for the `logit_bias` id check.
3398    const TEST_VOCAB: usize = 1000;
3399
3400    /// What a test generator with nothing to say about its device reports.
3401    fn cpu_status() -> GeneratorStatus {
3402        GeneratorStatus {
3403            backend: "cpu",
3404            device: None,
3405            ctx_per_slot: None,
3406            memory: None,
3407        }
3408    }
3409
3410    /// A stub generator that streams back exactly one content delta naming the model it belongs to,
3411    /// so a routing test can prove WHICH generator answered.
3412    pub(crate) struct EchoGen(pub(crate) &'static str);
3413    impl ChatGenerator for EchoGen {
3414        fn status(&self) -> GeneratorStatus {
3415            GeneratorStatus {
3416                backend: "vulkan",
3417                device: Some(format!("dev-{}", self.0)),
3418                ctx_per_slot: Some(4096),
3419                memory: Some(DeviceMemory {
3420                    total_bytes: 8 << 30,
3421                    available_bytes: 6 << 30,
3422                    live: true,
3423                    unified: false,
3424                }),
3425            }
3426        }
3427
3428        fn vocab_size(&self) -> usize {
3429            TEST_VOCAB
3430        }
3431
3432        fn chat(
3433            &self,
3434            _messages: &[ChatMessage],
3435            _tools: Option<&serde_json::Value>,
3436            _tool_choice: Option<&str>,
3437            _params: &GenParams,
3438            _cancel: &Arc<AtomicBool>,
3439            on_delta: &mut dyn FnMut(Delta),
3440        ) -> anyhow::Result<ChatOutcome> {
3441            on_delta(Delta::Content(format!("from:{}", self.0)));
3442            Ok(ChatOutcome {
3443                finish: Finish::Stop,
3444                prompt_tokens: 3,
3445                completion_tokens: 2,
3446                cached_tokens: 0,
3447            })
3448        }
3449    }
3450
3451    /// A generator that reports one token's log probability and then its text.
3452    struct LogprobGen;
3453    impl ChatGenerator for LogprobGen {
3454        fn status(&self) -> GeneratorStatus {
3455            cpu_status()
3456        }
3457
3458        fn vocab_size(&self) -> usize {
3459            TEST_VOCAB
3460        }
3461
3462        fn supports_logprobs(&self) -> bool {
3463            true
3464        }
3465
3466        fn chat(
3467            &self,
3468            _messages: &[ChatMessage],
3469            _tools: Option<&serde_json::Value>,
3470            _tool_choice: Option<&str>,
3471            params: &GenParams,
3472            _cancel: &Arc<AtomicBool>,
3473            on_delta: &mut dyn FnMut(Delta),
3474        ) -> anyhow::Result<ChatOutcome> {
3475            assert!(params.logprobs, "the server only asks when requested");
3476            let mut top = vec![infr_engine::TokenLogprobAlt {
3477                token: 9,
3478                text: "ho".into(),
3479                bytes: b"ho".to_vec(),
3480                logprob: -1.5,
3481            }];
3482            top.truncate(params.top_logprobs);
3483            on_delta(Delta::Logprob(infr_engine::TokenLogprob {
3484                token: 7,
3485                text: "hi".into(),
3486                bytes: b"hi".to_vec(),
3487                logprob: -0.25,
3488                top,
3489            }));
3490            on_delta(Delta::Content("hi".into()));
3491            Ok(ChatOutcome {
3492                finish: Finish::Stop,
3493                prompt_tokens: 1,
3494                completion_tokens: 1,
3495                cached_tokens: 0,
3496            })
3497        }
3498    }
3499
3500    fn multi_router() -> Router {
3501        let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
3502        let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
3503        build_router(AppState::multi(
3504            vec![("alpha".into(), a, 2), ("beta".into(), b, 2)],
3505            Arc::new(Config::default()),
3506        ))
3507    }
3508
3509    #[tokio::test]
3510    async fn multi_models_are_all_listed() {
3511        let resp = multi_router()
3512            .oneshot(
3513                Request::builder()
3514                    .uri("/v1/models")
3515                    .body(Body::empty())
3516                    .unwrap(),
3517            )
3518            .await
3519            .unwrap();
3520        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3521        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3522        let ids: Vec<&str> = json["data"]
3523            .as_array()
3524            .unwrap()
3525            .iter()
3526            .map(|c| c["id"].as_str().unwrap())
3527            .collect();
3528        assert_eq!(ids, vec!["alpha", "beta"]);
3529    }
3530
3531    /// A request naming `beta` must be answered by beta's generator; an unknown name falls to the
3532    /// default (first-listed `alpha`). This is the whole multi-model routing contract.
3533    async fn chat_model_field(router: Router, requested: &str) -> (String, String) {
3534        let body =
3535            format!(r#"{{"model":"{requested}","messages":[{{"role":"user","content":"hi"}}]}}"#);
3536        let resp = router
3537            .oneshot(
3538                Request::builder()
3539                    .method("POST")
3540                    .uri("/v1/chat/completions")
3541                    .header("content-type", "application/json")
3542                    .body(Body::from(body))
3543                    .unwrap(),
3544            )
3545            .await
3546            .unwrap();
3547        assert_eq!(resp.status(), StatusCode::OK);
3548        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3549        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3550        (
3551            json["model"].as_str().unwrap().to_string(),
3552            json["choices"][0]["message"]["content"]
3553                .as_str()
3554                .unwrap()
3555                .to_string(),
3556        )
3557    }
3558
3559    #[tokio::test]
3560    async fn request_routes_to_named_model() {
3561        let (model, content) = chat_model_field(multi_router(), "beta").await;
3562        assert_eq!(model, "beta");
3563        assert_eq!(content, "from:beta");
3564    }
3565
3566    #[tokio::test]
3567    async fn unknown_model_falls_to_default() {
3568        let (model, content) = chat_model_field(multi_router(), "does-not-exist").await;
3569        assert_eq!(model, "alpha");
3570        assert_eq!(content, "from:alpha");
3571    }
3572
3573    // --- ChatRequest serde round-trip tests --------------------------------
3574
3575    #[test]
3576    fn chat_request_string_content_deserializes() {
3577        let raw = r#"{"model":"m","messages":[{"role":"user","content":"hello"}]}"#;
3578        let req: ChatRequest = serde_json::from_str(raw).unwrap();
3579        assert_eq!(req.messages[0].role, "user");
3580        assert_eq!(flatten_content(&req.messages[0].content), "hello");
3581        assert!(!req.stream);
3582        assert!(req.tools.is_none());
3583        assert!(req.max_tokens.is_none());
3584    }
3585
3586    #[test]
3587    fn chat_request_array_content_deserializes_and_flattens() {
3588        let raw = r#"{
3589            "model": "m",
3590            "messages": [{
3591                "role": "user",
3592                "content": [
3593                    {"type":"text","text":"hello"},
3594                    {"type":"image_url","image_url":{"url":"data:..."}},
3595                    {"type":"text","text":" world"}
3596                ]
3597            }]
3598        }"#;
3599        let req: ChatRequest = serde_json::from_str(raw).unwrap();
3600        // Only text parts are concatenated; image_url is discarded.
3601        assert_eq!(flatten_content(&req.messages[0].content), "hello world");
3602    }
3603
3604    #[test]
3605    fn chat_request_stream_flag() {
3606        let raw = r#"{"model":"m","messages":[],"stream":true}"#;
3607        let req: ChatRequest = serde_json::from_str(raw).unwrap();
3608        assert!(req.stream);
3609    }
3610
3611    #[test]
3612    fn chat_request_with_tools_and_max_tokens() {
3613        let raw = r#"{
3614            "model":"m","messages":[],
3615            "tools":[{"type":"function","function":{"name":"bash","description":"run bash"}}],
3616            "max_tokens":512
3617        }"#;
3618        let req: ChatRequest = serde_json::from_str(raw).unwrap();
3619        // The whole array arrives as sent: it is handed to the chat template verbatim, so a field
3620        // lost or reshaped here is a tool the model is never told about.
3621        assert_eq!(
3622            req.tools,
3623            Some(serde_json::json!([
3624                {"type": "function", "function": {"name": "bash", "description": "run bash"}}
3625            ]))
3626        );
3627        assert_eq!(req.max_tokens, Some(512));
3628        assert_eq!(req.max_completion_tokens, None);
3629        assert_eq!(req.tool_choice, None);
3630        assert!(req.messages.is_empty());
3631    }
3632
3633    #[test]
3634    fn chat_message_dto_with_tool_call_id_and_name() {
3635        let raw = r#"{"role":"tool","content":"result","tool_call_id":"tc_1","name":"bash"}"#;
3636        let msg: ChatMessageDto = serde_json::from_str(raw).unwrap();
3637        assert_eq!(msg.tool_call_id.as_deref(), Some("tc_1"));
3638        assert_eq!(msg.name.as_deref(), Some("bash"));
3639    }
3640
3641    /// A replayed assistant `tool_calls[].id` survives into the engine message, so the chat
3642    /// template can pair it with the `tool` result's `tool_call_id`.
3643    #[test]
3644    fn replayed_tool_call_keeps_its_id() {
3645        let raw = r#"{"role":"assistant","content":null,"tool_calls":[
3646            {"id":"a1B2c3D4e","type":"function",
3647             "function":{"name":"bash","arguments":"{\"cmd\":\"ls\"}"}},
3648            {"type":"function","function":{"name":"noid","arguments":"{}"}}]}"#;
3649        let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(raw).unwrap());
3650        let calls = msg.tool_calls.expect("two calls parse");
3651        assert_eq!(calls[0].id.as_deref(), Some("a1B2c3D4e"));
3652        assert_eq!(calls[0].arguments, serde_json::json!({"cmd": "ls"}));
3653        assert_eq!(calls[1].id, None);
3654    }
3655
3656    /// A float in a replayed tool call's arguments reaches the engine as the exact value the client
3657    /// sent, so the chat template prints the same digits back: whether the arguments come as a
3658    /// JSON string (the OpenAI shape) or as an object. Each of these lost its last digit when
3659    /// serde_json parsed without `float_roundtrip` (`1e-25` became `9.999999999999999e-26`).
3660    #[test]
3661    fn replayed_tool_call_floats_survive_exactly() {
3662        let floats = ["1e-25", "905046994.6356679", "2.5788702084023933e-304"];
3663        let args = format!(
3664            r#"{{"a":{},"b":{},"c":[{}]}}"#,
3665            floats[0], floats[1], floats[2]
3666        );
3667        for arguments in [serde_json::to_string(&args).unwrap(), args.clone()] {
3668            let raw = format!(
3669                r#"{{"role":"assistant","content":null,"tool_calls":[
3670                {{"type":"function","function":{{"name":"f","arguments":{arguments}}}}}]}}"#
3671            );
3672            let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(&raw).unwrap());
3673            let a = &msg.tool_calls.expect("one call")[0].arguments;
3674            let got = [&a["a"], &a["b"], &a["c"][0]].map(|v| v.as_f64().unwrap());
3675            let want = floats.map(|f| f.parse::<f64>().unwrap());
3676            assert_eq!(got.map(f64::to_bits), want.map(f64::to_bits), "{arguments}");
3677            // …and the prompt prints them back: bare (Python's `repr`) and through `tojson`.
3678            const PRINT: &str = "{% set a = messages[0].tool_calls[0].function.arguments %}\
3679                {{ a.a }} {{ a.b }} {{ a.c[0] }}|{{ a | tojson }}";
3680            let msgs = vec![serde_json::json!({"role": "assistant", "content": "",
3681                "tool_calls": [{"type": "function",
3682                                "function": {"name": "f", "arguments": a}}]})];
3683            let prompt = infr_chat::render_template(
3684                PRINT,
3685                msgs,
3686                serde_json::Value::Null,
3687                "",
3688                "",
3689                false,
3690                true,
3691            )
3692            .unwrap();
3693            assert_eq!(
3694                prompt,
3695                format!(
3696                    r#"{0} {1} {2}|{{"a": {0}, "b": {1}, "c": [{2}]}}"#,
3697                    floats[0], floats[1], floats[2]
3698                )
3699            );
3700        }
3701    }
3702
3703    /// The ids `serve` hands out are ones every supported template accepts when the client replays
3704    /// them: Mistral's requires exactly nine alphanumerics. They are distinct per call and per
3705    /// completion, and the same (cid, index) always yields the same id.
3706    #[test]
3707    fn minted_tool_call_ids_are_template_safe_and_distinct() {
3708        let mut seen = std::collections::HashSet::new();
3709        for _ in 0..1000 {
3710            let cid = make_id();
3711            for idx in 0..4 {
3712                let id = tool_call_id(&cid, idx);
3713                assert_eq!(id.len(), TOOL_CALL_ID_LEN, "{id}");
3714                assert!(id.bytes().all(|b| b.is_ascii_alphanumeric()), "{id}");
3715                assert!(seen.insert(id.clone()), "duplicate tool-call id {id}");
3716                assert_eq!(id, tool_call_id(&cid, idx));
3717            }
3718        }
3719    }
3720
3721    // --- Non-streaming response serialization tests ------------------------
3722
3723    #[test]
3724    fn chat_completion_response_stop_serializes() {
3725        let resp = ChatCompletionResponse {
3726            id: "chatcmpl-test".into(),
3727            object: "chat.completion",
3728            created: 1000,
3729            model: "test-model".into(),
3730            choices: vec![CompletionChoice {
3731                index: 0,
3732                message: AssistantMessage {
3733                    role: "assistant",
3734                    content: Some("hello".into()),
3735                    reasoning_content: None,
3736                    tool_calls: None,
3737                },
3738                logprobs: None,
3739                finish_reason: "stop".into(),
3740            }],
3741            usage: UsageInfo {
3742                prompt_tokens: 10,
3743                completion_tokens: 5,
3744                total_tokens: 15,
3745                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3746            },
3747        };
3748        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3749        assert_eq!(v["object"], "chat.completion");
3750        assert_eq!(v["choices"][0]["finish_reason"], "stop");
3751        assert_eq!(v["choices"][0]["message"]["role"], "assistant");
3752        assert_eq!(v["choices"][0]["message"]["content"], "hello");
3753        // skip_serializing_if = None → field absent in JSON → serde_json gives Null on access
3754        assert!(v["choices"][0]["message"]["reasoning_content"].is_null());
3755        assert!(v["choices"][0]["message"]["tool_calls"].is_null());
3756    }
3757
3758    #[test]
3759    fn chat_completion_response_with_reasoning_content() {
3760        let resp = ChatCompletionResponse {
3761            id: "id".into(),
3762            object: "chat.completion",
3763            created: 0,
3764            model: "m".into(),
3765            choices: vec![CompletionChoice {
3766                index: 0,
3767                message: AssistantMessage {
3768                    role: "assistant",
3769                    content: Some("answer".into()),
3770                    reasoning_content: Some("I thought about it".into()),
3771                    tool_calls: None,
3772                },
3773                logprobs: None,
3774                finish_reason: "stop".into(),
3775            }],
3776            usage: UsageInfo {
3777                prompt_tokens: 0,
3778                completion_tokens: 0,
3779                total_tokens: 0,
3780                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3781            },
3782        };
3783        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3784        assert_eq!(
3785            v["choices"][0]["message"]["reasoning_content"],
3786            "I thought about it"
3787        );
3788        assert_eq!(v["choices"][0]["message"]["content"], "answer");
3789    }
3790
3791    #[test]
3792    fn chat_completion_response_tool_calls_finish_reason() {
3793        let resp = ChatCompletionResponse {
3794            id: "id".into(),
3795            object: "chat.completion",
3796            created: 0,
3797            model: "m".into(),
3798            choices: vec![CompletionChoice {
3799                index: 0,
3800                message: AssistantMessage {
3801                    role: "assistant",
3802                    content: None,
3803                    reasoning_content: None,
3804                    tool_calls: Some(vec![OAIToolCall {
3805                        index: 0,
3806                        id: "call_0".into(),
3807                        kind: "function",
3808                        function: OAIFunction {
3809                            name: "bash".into(),
3810                            arguments: r#"{"command":"ls"}"#.into(),
3811                        },
3812                    }]),
3813                },
3814                logprobs: None,
3815                finish_reason: "tool_calls".into(),
3816            }],
3817            usage: UsageInfo {
3818                prompt_tokens: 0,
3819                completion_tokens: 0,
3820                total_tokens: 0,
3821                prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3822            },
3823        };
3824        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3825        assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");
3826        let tc = &v["choices"][0]["message"]["tool_calls"][0];
3827        assert_eq!(tc["type"], "function");
3828        assert_eq!(tc["function"]["name"], "bash");
3829        assert_eq!(tc["function"]["arguments"], r#"{"command":"ls"}"#);
3830        assert_eq!(tc["index"], 0);
3831        // content: None serializes as null
3832        assert!(v["choices"][0]["message"]["content"].is_null());
3833    }
3834
3835    // --- Streaming chunk serialization tests --------------------------------
3836
3837    #[test]
3838    fn streaming_chunk_role_delta() {
3839        let chunk = ChatCompletionChunk {
3840            id: "id".into(),
3841            object: "chat.completion.chunk",
3842            created: 0,
3843            model: "m".into(),
3844            choices: vec![ChunkChoice {
3845                index: 0,
3846                delta: DeltaPayload {
3847                    role: Some("assistant".into()),
3848                    ..Default::default()
3849                },
3850                logprobs: None,
3851                finish_reason: None,
3852            }],
3853            usage: None,
3854        };
3855        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3856        assert_eq!(v["object"], "chat.completion.chunk");
3857        assert_eq!(v["choices"][0]["delta"]["role"], "assistant");
3858        // Other delta fields absent
3859        assert!(v["choices"][0]["delta"]["content"].is_null());
3860        assert!(v["choices"][0]["delta"]["reasoning_content"].is_null());
3861        assert!(v["choices"][0]["delta"]["tool_calls"].is_null());
3862        assert!(v["choices"][0]["finish_reason"].is_null());
3863    }
3864
3865    #[test]
3866    fn streaming_chunk_content_delta() {
3867        let chunk = ChatCompletionChunk {
3868            id: "id".into(),
3869            object: "chat.completion.chunk",
3870            created: 0,
3871            model: "m".into(),
3872            choices: vec![ChunkChoice {
3873                index: 0,
3874                delta: DeltaPayload {
3875                    content: Some("hello".into()),
3876                    ..Default::default()
3877                },
3878                logprobs: None,
3879                finish_reason: None,
3880            }],
3881            usage: None,
3882        };
3883        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3884        assert_eq!(v["choices"][0]["delta"]["content"], "hello");
3885        assert!(v["choices"][0]["delta"]["role"].is_null());
3886    }
3887
3888    #[test]
3889    fn streaming_chunk_reasoning_content_delta() {
3890        let chunk = ChatCompletionChunk {
3891            id: "id".into(),
3892            object: "chat.completion.chunk",
3893            created: 0,
3894            model: "m".into(),
3895            choices: vec![ChunkChoice {
3896                index: 0,
3897                delta: DeltaPayload {
3898                    reasoning_content: Some("thinking...".into()),
3899                    ..Default::default()
3900                },
3901                logprobs: None,
3902                finish_reason: None,
3903            }],
3904            usage: None,
3905        };
3906        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3907        assert_eq!(v["choices"][0]["delta"]["reasoning_content"], "thinking...");
3908        assert!(v["choices"][0]["delta"]["content"].is_null());
3909    }
3910
3911    #[test]
3912    fn streaming_chunk_tool_call_delta() {
3913        let chunk = ChatCompletionChunk {
3914            id: "id".into(),
3915            object: "chat.completion.chunk",
3916            created: 0,
3917            model: "m".into(),
3918            choices: vec![ChunkChoice {
3919                index: 0,
3920                delta: DeltaPayload {
3921                    tool_calls: Some(vec![OAIToolCall {
3922                        index: 0,
3923                        id: "call_0".into(),
3924                        kind: "function",
3925                        function: OAIFunction {
3926                            name: "bash".into(),
3927                            arguments: r#"{"cmd":"ls"}"#.into(),
3928                        },
3929                    }]),
3930                    ..Default::default()
3931                },
3932                logprobs: None,
3933                finish_reason: None,
3934            }],
3935            usage: None,
3936        };
3937        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3938        let tc = &v["choices"][0]["delta"]["tool_calls"][0];
3939        assert_eq!(tc["index"], 0);
3940        assert_eq!(tc["type"], "function");
3941        assert_eq!(tc["function"]["name"], "bash");
3942    }
3943
3944    #[test]
3945    fn streaming_chunk_finish_reason() {
3946        let chunk = ChatCompletionChunk {
3947            id: "id".into(),
3948            object: "chat.completion.chunk",
3949            created: 0,
3950            model: "m".into(),
3951            choices: vec![ChunkChoice {
3952                index: 0,
3953                delta: DeltaPayload::default(), // empty delta {}
3954                logprobs: None,
3955                finish_reason: Some("stop".into()),
3956            }],
3957            usage: None,
3958        };
3959        let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3960        assert_eq!(v["choices"][0]["finish_reason"], "stop");
3961        // Empty delta: all fields None → absent in JSON
3962        assert!(v["choices"][0]["delta"]["content"].is_null());
3963        assert!(v["choices"][0]["delta"]["role"].is_null());
3964    }
3965
3966    // --- /v1/models serialization test ------------------------------------
3967
3968    #[test]
3969    fn models_response_serializes() {
3970        let resp = ModelsResponse {
3971            object: "list",
3972            data: vec![ModelCard {
3973                id: "my-model".into(),
3974                object: "model",
3975                owned_by: "local",
3976            }],
3977        };
3978        let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3979        assert_eq!(v["object"], "list");
3980        assert_eq!(v["data"][0]["id"], "my-model");
3981        assert_eq!(v["data"][0]["object"], "model");
3982        assert_eq!(v["data"][0]["owned_by"], "local");
3983    }
3984
3985    // --- sampling param plumbing -------------------------------------------
3986
3987    fn req(raw: &str) -> ChatRequest {
3988        serde_json::from_str(raw).unwrap()
3989    }
3990
3991    #[test]
3992    fn absent_sampling_fields_stay_none() {
3993        // The whole point of Option-everything: a request that says nothing must not override the
3994        // process defaults (INFR_TEMP/TOP_K/TOP_P), i.e. today's behavior is preserved exactly.
3995        let p = GenParams::from_request(&req(
3996            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
3997        ))
3998        .unwrap();
3999        assert_eq!(p, GenParams::default());
4000    }
4001
4002    #[test]
4003    fn sampling_fields_parse() {
4004        let p = GenParams::from_request(&req(
4005            r#"{"model":"m","messages":[],"temperature":0.0,"top_p":0.9,"top_k":40,"seed":42,
4006                "presence_penalty":0.5,"frequency_penalty":-0.25,"repeat_penalty":1.1,
4007                "stop":["\n\n","END"]}"#,
4008        ))
4009        .unwrap();
4010        assert_eq!(p.temperature, Some(0.0));
4011        assert_eq!(p.top_p, Some(0.9));
4012        assert_eq!(p.top_k, Some(40));
4013        assert_eq!(p.seed, Some(42));
4014        assert_eq!(p.presence_penalty, Some(0.5));
4015        assert_eq!(p.frequency_penalty, Some(-0.25));
4016        assert_eq!(p.repeat_penalty, Some(1.1));
4017        assert_eq!(p.stop, vec!["\n\n".to_string(), "END".to_string()]);
4018    }
4019
4020    #[test]
4021    fn unknown_fields_are_ignored_not_rejected() {
4022        let p = GenParams::from_request(&req(
4023            r#"{"model":"m","messages":[],"user":"bob","response_format":{"type":"text"}}"#,
4024        ))
4025        .unwrap();
4026        assert_eq!(p, GenParams::default());
4027    }
4028
4029    /// The values of `n`, `logprobs`, `top_logprobs` and `logit_bias` that ask for nothing
4030    /// unsupported — one choice, no log probabilities, no bias, or `null` — are accepted.
4031    #[test]
4032    fn neutral_choice_and_logprob_fields_are_accepted() {
4033        for raw in [
4034            r#"{"model":"m","messages":[],"n":1,"logprobs":false,"top_logprobs":0,"logit_bias":{}}"#,
4035            r#"{"model":"m","messages":[],"n":null,"logprobs":null,"top_logprobs":null,
4036                "logit_bias":null,"min_p":null}"#,
4037        ] {
4038            let p = GenParams::from_request(&req(raw)).unwrap();
4039            assert_eq!(p, GenParams::default(), "{raw}");
4040        }
4041    }
4042
4043    #[test]
4044    fn min_p_and_logit_bias_parse() {
4045        let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"min_p":0.05,
4046                "logit_bias":{"50256":-100,"7":3.5,"12":100}}"#))
4047        .unwrap();
4048        assert_eq!(p.min_p, Some(0.05));
4049        assert_eq!(p.logit_bias, vec![(7, 3.5), (12, 100.0), (50256, -100.0)]);
4050    }
4051
4052    /// `0` is a canonical id, and a whole-number float `n` / `top_logprobs` reads as that integer
4053    /// (as OpenAI's own validation does): `n: 1.0` is one choice.
4054    #[test]
4055    fn zero_ids_and_whole_number_counts_are_accepted() {
4056        let p = GenParams::from_request(&req(
4057            r#"{"model":"m","messages":[],"n":1.0,"top_logprobs":0.0,"logit_bias":{"0":-1}}"#,
4058        ))
4059        .unwrap();
4060        assert_eq!(p.logit_bias, vec![(0, -1.0)]);
4061    }
4062
4063    /// A `logit_bias` id is a token only below the routed model's vocabulary size.
4064    #[test]
4065    fn logit_bias_ids_are_checked_against_the_vocabulary() {
4066        let p = GenParams::from_request(&req(
4067            r#"{"model":"m","messages":[],"logit_bias":{"999":1,"3":-1}}"#,
4068        ))
4069        .unwrap();
4070        assert_eq!(p.check_vocab(1000), Ok(()));
4071        let e = p.check_vocab(999).unwrap_err();
4072        assert_eq!(e.param, "logit_bias");
4073        assert!(e.message.contains("999"), "{}", e.message);
4074    }
4075
4076    #[test]
4077    fn max_completion_tokens_is_preferred_alias() {
4078        let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"max_tokens":10}"#))
4079            .unwrap();
4080        assert_eq!(p.max_tokens, Some(10));
4081        let p = GenParams::from_request(&req(
4082            r#"{"model":"m","messages":[],"max_completion_tokens":20}"#,
4083        ))
4084        .unwrap();
4085        assert_eq!(p.max_tokens, Some(20));
4086        // Both present: the new name wins.
4087        let p = GenParams::from_request(&req(
4088            r#"{"model":"m","messages":[],"max_tokens":10,"max_completion_tokens":20}"#,
4089        ))
4090        .unwrap();
4091        assert_eq!(p.max_tokens, Some(20));
4092    }
4093
4094    #[test]
4095    fn logprobs_are_accepted_and_bounded() {
4096        let p = GenParams::from_request(&req(
4097            r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":5}"#,
4098        ))
4099        .unwrap();
4100        assert!(p.logprobs);
4101        assert_eq!(p.top_logprobs, 5);
4102
4103        // llama.cpp's default: logprobs on with no `top_logprobs` reports 20 alternatives.
4104        let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"logprobs":true}"#))
4105            .unwrap();
4106        assert!(p.logprobs);
4107        assert_eq!(p.top_logprobs, MAX_TOP_LOGPROBS);
4108
4109        let p = GenParams::from_request(&req(
4110            r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":0}"#,
4111        ))
4112        .unwrap();
4113        assert!(p.logprobs);
4114        assert_eq!(p.top_logprobs, 0);
4115    }
4116
4117    #[test]
4118    fn stop_accepts_a_bare_string() {
4119        let p =
4120            GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":"\n"}"#)).unwrap();
4121        assert_eq!(p.stop, vec!["\n".to_string()]);
4122    }
4123
4124    #[test]
4125    fn empty_stop_strings_are_dropped() {
4126        // An empty stop would match at position 0 of every step — kill it at the door.
4127        let p =
4128            GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":["",""]}"#)).unwrap();
4129        assert!(p.stop.is_empty());
4130    }
4131
4132    #[test]
4133    fn invalid_values_are_param_errors_not_clamps() {
4134        for (raw, param) in [
4135            (
4136                r#"{"model":"m","messages":[],"temperature":-1}"#,
4137                "temperature",
4138            ),
4139            (
4140                r#"{"model":"m","messages":[],"temperature":3}"#,
4141                "temperature",
4142            ),
4143            (r#"{"model":"m","messages":[],"top_p":5}"#, "top_p"),
4144            (r#"{"model":"m","messages":[],"top_k":-2}"#, "top_k"),
4145            (
4146                r#"{"model":"m","messages":[],"presence_penalty":-3}"#,
4147                "presence_penalty",
4148            ),
4149            (
4150                r#"{"model":"m","messages":[],"frequency_penalty":9}"#,
4151                "frequency_penalty",
4152            ),
4153            (
4154                r#"{"model":"m","messages":[],"repeat_penalty":0}"#,
4155                "repeat_penalty",
4156            ),
4157            (r#"{"model":"m","messages":[],"stop":[1,2]}"#, "stop"),
4158            (
4159                r#"{"model":"m","messages":[],"stop":["a","b","c","d","e"]}"#,
4160                "stop",
4161            ),
4162            (r#"{"model":"m","messages":[],"min_p":-0.1}"#, "min_p"),
4163            (r#"{"model":"m","messages":[],"min_p":1.5}"#, "min_p"),
4164            (
4165                r#"{"model":"m","messages":[],"logit_bias":[1]}"#,
4166                "logit_bias",
4167            ),
4168            (
4169                r#"{"model":"m","messages":[],"logit_bias":{"a":1}}"#,
4170                "logit_bias",
4171            ),
4172            (
4173                r#"{"model":"m","messages":[],"logit_bias":{"-1":1}}"#,
4174                "logit_bias",
4175            ),
4176            (
4177                r#"{"model":"m","messages":[],"logit_bias":{"5":"x"}}"#,
4178                "logit_bias",
4179            ),
4180            (
4181                r#"{"model":"m","messages":[],"logit_bias":{"5":100.5}}"#,
4182                "logit_bias",
4183            ),
4184            (
4185                r#"{"model":"m","messages":[],"logit_bias":{"5":-101}}"#,
4186                "logit_bias",
4187            ),
4188            (r#"{"model":"m","messages":[],"n":2}"#, "n"),
4189            (r#"{"model":"m","messages":[],"n":0}"#, "n"),
4190            (
4191                r#"{"model":"m","messages":[],"top_logprobs":3}"#,
4192                "top_logprobs",
4193            ),
4194            (
4195                r#"{"model":"m","messages":[],"top_logprobs":-1}"#,
4196                "top_logprobs",
4197            ),
4198            // Only canonical decimal ids: each of these names token 5 a second way, and together
4199            // they would stack past the bias range on one token.
4200            (
4201                r#"{"model":"m","messages":[],"logit_bias":{"+5":-100}}"#,
4202                "logit_bias",
4203            ),
4204            (
4205                r#"{"model":"m","messages":[],"logit_bias":{"05":-100}}"#,
4206                "logit_bias",
4207            ),
4208            (
4209                r#"{"model":"m","messages":[],"logit_bias":{" 5":-100}}"#,
4210                "logit_bias",
4211            ),
4212            (
4213                r#"{"model":"m","messages":[],"logit_bias":{"":-100}}"#,
4214                "logit_bias",
4215            ),
4216            // The same id twice, which a JSON object map would otherwise collapse to one.
4217            (
4218                r#"{"model":"m","messages":[],"logit_bias":{"5":-100,"5":-100}}"#,
4219                "logit_bias",
4220            ),
4221            (r#"{"model":"m","messages":[],"n":1.5}"#, "n"),
4222            (r#"{"model":"m","messages":[],"n":"1"}"#, "n"),
4223            (
4224                r#"{"model":"m","messages":[],"top_logprobs":0.5}"#,
4225                "top_logprobs",
4226            ),
4227            (
4228                r#"{"model":"m","messages":[],"top_logprobs":[]}"#,
4229                "top_logprobs",
4230            ),
4231            (
4232                r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":21}"#,
4233                "top_logprobs",
4234            ),
4235        ] {
4236            let e = GenParams::from_request(&req(raw)).unwrap_err();
4237            assert_eq!(e.param, param, "{raw}");
4238        }
4239    }
4240
4241    #[tokio::test]
4242    async fn bad_temperature_returns_openai_shaped_400() {
4243        let resp = test_router()
4244            .oneshot(
4245                Request::builder()
4246                    .method("POST")
4247                    .uri("/v1/chat/completions")
4248                    .header("content-type", "application/json")
4249                    .body(Body::from(
4250                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":-1}"#,
4251                    ))
4252                    .unwrap(),
4253            )
4254            .await
4255            .unwrap();
4256        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4257        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4258        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4259        assert_eq!(v["error"]["type"], "invalid_request_error");
4260        assert_eq!(v["error"]["param"], "temperature");
4261    }
4262
4263    // --- StopMatcher: the token-boundary case -------------------------------
4264
4265    /// Drive a matcher over a token sequence, returning (emitted text, hit).
4266    fn run_stops(stops: &[&str], pieces: &[&str]) -> (String, bool) {
4267        let mut m = StopMatcher::new(stops.iter().map(|s| s.to_string()).collect());
4268        let mut out = String::new();
4269        for p in pieces {
4270            out.push_str(&m.push(p));
4271            if m.hit() {
4272                break;
4273            }
4274        }
4275        if !m.hit() {
4276            out.push_str(&m.flush());
4277        }
4278        (out, m.hit())
4279    }
4280
4281    #[test]
4282    fn stop_within_one_token_fires_and_is_excluded() {
4283        let (out, hit) = run_stops(&["END"], &["hello ", "END", " more"]);
4284        assert!(hit);
4285        assert_eq!(out, "hello ");
4286    }
4287
4288    #[test]
4289    fn stop_split_across_two_tokens_still_fires() {
4290        // THE boundary case: "END" arrives as "E" + "ND". It must fire, and the partial "E" must
4291        // NEVER have been emitted.
4292        let (out, hit) = run_stops(&["END"], &["hello ", "E", "ND", " more"]);
4293        assert!(hit, "a stop split across tokens must fire");
4294        assert_eq!(out, "hello ", "no partial stop prefix may leak");
4295    }
4296
4297    #[test]
4298    fn stop_split_across_three_tokens_still_fires() {
4299        let (out, hit) = run_stops(&["<|done|>"], &["a", "<|", "do", "ne", "|>", "b"]);
4300        assert!(hit);
4301        assert_eq!(out, "a");
4302    }
4303
4304    #[test]
4305    fn double_newline_stop_split_across_tokens() {
4306        let (out, hit) = run_stops(&["\n\n"], &["line", "\n", "\n", "next"]);
4307        assert!(hit);
4308        assert_eq!(out, "line");
4309    }
4310
4311    #[test]
4312    fn stop_prefix_that_does_not_complete_is_eventually_emitted() {
4313        // "E" looked like the start of "END" but turned out to be "Every" — it must still be
4314        // delivered, exactly once, in order.
4315        let (out, hit) = run_stops(&["END"], &["E", "very", " day"]);
4316        assert!(!hit);
4317        assert_eq!(out, "Every day");
4318    }
4319
4320    #[test]
4321    fn held_prefix_is_flushed_at_end_of_generation() {
4322        // Generation ends while the matcher still holds a partial prefix -> flush must emit it.
4323        let (out, hit) = run_stops(&["END"], &["done E"]);
4324        assert!(!hit);
4325        assert_eq!(out, "done E");
4326    }
4327
4328    #[test]
4329    fn multiple_stops_take_the_earliest_match() {
4330        let (out, hit) = run_stops(&["World", "lo"], &["hel", "lo World"]);
4331        assert!(hit);
4332        assert_eq!(out, "hel");
4333    }
4334
4335    #[test]
4336    fn no_stops_is_a_passthrough() {
4337        let (out, hit) = run_stops(&[], &["a", "b", "c"]);
4338        assert!(!hit);
4339        assert_eq!(out, "abc");
4340        assert!(!StopMatcher::new(vec![]).is_active());
4341    }
4342
4343    #[test]
4344    fn multibyte_stop_split_mid_codepoint_is_safe() {
4345        // Pieces are always whole UTF-8, but a stop's own bytes may straddle them: "→END" arriving
4346        // as "→" + "END". Must fire without panicking on a char boundary.
4347        let (out, hit) = run_stops(&["→END"], &["x", "→", "END", "y"]);
4348        assert!(hit);
4349        assert_eq!(out, "x");
4350    }
4351
4352    #[test]
4353    fn nothing_is_emitted_after_a_hit() {
4354        let mut m = StopMatcher::new(vec!["END".into()]);
4355        assert_eq!(m.push("aEND"), "a");
4356        assert!(m.hit());
4357        assert_eq!(m.push("more"), "");
4358        assert_eq!(m.flush(), "");
4359    }
4360
4361    // --- finish_reason ------------------------------------------------------
4362
4363    #[test]
4364    fn finish_reason_strings() {
4365        assert_eq!(Finish::Stop.as_str(), "stop");
4366        assert_eq!(Finish::Length.as_str(), "length");
4367        assert_eq!(Finish::ToolCalls.as_str(), "tool_calls");
4368    }
4369
4370    // --- flatten_content unit tests ----------------------------------------
4371
4372    #[test]
4373    fn flatten_content_string_value() {
4374        let v = Some(serde_json::Value::String("hello world".into()));
4375        assert_eq!(flatten_content(&v), "hello world");
4376    }
4377
4378    #[test]
4379    fn flatten_content_array_skips_non_text_parts() {
4380        let v = Some(serde_json::json!([
4381            {"type": "text",      "text": "hello"},
4382            {"type": "image_url", "image_url": {"url": "http://x"}},
4383            {"type": "text",      "text": " world"}
4384        ]));
4385        assert_eq!(flatten_content(&v), "hello world");
4386    }
4387
4388    #[test]
4389    fn flatten_content_none_gives_empty_string() {
4390        assert_eq!(flatten_content(&None), "");
4391    }
4392
4393    #[test]
4394    fn flatten_content_null_json_gives_empty_string() {
4395        // An assistant tool-call message legally has `content: null` — it must flatten to "" (not the
4396        // literal "null", which would inject a stray word into the prompt).
4397        assert_eq!(flatten_content(&Some(serde_json::Value::Null)), "");
4398    }
4399
4400    /// CHARACTERIZATION TEST — pins current behaviour, does not ask for a change.
4401    ///
4402    /// OpenAI's schema says `content` is a string or an array of content parts. A number, a
4403    /// bool or an object is a client bug. `flatten_content`'s fallback arm renders such a value
4404    /// with `Value::to_string()` (its JSON form) and feeds that to the prompt rather than
4405    /// erroring or dropping it. That leniency is DELIBERATE: a chat request that is merely
4406    /// sloppily typed still produces a sensible completion instead of a 400, and the rendered
4407    /// form is at least visible to the user in the echoed prompt rather than silently vanishing.
4408    ///
4409    /// It is pinned here because nothing else pins it: the arm is a one-liner a future refactor
4410    /// could plausibly "tidy" into `String::new()` or a rejection, silently changing what every
4411    /// such request produces. If this test fails, the change was intentional or it was not —
4412    /// decide, don't just re-bless.
4413    ///
4414    /// Note the exact rendering: `Value::to_string` is compact JSON, so a string INSIDE an
4415    /// object keeps its quotes, and `null` never reaches this arm (it is handled above).
4416    #[test]
4417    fn flatten_content_non_string_renders_json_leniently() {
4418        use serde_json::json;
4419        assert_eq!(flatten_content(&Some(json!(42))), "42");
4420        assert_eq!(flatten_content(&Some(json!(-1.5))), "-1.5");
4421        assert_eq!(flatten_content(&Some(json!(true))), "true");
4422        assert_eq!(flatten_content(&Some(json!(false))), "false");
4423        assert_eq!(flatten_content(&Some(json!({"a": 1}))), r#"{"a":1}"#);
4424        assert_eq!(
4425            flatten_content(&Some(json!({"a": "b", "c": [1, 2]}))),
4426            r#"{"a":"b","c":[1,2]}"#
4427        );
4428    }
4429
4430    // --- make_id uniqueness (audit finding 4) ------------------------------
4431
4432    #[test]
4433    fn make_id_is_unique_across_rapid_calls() {
4434        // Two completions minted in the same millisecond (routine under --parallel N) must NOT
4435        // collide — the monotonic suffix guarantees it even when the ms component is identical.
4436        let n = 10_000;
4437        let ids: std::collections::HashSet<String> = (0..n).map(|_| make_id()).collect();
4438        assert_eq!(ids.len(), n, "make_id produced a collision");
4439    }
4440
4441    // --- usage totals (audit finding 3) ------------------------------------
4442
4443    #[test]
4444    fn usage_total_is_prompt_plus_completion() {
4445        // The real fix: total == prompt + completion, from real counts, not content.len()/4.
4446        let outcome = ChatOutcome {
4447            finish: Finish::Stop,
4448            prompt_tokens: 17,
4449            completion_tokens: 5,
4450            cached_tokens: 0,
4451        };
4452        let usage = UsageInfo::from_outcome(&outcome);
4453        assert_eq!(usage.total_tokens, 22);
4454        assert_eq!(
4455            usage.total_tokens,
4456            usage.prompt_tokens + usage.completion_tokens
4457        );
4458    }
4459
4460    /// End-to-end: the non-streaming handler must surface the generator's REAL counts (EchoGen
4461    /// reports 3 prompt + 2 completion), not a byte-length estimate.
4462    #[tokio::test]
4463    async fn non_streaming_usage_comes_from_generator() {
4464        let resp = multi_router()
4465            .oneshot(
4466                Request::builder()
4467                    .method("POST")
4468                    .uri("/v1/chat/completions")
4469                    .header("content-type", "application/json")
4470                    .body(Body::from(
4471                        r#"{"model":"alpha","messages":[{"role":"user","content":"hi"}]}"#,
4472                    ))
4473                    .unwrap(),
4474            )
4475            .await
4476            .unwrap();
4477        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4478        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4479        assert_eq!(v["usage"]["prompt_tokens"], 3);
4480        assert_eq!(v["usage"]["completion_tokens"], 2);
4481        assert_eq!(v["usage"]["total_tokens"], 5);
4482    }
4483
4484    // --- tool_choice parsing (audit finding 6) -----------------------------
4485
4486    #[test]
4487    fn tool_choice_string_passes_through() {
4488        assert_eq!(
4489            tool_choice_str(&serde_json::json!("required")).unwrap(),
4490            Some("required".to_string())
4491        );
4492        assert_eq!(
4493            tool_choice_str(&serde_json::json!("auto")).unwrap(),
4494            Some("auto".to_string())
4495        );
4496    }
4497
4498    /// B22: a forced `tool_choice` the server cannot honour is a 400, not free text.
4499    ///
4500    /// `OaiRenderer::tool_constraint` returns `None` as soon as `tools` is absent — without reading
4501    /// `tool_choice` at all — and `run_chat` treats that as "generate normally". So every case
4502    /// below used to produce ordinary assistant text while the client believed it had forced a
4503    /// call.
4504    #[test]
4505    fn a_forced_tool_choice_needs_tools_that_can_satisfy_it() {
4506        let tools = serde_json::json!([{"function": {"name": "bash"}}]);
4507
4508        // Rejected: nothing to call.
4509        for choice in ["required", "bash"] {
4510            assert!(
4511                validate_tool_choice(Some(choice), None).is_err(),
4512                "{choice:?} with no tools must 400"
4513            );
4514            assert!(
4515                validate_tool_choice(Some(choice), Some(&serde_json::json!([]))).is_err(),
4516                "{choice:?} with an empty tools array must 400"
4517            );
4518        }
4519        // Rejected: names no tool that was offered. This is the case that built `{"anyOf": []}`.
4520        assert!(validate_tool_choice(Some("bogus"), Some(&tools)).is_err());
4521
4522        // Accepted: policies that are satisfiable without tools, and a name that is present.
4523        assert!(validate_tool_choice(Some("auto"), None).is_ok());
4524        assert!(
4525            validate_tool_choice(Some("none"), None).is_ok(),
4526            "`none` asks for no tool call, which needs no tools"
4527        );
4528        assert!(validate_tool_choice(None, None).is_ok());
4529        assert!(validate_tool_choice(Some("required"), Some(&tools)).is_ok());
4530        assert!(validate_tool_choice(Some("bash"), Some(&tools)).is_ok());
4531    }
4532
4533    /// The same rule over HTTP, so the wire really returns 400 and names the offending parameter.
4534    #[tokio::test]
4535    async fn forced_tool_choice_without_tools_is_a_400() {
4536        let resp = multi_router()
4537            .oneshot(
4538                Request::builder()
4539                    .method("POST")
4540                    .uri("/v1/chat/completions")
4541                    .header("content-type", "application/json")
4542                    .body(Body::from(
4543                        r#"{"model":"a","messages":[{"role":"user","content":"hi"}],"tool_choice":"required"}"#,
4544                    ))
4545                    .unwrap(),
4546            )
4547            .await
4548            .unwrap();
4549        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4550        let v = body_json(resp).await;
4551        assert_eq!(v["error"]["param"], "tool_choice");
4552        assert_eq!(v["error"]["type"], "invalid_request_error");
4553    }
4554
4555    #[test]
4556    fn tool_choice_named_function_forces_that_tool() {
4557        let v = serde_json::json!({"type":"function","function":{"name":"bash"}});
4558        assert_eq!(tool_choice_str(&v).unwrap(), Some("bash".to_string()));
4559    }
4560
4561    #[test]
4562    fn tool_choice_object_without_name_is_an_error_not_auto() {
4563        // The bug: a forced-tool object lacking function.name silently downgraded to "auto". It must
4564        // now be a 400 (ParamError), distinguishable from ABSENT (which the caller maps to None).
4565        let v = serde_json::json!({"type":"function","function":{}});
4566        let e = tool_choice_str(&v).unwrap_err();
4567        assert_eq!(e.param, "tool_choice");
4568        let v = serde_json::json!({"type":"function"});
4569        assert!(tool_choice_str(&v).is_err());
4570    }
4571
4572    #[test]
4573    fn tool_choice_wrong_shape_is_an_error() {
4574        assert!(tool_choice_str(&serde_json::json!(42)).is_err());
4575        assert!(tool_choice_str(&serde_json::json!(["auto"])).is_err());
4576    }
4577
4578    // --- max_tokens clamp (audit finding 5) --------------------------------
4579
4580    #[test]
4581    fn max_tokens_clamps_absurd_values_but_passes_unset_and_normal() {
4582        // Unset stays unset — the generator keeps applying its own INFR_MAX_NEW default (behaviour
4583        // unchanged for requests that don't ask for a budget).
4584        assert_eq!(clamp_max_tokens(None, 1000), None);
4585        // A sane value under the cap is untouched.
4586        assert_eq!(clamp_max_tokens(Some(512), 1000), Some(512));
4587        // An absurd value is capped, not rejected.
4588        assert_eq!(clamp_max_tokens(Some(10_000_000), 1000), Some(1000));
4589        // Exactly the cap passes.
4590        assert_eq!(clamp_max_tokens(Some(1000), 1000), Some(1000));
4591    }
4592
4593    // --- optional bearer auth (audit finding 5) ----------------------------
4594
4595    #[test]
4596    fn auth_disabled_allows_everything() {
4597        // No key configured (None) => open, regardless of what the client sends.
4598        assert!(authorize(None, None));
4599        assert!(authorize(None, Some("Bearer whatever")));
4600        assert!(authorize(None, Some("garbage")));
4601    }
4602
4603    #[test]
4604    fn auth_enabled_requires_matching_bearer() {
4605        let key = Some("s3cret");
4606        // Correct token (either capitalisation of the scheme) => allowed.
4607        assert!(authorize(key, Some("Bearer s3cret")));
4608        assert!(authorize(key, Some("bearer s3cret")));
4609        // Wrong token, missing header, or malformed scheme => denied.
4610        assert!(!authorize(key, Some("Bearer wrong")));
4611        assert!(!authorize(key, None));
4612        assert!(!authorize(key, Some("s3cret")));
4613        assert!(!authorize(key, Some("Basic s3cret")));
4614    }
4615
4616    /// The constant-time swap is a comparison, not a hash or a prefix check — so pin the two
4617    /// mistakes a hand-rolled "no early exit" loop typically makes.
4618    ///
4619    /// 1. SAME-LENGTH tokens must still be decided on CONTENT. A fold that ORs XORs together is
4620    ///    easy to get wrong in the direction of always-equal (e.g. accumulating `&=`, or seeding
4621    ///    the accumulator with the wrong identity), and same-length pairs are the only case where
4622    ///    that bug is invisible to the length check.
4623    /// 2. A correct PREFIX must be rejected. `ct_eq` answers `false` on a length mismatch, but a
4624    ///    zip-based loop silently compares only `min(len)` bytes and would accept `"s3c"` for
4625    ///    `"s3cret"` — the exact shape an attacker walks a key out with.
4626    #[test]
4627    fn auth_compares_full_token_not_a_prefix() {
4628        let key = Some("s3cret");
4629        // Same length as the wrong token below, and correct => allowed.
4630        assert!(authorize(key, Some("Bearer s3cret")));
4631        // Same length, differs only in the LAST byte => denied.
4632        assert!(!authorize(key, Some("Bearer s3creT")));
4633        // Same length, differs only in the FIRST byte => denied.
4634        assert!(!authorize(key, Some("Bearer S3cret")));
4635        // Correct prefix, short => denied (never "equal so far, therefore equal").
4636        assert!(!authorize(key, Some("Bearer s3c")));
4637        assert!(!authorize(key, Some("Bearer s")));
4638        assert!(!authorize(key, Some("Bearer ")));
4639        // Correct prefix, long => denied.
4640        assert!(!authorize(key, Some("Bearer s3cretx")));
4641        // The header's `str::trim` still runs before the compare (surrounding whitespace is not
4642        // part of the token), so a padded correct token is accepted and a padded wrong one is not.
4643        assert!(authorize(key, Some("Bearer   s3cret  ")));
4644        assert!(!authorize(key, Some("Bearer   s3cre  ")));
4645    }
4646
4647    // --- the `serve.*` knobs, driven through a `Config` (R7: never the environment) ------
4648
4649    /// `serve.api_key` decides whether auth is on, and the EMPTY string still means OFF — the
4650    /// grammar `INFR_API_KEY=` has always had. Getting this backwards would turn an empty
4651    /// key into a credential every request has to guess, so it is asserted explicitly.
4652    #[test]
4653    fn configured_api_key_reads_the_config_and_empty_still_means_no_auth() {
4654        let mut cfg = Config::default();
4655        assert_eq!(configured_api_key(&cfg), None, "unset => auth disabled");
4656
4657        cfg.serve.api_key = Some(String::new());
4658        assert_eq!(configured_api_key(&cfg), None, "empty => auth DISABLED");
4659
4660        cfg.serve.api_key = Some("hunter2".into());
4661        assert_eq!(configured_api_key(&cfg), Some("hunter2"));
4662        // …and a configured key really does gate the request.
4663        assert!(authorize(configured_api_key(&cfg), Some("Bearer hunter2")));
4664        assert!(!authorize(configured_api_key(&cfg), None));
4665    }
4666
4667    /// `serve.max_tokens_cap` feeds the clamp, and a non-positive value falls back to the shipped
4668    /// default rather than clamping every request to zero.
4669    #[test]
4670    fn max_tokens_cap_reads_the_config_and_rejects_non_positive() {
4671        let mut cfg = Config::default();
4672        assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
4673
4674        cfg.serve.max_tokens_cap = 4096;
4675        assert_eq!(max_tokens_cap(&cfg), 4096);
4676        assert_eq!(
4677            clamp_max_tokens(Some(10_000), max_tokens_cap(&cfg)),
4678            Some(4096)
4679        );
4680
4681        cfg.serve.max_tokens_cap = 0;
4682        assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
4683    }
4684
4685    /// End to end through the router: a state built with `serve.api_key` set answers 401 without a
4686    /// bearer token and gets past auth with one. Proves the handler reads the state's config, not
4687    /// the process environment.
4688    #[tokio::test]
4689    async fn configured_api_key_gates_the_chat_endpoint() {
4690        let mut cfg = Config::default();
4691        cfg.serve.api_key = Some("s3cret".into());
4692        let state = AppState::headless("test-model", Arc::new(cfg));
4693        let body = r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}]}"#;
4694        let req = |auth: Option<&str>| {
4695            let mut b = Request::builder()
4696                .method("POST")
4697                .uri("/v1/chat/completions")
4698                .header("content-type", "application/json");
4699            if let Some(a) = auth {
4700                b = b.header("authorization", a);
4701            }
4702            b.body(Body::from(body)).unwrap()
4703        };
4704        let resp = build_router(state.clone())
4705            .oneshot(req(None))
4706            .await
4707            .unwrap();
4708        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4709        // With the right token the request gets PAST auth (headless => 500 from the missing
4710        // engine, which is exactly "not 401").
4711        let resp = build_router(state)
4712            .oneshot(req(Some("Bearer s3cret")))
4713            .await
4714            .unwrap();
4715        assert_ne!(resp.status(), StatusCode::UNAUTHORIZED);
4716    }
4717
4718    /// `/v1/models` enumerates what the process is hosting, so a configured key must gate it too —
4719    /// otherwise anyone who can reach the port learns every model id for free, on a server whose
4720    /// operator explicitly said it is not open. `/health` must stay OPEN through the same config: a
4721    /// load balancer holds no bearer token, and a bare 200 discloses nothing.
4722    #[tokio::test]
4723    async fn configured_api_key_gates_models_but_never_health() {
4724        let mut cfg = Config::default();
4725        cfg.serve.api_key = Some("s3cret".into());
4726        let state = AppState::headless("test-model", Arc::new(cfg));
4727        let get = |uri: &str, auth: Option<&str>| {
4728            let mut b = Request::builder().uri(uri);
4729            if let Some(a) = auth {
4730                b = b.header("authorization", a);
4731            }
4732            b.body(Body::empty()).unwrap()
4733        };
4734
4735        // No bearer => 401, in the same envelope the chat handler returns.
4736        let resp = build_router(state.clone())
4737            .oneshot(get("/v1/models", None))
4738            .await
4739            .unwrap();
4740        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4741        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4742        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4743        assert_eq!(v["error"]["type"], "invalid_request_error");
4744        assert_eq!(v["error"]["code"], "invalid_api_key");
4745        assert_eq!(
4746            v["error"]["message"],
4747            "missing or invalid Authorization bearer token"
4748        );
4749        // …and the model list did NOT leak into the error body.
4750        assert!(
4751            !String::from_utf8_lossy(&bytes).contains("test-model"),
4752            "a 401 must not disclose the model set: {bytes:?}"
4753        );
4754
4755        // Wrong bearer => still 401.
4756        let resp = build_router(state.clone())
4757            .oneshot(get("/v1/models", Some("Bearer wrong")))
4758            .await
4759            .unwrap();
4760        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4761
4762        // Right bearer => the unchanged 200 body.
4763        let resp = build_router(state.clone())
4764            .oneshot(get("/v1/models", Some("Bearer s3cret")))
4765            .await
4766            .unwrap();
4767        assert_eq!(resp.status(), StatusCode::OK);
4768        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4769        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4770        assert_eq!(v["object"], "list");
4771        assert_eq!(v["data"][0]["id"], "test-model");
4772        assert_eq!(v["data"][0]["object"], "model");
4773        assert_eq!(v["data"][0]["owned_by"], "local");
4774
4775        // /health is open both ways.
4776        for auth in [None, Some("Bearer s3cret")] {
4777            let resp = build_router(state.clone())
4778                .oneshot(get("/health", auth))
4779                .await
4780                .unwrap();
4781            assert_eq!(resp.status(), StatusCode::OK, "auth={auth:?}");
4782        }
4783    }
4784
4785    // --- per-request wall-clock deadline ------------------------------------
4786
4787    /// `serve.request_timeout_secs` is OFF (unbounded) by default, and `0` explicitly means the
4788    /// same thing — a deadline truncates legitimate long replies, so it is opt-in only.
4789    #[test]
4790    fn request_timeout_is_off_by_default_and_zero_means_unbounded() {
4791        let mut cfg = Config::default();
4792        assert_eq!(request_timeout(&cfg), None, "default => no deadline");
4793
4794        cfg.serve.request_timeout_secs = 0;
4795        assert_eq!(request_timeout(&cfg), None, "0 => no deadline");
4796
4797        cfg.serve.request_timeout_secs = 300;
4798        assert_eq!(request_timeout(&cfg), Some(Duration::from_secs(300)));
4799    }
4800
4801    /// A generator that never stops on its own: it emits one delta and then polls `cancel` until
4802    /// something latches it — exactly the shape of a real decode loop, and the only way to test
4803    /// that the deadline reaches the abort mechanism rather than just abandoning the join. Returns
4804    /// `Finish::Stop`, because that is what a real generator reports when it is aborted: it cannot
4805    /// tell WHY the flag was set, which is why the handler has to relabel.
4806    struct LoopGen;
4807    impl ChatGenerator for LoopGen {
4808        fn status(&self) -> GeneratorStatus {
4809            cpu_status()
4810        }
4811
4812        fn vocab_size(&self) -> usize {
4813            TEST_VOCAB
4814        }
4815
4816        fn chat(
4817            &self,
4818            _messages: &[ChatMessage],
4819            _tools: Option<&serde_json::Value>,
4820            _tool_choice: Option<&str>,
4821            _params: &GenParams,
4822            cancel: &Arc<AtomicBool>,
4823            on_delta: &mut dyn FnMut(Delta),
4824        ) -> anyhow::Result<ChatOutcome> {
4825            on_delta(Delta::Content("partial".into()));
4826            while !cancel.load(Ordering::Relaxed) {
4827                std::thread::sleep(Duration::from_millis(2));
4828            }
4829            Ok(ChatOutcome {
4830                finish: Finish::Stop,
4831                prompt_tokens: 3,
4832                completion_tokens: 1,
4833                cached_tokens: 0,
4834            })
4835        }
4836    }
4837
4838    /// One entry hosting `gen`, routed as `"m"` — the handler-level fixture the deadline tests
4839    /// need, since `non_streaming`/`streaming` take a `ModelEntry` and a deadline directly (the
4840    /// knob is in whole SECONDS, so driving these through the router could not stay sub-second).
4841    fn deadline_entry(generator: Arc<dyn ChatGenerator>) -> ModelEntry {
4842        AppState::new(generator, "m", 1, Arc::new(Config::default())).route("m")
4843    }
4844
4845    /// The per-request context the two generation paths take, with a fresh (undrained) stats sink —
4846    /// the handler builds this from the request; a test that calls `streaming`/`non_streaming`
4847    /// directly has to build its own.
4848    fn test_ctx(deadline: Option<Duration>, stream: bool) -> ReqCtx {
4849        ReqCtx {
4850            id: next_req_id(),
4851            cid: "cid".into(),
4852            model_id: "m".into(),
4853            created: 0,
4854            deadline,
4855            keep_alive: None,
4856            stream,
4857            include_usage: false,
4858            stats: Arc::default(),
4859        }
4860    }
4861
4862    fn user_msg() -> Vec<ChatMessage> {
4863        vec![ChatMessage {
4864            role: "user".into(),
4865            content: "hi".into(),
4866            tool_calls: None,
4867            tool_call_id: None,
4868            name: None,
4869        }]
4870    }
4871
4872    async fn body_json(resp: Response) -> serde_json::Value {
4873        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4874        serde_json::from_slice(&bytes).unwrap()
4875    }
4876
4877    /// The non-streaming deadline: it fires, the client still gets what was generated, and the
4878    /// finish reason is `length` — NOT a 500, and not the `stop` the generator itself reported.
4879    #[tokio::test]
4880    async fn non_streaming_deadline_returns_partial_content_as_length() {
4881        let started = std::time::Instant::now();
4882        let resp = non_streaming(
4883            deadline_entry(Arc::new(LoopGen)),
4884            None,
4885            user_msg(),
4886            None,
4887            None,
4888            GenParams::default(),
4889            test_ctx(Some(Duration::from_millis(150)), false),
4890        )
4891        .await;
4892        assert_eq!(resp.status(), StatusCode::OK, "a deadline is not a failure");
4893        let v = body_json(resp).await;
4894        assert_eq!(v["choices"][0]["finish_reason"], "length");
4895        assert_eq!(
4896            v["choices"][0]["message"]["content"], "partial",
4897            "the partial completion must survive the deadline"
4898        );
4899        // The handler kept awaiting the join after latching the abort, so by the time it answered
4900        // the blocking task had really ended — and with it, its slot permit.
4901        assert!(
4902            started.elapsed() < Duration::from_secs(5),
4903            "the deadline did not stop the generator"
4904        );
4905    }
4906
4907    /// The permit is genuinely back: the entry admits `--parallel 1` at a time, so a SECOND request
4908    /// on the same entry can only be served if the first one's blocking task actually ended. If the
4909    /// deadline had merely timed out the join and left the task running, this would hang.
4910    #[tokio::test]
4911    async fn deadline_frees_the_slot_for_the_next_request() {
4912        let entry = deadline_entry(Arc::new(LoopGen));
4913        for _ in 0..2 {
4914            let resp = non_streaming(
4915                entry.clone(),
4916                None,
4917                user_msg(),
4918                None,
4919                None,
4920                GenParams::default(),
4921                test_ctx(Some(Duration::from_millis(100)), false),
4922            )
4923            .await;
4924            assert_eq!(
4925                body_json(resp).await["choices"][0]["finish_reason"],
4926                "length"
4927            );
4928        }
4929        assert_eq!(
4930            entry.slots.available_permits(),
4931            1,
4932            "the slot must be back after a deadline hit"
4933        );
4934    }
4935
4936    /// A request that finishes well inside its deadline is untouched: real content, the
4937    /// generator's OWN finish reason, and no relabelling.
4938    #[tokio::test]
4939    async fn generation_inside_the_deadline_is_untouched() {
4940        let resp = non_streaming(
4941            deadline_entry(Arc::new(EchoGen("alpha"))),
4942            None,
4943            user_msg(),
4944            None,
4945            None,
4946            GenParams::default(),
4947            test_ctx(Some(Duration::from_secs(30)), false),
4948        )
4949        .await;
4950        let v = body_json(resp).await;
4951        assert_eq!(v["choices"][0]["finish_reason"], "stop");
4952        assert_eq!(v["choices"][0]["message"]["content"], "from:alpha");
4953    }
4954
4955    /// The streaming deadline: the deltas already sent are kept, the finish chunk says `length`,
4956    /// and `[DONE]` still closes the stream.
4957    #[tokio::test]
4958    async fn streaming_deadline_finishes_with_length() {
4959        let resp = streaming(
4960            deadline_entry(Arc::new(LoopGen)),
4961            None,
4962            user_msg(),
4963            None,
4964            None,
4965            GenParams::default(),
4966            test_ctx(Some(Duration::from_millis(150)), true),
4967        )
4968        .await;
4969        assert_eq!(resp.status(), StatusCode::OK);
4970        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4971        let text = String::from_utf8(bytes.to_vec()).unwrap();
4972        assert!(text.contains("partial"), "partial content lost: {text}");
4973        assert!(
4974            text.contains("\"finish_reason\":\"length\""),
4975            "a deadline hit must finish as `length`: {text}"
4976        );
4977        assert!(
4978            !text.contains("\"finish_reason\":\"stop\""),
4979            "the generator's `stop` must not reach the wire: {text}"
4980        );
4981        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
4982    }
4983
4984    /// The watchdog must not outlive its request. Dropping the "generation finished" sender — which
4985    /// is what the blocking task does when it returns, or unwinds — has to end the timer task, or a
4986    /// long-lived server accumulates one sleeping task per request. Asserted by waiting PAST the
4987    /// deadline and finding the flags still clear.
4988    #[tokio::test]
4989    async fn dropping_the_done_signal_disarms_the_watchdog() {
4990        let cancel = Arc::new(AtomicBool::new(false));
4991        let hit = Arc::new(AtomicBool::new(false));
4992        let done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
4993        drop(done_tx); // the generation finished first
4994        tokio::time::sleep(Duration::from_millis(200)).await;
4995        assert!(
4996            !cancel.load(Ordering::Relaxed) && !hit.load(Ordering::Relaxed),
4997            "a disarmed watchdog must never fire"
4998        );
4999
5000        // …and one that is NOT disarmed does fire, on both flags (so the finish reason can tell a
5001        // deadline apart from a client disconnect, which latches only `cancel`).
5002        let cancel = Arc::new(AtomicBool::new(false));
5003        let hit = Arc::new(AtomicBool::new(false));
5004        let _done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
5005        tokio::time::sleep(Duration::from_millis(200)).await;
5006        assert!(cancel.load(Ordering::Relaxed) && hit.load(Ordering::Relaxed));
5007    }
5008
5009    // --- finish-reason mapping: Err is an error frame, never `stop` (finding 1) ---
5010
5011    /// A generator whose `chat` fails mid-stream. The streaming path must NOT relabel this as a
5012    /// clean `stop`; it must emit a terminal error frame, then `[DONE]`.
5013    struct FailGen;
5014    impl ChatGenerator for FailGen {
5015        fn status(&self) -> GeneratorStatus {
5016            cpu_status()
5017        }
5018
5019        fn vocab_size(&self) -> usize {
5020            TEST_VOCAB
5021        }
5022
5023        fn chat(
5024            &self,
5025            _messages: &[ChatMessage],
5026            _tools: Option<&serde_json::Value>,
5027            _tool_choice: Option<&str>,
5028            _params: &GenParams,
5029            _cancel: &Arc<AtomicBool>,
5030            on_delta: &mut dyn FnMut(Delta),
5031        ) -> anyhow::Result<ChatOutcome> {
5032            on_delta(Delta::Content("partial".into()));
5033            anyhow::bail!("boom mid-stream")
5034        }
5035    }
5036
5037    #[tokio::test]
5038    async fn streaming_error_emits_error_frame_not_stop() {
5039        let g: Arc<dyn ChatGenerator> = Arc::new(FailGen);
5040        let router = build_router(AppState::new(g, "m", 1, Arc::new(Config::default())));
5041        let resp = router
5042            .oneshot(
5043                Request::builder()
5044                    .method("POST")
5045                    .uri("/v1/chat/completions")
5046                    .header("content-type", "application/json")
5047                    .body(Body::from(
5048                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5049                    ))
5050                    .unwrap(),
5051            )
5052            .await
5053            .unwrap();
5054        assert_eq!(resp.status(), StatusCode::OK);
5055        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5056        let text = String::from_utf8(bytes.to_vec()).unwrap();
5057        // A terminal error frame is present, the stream is closed with [DONE], and NO finish chunk
5058        // ever claimed a clean "stop".
5059        assert!(text.contains("\"error\""), "missing error frame: {text}");
5060        assert!(
5061            text.contains("boom mid-stream"),
5062            "error message lost: {text}"
5063        );
5064        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
5065        assert!(
5066            !text.contains("\"finish_reason\":\"stop\""),
5067            "an Err must not report a clean stop: {text}"
5068        );
5069    }
5070
5071    /// A generator that refuses every request with a [`ParamError`], as a backend that cannot
5072    /// apply a sampling field does.
5073    struct RefusingGen;
5074    impl ChatGenerator for RefusingGen {
5075        fn status(&self) -> GeneratorStatus {
5076            cpu_status()
5077        }
5078
5079        fn vocab_size(&self) -> usize {
5080            TEST_VOCAB
5081        }
5082
5083        fn chat(
5084            &self,
5085            _messages: &[ChatMessage],
5086            _tools: Option<&serde_json::Value>,
5087            _tool_choice: Option<&str>,
5088            _params: &GenParams,
5089            _cancel: &Arc<AtomicBool>,
5090            _on_delta: &mut dyn FnMut(Delta),
5091        ) -> anyhow::Result<ChatOutcome> {
5092            Err(ParamError {
5093                param: "min_p",
5094                message: "min_p is not supported by the test backend".into(),
5095            }
5096            .into())
5097        }
5098    }
5099
5100    /// A generator's [`ParamError`] is the request's fault: a 400 naming the field, and when
5101    /// streaming a terminal error frame carrying the same, not a 500 or an anonymous failure.
5102    #[tokio::test]
5103    async fn a_generator_param_error_is_a_400_naming_the_field() {
5104        let gen: Arc<dyn ChatGenerator> = Arc::new(RefusingGen);
5105        let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5106        let resp = post_chat(router_for(gen.clone()), &format!("{{{base}}}")).await;
5107        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5108        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5109        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
5110        assert_eq!(v["error"]["type"], "invalid_request_error");
5111        assert_eq!(v["error"]["param"], "min_p");
5112        let resp = post_chat(router_for(gen), &format!(r#"{{{base},"stream":true}}"#)).await;
5113        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5114        let text = String::from_utf8(bytes.to_vec()).unwrap();
5115        assert!(text.contains(r#""param":"min_p""#), "{text}");
5116        assert!(text.contains("invalid_request_error"), "{text}");
5117    }
5118
5119    /// A generator whose `chat` PANICS mid-stream, which is not the same as returning `Err`: the
5120    /// unwind skips every arm of the `match res` below it, so before B23 the only thing that ran
5121    /// was `DoneGuard`'s `[DONE]`.
5122    struct PanicGen;
5123    impl ChatGenerator for PanicGen {
5124        fn status(&self) -> GeneratorStatus {
5125            cpu_status()
5126        }
5127
5128        fn vocab_size(&self) -> usize {
5129            TEST_VOCAB
5130        }
5131
5132        fn chat(
5133            &self,
5134            _messages: &[ChatMessage],
5135            _tools: Option<&serde_json::Value>,
5136            _tool_choice: Option<&str>,
5137            _params: &GenParams,
5138            _cancel: &Arc<AtomicBool>,
5139            on_delta: &mut dyn FnMut(Delta),
5140        ) -> anyhow::Result<ChatOutcome> {
5141            on_delta(Delta::Content("partial".into()));
5142            panic!("boom: generator panicked mid-stream")
5143        }
5144    }
5145
5146    /// B23: a panicking generator must terminate the stream like a FAILURE, not like a success.
5147    ///
5148    /// The bug this pins is one of omission, so assert on what was missing: an error frame, and a
5149    /// `failed` count. Both were absent while `[DONE]` was present, which is precisely what made a
5150    /// panic indistinguishable from a short completion on the wire.
5151    #[tokio::test]
5152    async fn streaming_panic_is_reported_as_a_failure() {
5153        let g: Arc<dyn ChatGenerator> = Arc::new(PanicGen);
5154        let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
5155        let stats = state.stats.clone();
5156        let router = build_router(state);
5157        // The panic is expected and its message lands in this test's captured output. No
5158        // `set_hook` to hide it: the hook is process-global and would also swallow the backtrace
5159        // of any test panicking on another thread meanwhile.
5160        let resp = router
5161            .oneshot(
5162                Request::builder()
5163                    .method("POST")
5164                    .uri("/v1/chat/completions")
5165                    .header("content-type", "application/json")
5166                    .body(Body::from(
5167                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5168                    ))
5169                    .unwrap(),
5170            )
5171            .await
5172            .unwrap();
5173        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5174        let text = String::from_utf8(bytes.to_vec()).unwrap();
5175
5176        assert!(
5177            text.contains("\"error\""),
5178            "a panicking generator must still put a terminal error frame on the wire: {text}"
5179        );
5180        assert!(text.contains("[DONE]"), "sentinel missing: {text}");
5181        assert!(
5182            !text.contains("\"finish_reason\":\"stop\""),
5183            "a panic must never look like a clean stop: {text}"
5184        );
5185
5186        let w = stats.drain(Duration::from_secs(1));
5187        assert_eq!(w.failed, 1, "the panic must be counted as a failure");
5188        assert_eq!(
5189            w.completed, 1,
5190            "a failure is still a completed request for the interval line"
5191        );
5192        assert_eq!(w.active, 0, "the slot gauge must be released by the unwind");
5193    }
5194
5195    /// The abort-on-disconnect decision, unit-tested without a socket: when the SSE `send` returns
5196    /// Err (receiver dropped), the callback must latch the per-request cancel flag. Full
5197    /// disconnect→GPU-slot-release is integration-only (needs a live generator + real client drop).
5198    #[test]
5199    fn send_failure_latches_the_cancel_flag() {
5200        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
5201        let cancel = AtomicBool::new(false);
5202        drop(rx); // simulate the client disconnecting: the receiver is gone.
5203        if tx.send(Ok(Event::default().data("x"))).is_err() {
5204            cancel.store(true, Ordering::Relaxed);
5205        }
5206        assert!(
5207            cancel.load(Ordering::Relaxed),
5208            "a failed send must latch the abort flag so the decode loop stops"
5209        );
5210    }
5211
5212    // --- request / throughput logging (B10) ---------------------------------
5213
5214    /// A finished request, spelled out so a test can fold one in without running a generator.
5215    ///
5216    /// Defaults to "all of its deltas are in window 0, which is still open" — the ordinary case
5217    /// where no drain intervened. [`rec_in_window`] is for the case that does.
5218    fn rec(prompt: u32, gen: u32, deltas: u64) -> ReqRecord {
5219        rec_in_window(prompt, gen, deltas, 0, deltas)
5220    }
5221
5222    /// A finished request whose deltas landed in a specific stats window — the B24 shape.
5223    fn rec_in_window(
5224        prompt: u32,
5225        gen: u32,
5226        deltas: u64,
5227        window: u64,
5228        deltas_in_window: u64,
5229    ) -> ReqRecord {
5230        ReqRecord {
5231            prompt_tokens: prompt,
5232            gen_tokens: gen,
5233            deltas,
5234            window,
5235            deltas_in_window,
5236            prefill: Duration::from_millis(100),
5237            decode: Duration::from_millis(400),
5238            total: Duration::from_millis(500),
5239            finish: Finish::Stop,
5240        }
5241    }
5242
5243    /// **The whole point of the periodic line.** Its numbers must describe the INTERVAL, so a drain
5244    /// has to leave the counters at zero — a cumulative counter would turn every rate into an
5245    /// average-since-boot, which looks plausible and is useless.
5246    ///
5247    /// Asserted by three consecutive intervals of the SAME wall length with DIFFERENT work in them:
5248    /// busy, half as busy, idle. Per-interval, the rates must go 10 → 5 → 0. Cumulative, they would
5249    /// go 10 → 15 → 15 (or 10 → 7.5 → 5 as an average), i.e. they could never fall — which is the
5250    /// exact failure this pins.
5251    #[test]
5252    fn stats_windows_cover_the_interval_and_never_accumulate() {
5253        let stats = ServeStats::default();
5254        let window = Duration::from_secs(2);
5255
5256        for _ in 0..20 {
5257            stats.bump_gen(1);
5258        }
5259        stats.fold_completion(&rec(100, 20, 20));
5260        let busy = stats.drain(window);
5261        assert_eq!(
5262            (busy.prompt_tokens, busy.gen_tokens, busy.completed),
5263            (100, 20, 1)
5264        );
5265        assert!((busy.decode_tps() - 10.0).abs() < 1e-9, "{busy:?}");
5266        assert!((busy.prefill_tps() - 50.0).abs() < 1e-9, "{busy:?}");
5267
5268        for _ in 0..10 {
5269            stats.bump_gen(1);
5270        }
5271        stats.fold_completion(&rec(20, 10, 10));
5272        let quieter = stats.drain(window);
5273        assert_eq!((quieter.prompt_tokens, quieter.gen_tokens), (20, 10));
5274        assert!(
5275            (quieter.decode_tps() - 5.0).abs() < 1e-9,
5276            "the second interval must report only ITS OWN 10 tokens: {quieter:?}"
5277        );
5278        assert!(
5279            quieter.decode_tps() < busy.decode_tps() && quieter.prefill_tps() < busy.prefill_tps(),
5280            "half the work in the same wall time must report a LOWER rate: {busy:?} then {quieter:?}"
5281        );
5282
5283        let idle = stats.drain(window);
5284        assert_eq!(
5285            (idle.gen_tokens, idle.prompt_tokens, idle.completed),
5286            (0, 0, 0)
5287        );
5288        assert_eq!(idle.decode_tps(), 0.0);
5289        assert!(
5290            !idle.has_activity(),
5291            "an interval with nothing in it must emit no line: {idle:?}"
5292        );
5293    }
5294
5295    /// The live per-delta count is an ESTIMATE (a delta is a text piece, not necessarily a token);
5296    /// `ChatOutcome` is authoritative. Whichever way they disagree, the interval total must end up
5297    /// on the authoritative number.
5298    #[test]
5299    fn the_live_delta_count_is_reconciled_against_the_real_token_count() {
5300        // Generator emitted 3 pieces but really decoded 5 tokens.
5301        let under = ServeStats::default();
5302        for _ in 0..3 {
5303            under.bump_gen(1);
5304        }
5305        under.fold_completion(&rec(1, 5, 3));
5306        assert_eq!(under.drain(Duration::from_secs(1)).gen_tokens, 5);
5307
5308        // …and the other way: 6 pieces for 4 tokens.
5309        let over = ServeStats::default();
5310        for _ in 0..6 {
5311            over.bump_gen(1);
5312        }
5313        over.fold_completion(&rec(1, 4, 6));
5314        assert_eq!(over.drain(Duration::from_secs(1)).gen_tokens, 4);
5315    }
5316
5317    /// B24: a correction must never be paid for out of a DIFFERENT request's interval.
5318    ///
5319    /// The reconciliation above only works because nothing drains between the deltas and the
5320    /// completion. When a reporter tick lands in that gap the deltas have already been published,
5321    /// and the retraction used to come out of whatever was generating next.
5322    #[test]
5323    fn a_correction_never_retracts_another_requests_tokens() {
5324        let s = ServeStats::default();
5325
5326        // Request A emits two deltas, and the reporter ticks before A finishes.
5327        let mut a = ReqTally::new();
5328        a.on_text_delta(&s);
5329        a.on_text_delta(&s);
5330        let w1 = s.drain(Duration::from_secs(1));
5331        assert_eq!(w1.gen_tokens, 2, "the open window had A's two deltas");
5332
5333        // Request B is now generating and puts three real tokens into the new window.
5334        let mut b = ReqTally::new();
5335        for _ in 0..3 {
5336            b.on_text_delta(&s);
5337        }
5338
5339        // A completes: it really produced ONE token, so its live estimate was 1 too high. That
5340        // overcount is in a window that has already been reported and cannot be taken back.
5341        s.fold_completion(&a.finish(
5342            ChatOutcome {
5343                finish: Finish::Stop,
5344                prompt_tokens: 1,
5345                completion_tokens: 1,
5346                cached_tokens: 0,
5347            },
5348            Finish::Stop,
5349        ));
5350
5351        let w2 = s.drain(Duration::from_secs(1));
5352        assert_eq!(
5353            w2.gen_tokens, 3,
5354            "B's three tokens must survive A's correction — the −1 belongs to a closed window"
5355        );
5356    }
5357
5358    /// The other half of B24: while the window is still open, a correction DOES apply — clamped to
5359    /// this request's own contribution, so it can never dig into tokens it did not put there.
5360    #[test]
5361    fn a_correction_applies_within_the_open_window_and_is_clamped_to_its_own_deltas() {
5362        let s = ServeStats::default();
5363        let mut a = ReqTally::new();
5364        for _ in 0..4 {
5365            a.on_text_delta(&s);
5366        }
5367        // No drain: A's deltas are still in the open window, so its −2 lands.
5368        s.fold_completion(&a.finish(
5369            ChatOutcome {
5370                finish: Finish::Stop,
5371                prompt_tokens: 1,
5372                completion_tokens: 2,
5373                cached_tokens: 0,
5374            },
5375            Finish::Stop,
5376        ));
5377        assert_eq!(s.drain(Duration::from_secs(1)).gen_tokens, 2);
5378
5379        // A request claiming FEWER tokens than it has deltas in this window can still only retract
5380        // what it contributed: 1 delta here, so a −3 becomes −1 and the other request keeps its 5.
5381        let s = ServeStats::default();
5382        let mut c = ReqTally::new();
5383        c.on_text_delta(&s);
5384        for _ in 0..5 {
5385            s.bump_gen(1); // another request's tokens, same window
5386        }
5387        let mut r = c.finish(
5388            ChatOutcome {
5389                finish: Finish::Stop,
5390                prompt_tokens: 0,
5391                completion_tokens: 0,
5392                cached_tokens: 0,
5393            },
5394            Finish::Stop,
5395        );
5396        r.deltas = 4; // pretend 4 deltas were seen, only 1 of them in this window
5397        s.fold_completion(&r);
5398        assert_eq!(
5399            s.drain(Duration::from_secs(1)).gen_tokens,
5400            5,
5401            "the retraction is capped at this request's own contribution to the window"
5402        );
5403    }
5404
5405    /// Activity-only, and what counts as activity. A request that is mid-generation has produced no
5406    /// completed tokens yet, but the server is plainly busy — so `active`/`queued` alone must be
5407    /// enough to emit a line, or a single long generation would log nothing until it ended. An
5408    /// interval with none of it emits nothing: there is no idle heartbeat, by decision.
5409    #[test]
5410    fn in_flight_requests_are_activity_and_an_empty_interval_is_not() {
5411        let stats = Arc::new(ServeStats::default());
5412        let w = Duration::from_secs(1);
5413        assert!(!stats.drain(w).has_activity(), "idle must be silent");
5414
5415        let generating = ActiveGuard::new(stats.clone());
5416        assert!(
5417            stats.drain(w).has_activity(),
5418            "a generation in flight is activity even before it yields a token"
5419        );
5420        drop(generating);
5421        assert!(!stats.drain(w).has_activity());
5422
5423        let waiting = QueuedGuard::new(stats.clone());
5424        assert!(
5425            stats.drain(w).has_activity(),
5426            "a request queued for a slot is activity"
5427        );
5428        drop(waiting);
5429        assert!(!stats.drain(w).has_activity());
5430    }
5431
5432    /// The gauges are RAII, so the interesting case is the abnormal exit: a guard dropped while
5433    /// unwinding must still put the gauge back, or one panicking request leaves the server looking
5434    /// permanently busy.
5435    #[test]
5436    fn the_active_gauge_is_released_by_an_unwinding_panic() {
5437        let stats = Arc::new(ServeStats::default());
5438        let inner = stats.clone();
5439        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
5440            let _active = ActiveGuard::new(inner);
5441            panic!("decode closure blew up");
5442        }));
5443        assert!(caught.is_err(), "the panic must have happened");
5444        assert_eq!(stats.active.load(Ordering::Relaxed), 0);
5445    }
5446
5447    /// `serve.stats_interval_secs`: 5 s by default, `0` switches the periodic line OFF.
5448    #[test]
5449    fn stats_interval_defaults_to_five_seconds_and_zero_disables_it() {
5450        let mut cfg = Config::default();
5451        assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(5)));
5452        cfg.serve.stats_interval_secs = 0;
5453        assert_eq!(stats_interval(&cfg), None, "0 => no periodic line at all");
5454        cfg.serve.stats_interval_secs = 30;
5455        assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(30)));
5456    }
5457
5458    /// KV slot occupancy is `busy/total` across every hosted model — the number the periodic line
5459    /// reports. It has to count HELD permits, not available ones.
5460    #[tokio::test]
5461    async fn slot_occupancy_counts_held_permits_across_models() {
5462        let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
5463        let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
5464        let state = AppState::multi(
5465            vec![("alpha".into(), a, 3), ("beta".into(), b, 1)],
5466            Arc::new(Config::default()),
5467        );
5468        assert_eq!(state.slot_occupancy(), (0, 4));
5469        let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
5470        assert_eq!(state.slot_occupancy(), (1, 4));
5471        let held2 = state.models[1].slots.clone().acquire_owned().await.unwrap();
5472        assert_eq!(state.slot_occupancy(), (2, 4));
5473        drop(held);
5474        drop(held2);
5475        assert_eq!(state.slot_occupancy(), (0, 4));
5476    }
5477
5478    /// Request ids are a monotonic counter, NOT a clock reading: two requests admitted in the same
5479    /// millisecond must still be tellable apart in the log.
5480    #[test]
5481    fn request_ids_are_monotonic_and_distinct() {
5482        // STRICTLY increasing rather than dense: the counter is process-wide and the rest of the
5483        // suite is minting ids from other threads at the same time, so the gaps are the mechanism
5484        // working, not a failure. What must hold is that no id is ever reissued or reused.
5485        let ids: Vec<u64> = (0..1000).map(|_| next_req_id()).collect();
5486        assert!(
5487            ids.windows(2).all(|w| w[1] > w[0]),
5488            "ids must increase monotonically"
5489        );
5490        let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
5491        assert_eq!(unique.len(), ids.len(), "ids must never repeat");
5492    }
5493
5494    /// End to end through the real non-streaming path: the request's tallies reach the shared
5495    /// counters exactly once, with the generator's OWN token counts — `EchoGen` sends one delta but
5496    /// reports two completion tokens, so this also proves the reconciliation runs on the live path
5497    /// and not only in its unit test.
5498    #[tokio::test]
5499    async fn a_served_request_folds_its_counts_into_the_window() {
5500        let stats: Arc<ServeStats> = Arc::default();
5501        let ctx = ReqCtx {
5502            stats: stats.clone(),
5503            ..test_ctx(None, false)
5504        };
5505        let resp = non_streaming(
5506            deadline_entry(Arc::new(EchoGen("alpha"))),
5507            None,
5508            user_msg(),
5509            None,
5510            None,
5511            GenParams::default(),
5512            ctx,
5513        )
5514        .await;
5515        assert_eq!(resp.status(), StatusCode::OK);
5516        let w = stats.drain(Duration::from_secs(1));
5517        assert_eq!(
5518            (w.prompt_tokens, w.gen_tokens, w.completed, w.failed),
5519            (3, 2, 1, 0),
5520            "EchoGen reports prompt_tokens=3, completion_tokens=2 for one request: {w:?}"
5521        );
5522        assert_eq!(
5523            (w.active, w.queued),
5524            (0, 0),
5525            "both gauges must be back at zero once the request is answered"
5526        );
5527    }
5528
5529    /// A failed generation is still a completed request, and it is counted as a FAILURE — a server
5530    /// erroring on everything must not look idle.
5531    #[tokio::test]
5532    async fn a_failed_request_is_counted_as_a_failure() {
5533        let stats: Arc<ServeStats> = Arc::default();
5534        let ctx = ReqCtx {
5535            stats: stats.clone(),
5536            ..test_ctx(None, false)
5537        };
5538        let resp = non_streaming(
5539            deadline_entry(Arc::new(FailGen)),
5540            None,
5541            user_msg(),
5542            None,
5543            None,
5544            GenParams::default(),
5545            ctx,
5546        )
5547        .await;
5548        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
5549        let w = stats.drain(Duration::from_secs(1));
5550        assert_eq!((w.completed, w.failed), (1, 1), "{w:?}");
5551        assert!(
5552            w.has_activity(),
5553            "an interval of failures is not an idle one"
5554        );
5555    }
5556
5557    // --- wire contract: usage, context length, body rejections, hang-ups ----
5558
5559    /// POST `body` to the chat route of `router` with a JSON content type.
5560    async fn post_chat(router: Router, body: &str) -> Response {
5561        router
5562            .oneshot(
5563                Request::builder()
5564                    .method("POST")
5565                    .uri("/v1/chat/completions")
5566                    .header("content-type", "application/json")
5567                    .body(Body::from(body.to_owned()))
5568                    .unwrap(),
5569            )
5570            .await
5571            .unwrap()
5572    }
5573
5574    /// A generator that counts how often the server asks for its vocabulary size.
5575    struct VocabCountingGen(Arc<AtomicU64>);
5576    impl ChatGenerator for VocabCountingGen {
5577        fn status(&self) -> GeneratorStatus {
5578            cpu_status()
5579        }
5580
5581        fn vocab_size(&self) -> usize {
5582            self.0.fetch_add(1, Ordering::Relaxed);
5583            TEST_VOCAB
5584        }
5585
5586        fn chat(
5587            &self,
5588            _messages: &[ChatMessage],
5589            _tools: Option<&serde_json::Value>,
5590            _tool_choice: Option<&str>,
5591            _params: &GenParams,
5592            _cancel: &Arc<AtomicBool>,
5593            on_delta: &mut dyn FnMut(Delta),
5594        ) -> anyhow::Result<ChatOutcome> {
5595            on_delta(Delta::Content("ok".into()));
5596            Ok(ChatOutcome {
5597                finish: Finish::Stop,
5598                prompt_tokens: 1,
5599                completion_tokens: 1,
5600                cached_tokens: 0,
5601            })
5602        }
5603    }
5604
5605    /// The vocabulary size is asked for only when a request carries a `logit_bias` to check: a
5606    /// request without one must not pay for it.
5607    #[tokio::test]
5608    async fn the_vocab_size_is_read_only_for_a_logit_bias() {
5609        let calls = Arc::new(AtomicU64::new(0));
5610        let gen: Arc<dyn ChatGenerator> = Arc::new(VocabCountingGen(calls.clone()));
5611        let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5612        for extra in ["", r#","logit_bias":{}"#, r#","logit_bias":null"#] {
5613            let resp = post_chat(router_for(gen.clone()), &format!("{{{base}{extra}}}")).await;
5614            assert_eq!(resp.status(), StatusCode::OK);
5615        }
5616        assert_eq!(calls.load(Ordering::Relaxed), 0, "asked without a bias");
5617        let body = format!(r#"{{{base},"logit_bias":{{"3":-100}}}}"#);
5618        let resp = post_chat(router_for(gen), &body).await;
5619        assert_eq!(resp.status(), StatusCode::OK);
5620        assert_eq!(calls.load(Ordering::Relaxed), 1, "the bias was not checked");
5621    }
5622
5623    /// The new request checks answer an OpenAI-shaped 400 naming the parameter, on a streaming
5624    /// request as well — the `logit_bias` vocabulary check included, which needs the routed
5625    /// generator — and the neutral values still get a reply.
5626    #[tokio::test]
5627    async fn unsupported_and_invalid_sampling_fields_are_400s() {
5628        let gen: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
5629        let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5630        let vocab = TEST_VOCAB;
5631        for stream in [false, true] {
5632            for (extra, param) in [
5633                (r#""n":2"#.to_string(), "n"),
5634                (r#""logprobs":true"#.to_string(), "logprobs"),
5635                (r#""top_logprobs":2"#.to_string(), "top_logprobs"),
5636                (r#""min_p":2"#.to_string(), "min_p"),
5637                (r#""logit_bias":{"1":-150}"#.to_string(), "logit_bias"),
5638                (format!(r#""logit_bias":{{"{vocab}":-100}}"#), "logit_bias"),
5639                (
5640                    r#""logit_bias":{"5":-100,"+5":-100}"#.to_string(),
5641                    "logit_bias",
5642                ),
5643                (r#""n":"2""#.to_string(), "n"),
5644                (r#""top_logprobs":1.5"#.to_string(), "top_logprobs"),
5645            ] {
5646                let body = format!(r#"{{{base},"stream":{stream},{extra}}}"#);
5647                let resp = post_chat(router_for(gen.clone()), &body).await;
5648                assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{body}");
5649                let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5650                let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
5651                assert_eq!(v["error"]["type"], "invalid_request_error", "{body}");
5652                assert_eq!(v["error"]["param"], param, "{body}");
5653            }
5654        }
5655        let last = vocab - 1;
5656        let body = format!(
5657            r#"{{{base},"n":1.0,"logprobs":false,"top_logprobs":0,"min_p":0.1,
5658                "logit_bias":{{"{last}":-100}}}}"#
5659        );
5660        let resp = post_chat(router_for(gen), &body).await;
5661        assert_eq!(resp.status(), StatusCode::OK, "{body}");
5662    }
5663
5664    fn router_for(generator: Arc<dyn ChatGenerator>) -> Router {
5665        build_router(AppState::new(
5666            generator,
5667            "m",
5668            1,
5669            Arc::new(Config::default()),
5670        ))
5671    }
5672
5673    /// A generator whose prompt was mostly served from the KV prefix cache: 20 prompt tokens, 19
5674    /// of them cached, so only 1 was prefilled.
5675    struct CachedPrefixGen;
5676    impl ChatGenerator for CachedPrefixGen {
5677        fn status(&self) -> GeneratorStatus {
5678            cpu_status()
5679        }
5680
5681        fn vocab_size(&self) -> usize {
5682            TEST_VOCAB
5683        }
5684
5685        fn chat(
5686            &self,
5687            _messages: &[ChatMessage],
5688            _tools: Option<&serde_json::Value>,
5689            _tool_choice: Option<&str>,
5690            _params: &GenParams,
5691            _cancel: &Arc<AtomicBool>,
5692            on_delta: &mut dyn FnMut(Delta),
5693        ) -> anyhow::Result<ChatOutcome> {
5694            on_delta(Delta::Content("ok".into()));
5695            Ok(ChatOutcome {
5696                finish: Finish::Stop,
5697                prompt_tokens: 20,
5698                completion_tokens: 1,
5699                cached_tokens: 19,
5700            })
5701        }
5702    }
5703
5704    /// B83: `usage.prompt_tokens` is the whole prompt and the cached part is reported under
5705    /// `prompt_tokens_details.cached_tokens` — while the throughput counters still count only the
5706    /// one token that was actually prefilled.
5707    #[tokio::test]
5708    async fn usage_counts_the_whole_prompt_and_reports_the_cached_part() {
5709        let g: Arc<dyn ChatGenerator> = Arc::new(CachedPrefixGen);
5710        let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
5711        let stats = state.stats.clone();
5712        let resp = post_chat(
5713            build_router(state),
5714            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5715        )
5716        .await;
5717        let v = body_json(resp).await;
5718        assert_eq!(v["usage"]["prompt_tokens"], 20);
5719        assert_eq!(v["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
5720        assert_eq!(v["usage"]["total_tokens"], 21);
5721        let w = stats.drain(Duration::from_secs(1));
5722        assert_eq!(w.prompt_tokens, 1, "only the prefilled token is throughput");
5723    }
5724
5725    /// The SSE frames of a streamed response, `data:` payloads in order.
5726    async fn sse_frames(resp: Response) -> Vec<String> {
5727        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5728        String::from_utf8(bytes.to_vec())
5729            .unwrap()
5730            .lines()
5731            .filter_map(|l| l.strip_prefix("data: ").map(str::to_owned))
5732            .collect()
5733    }
5734
5735    /// B137: `stream_options.include_usage` ends the stream with one chunk carrying `usage` and an
5736    /// empty `choices` array, after the finish chunk and before `[DONE]`. Without the option, no
5737    /// chunk carries `usage`.
5738    #[tokio::test]
5739    async fn include_usage_ends_the_stream_with_a_usage_chunk() {
5740        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true,
5741                       "stream_options":{"include_usage":true}}"#;
5742        let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
5743        let n = frames.len();
5744        assert!(n >= 3, "{frames:?}");
5745        assert_eq!(frames[n - 1], "[DONE]");
5746        let usage: serde_json::Value = serde_json::from_str(&frames[n - 2]).unwrap();
5747        assert_eq!(usage["choices"], serde_json::json!([]), "{frames:?}");
5748        assert_eq!(usage["usage"]["prompt_tokens"], 20);
5749        assert_eq!(usage["usage"]["completion_tokens"], 1);
5750        assert_eq!(usage["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
5751        let finish: serde_json::Value = serde_json::from_str(&frames[n - 3]).unwrap();
5752        assert_eq!(finish["choices"][0]["finish_reason"], "stop", "{frames:?}");
5753
5754        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#;
5755        let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
5756        assert!(
5757            frames.iter().all(|f| !f.contains("\"usage\"")),
5758            "usage was not asked for: {frames:?}"
5759        );
5760    }
5761
5762    /// `logprobs` on a non-streaming chat reply: the chosen token's text, bytes and probability,
5763    /// plus the requested alternatives.
5764    #[tokio::test]
5765    async fn logprobs_are_returned_on_the_non_streaming_choice() {
5766        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5767                       "logprobs":true,"top_logprobs":1}"#;
5768        let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5769        assert_eq!(v["choices"][0]["message"]["content"], "hi");
5770        let lp = &v["choices"][0]["logprobs"]["content"][0];
5771        assert_eq!(lp["id"], 7);
5772        assert_eq!(lp["token"], "hi");
5773        assert_eq!(lp["bytes"], serde_json::json!([104, 105]));
5774        assert_eq!(lp["logprob"], -0.25);
5775        assert_eq!(lp["top_logprobs"][0]["id"], 9);
5776        assert_eq!(lp["top_logprobs"][0]["token"], "ho");
5777        assert_eq!(lp["top_logprobs"][0]["logprob"], -1.5);
5778    }
5779
5780    /// `top_logprobs: 0` asks for the chosen tokens' log probabilities with no alternatives.
5781    #[tokio::test]
5782    async fn zero_top_logprobs_returns_entries_without_alternatives() {
5783        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5784                       "logprobs":true,"top_logprobs":0}"#;
5785        let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5786        let lp = &v["choices"][0]["logprobs"]["content"][0];
5787        assert_eq!(lp["token"], "hi");
5788        assert_eq!(lp["logprob"], -0.25);
5789        assert_eq!(lp["top_logprobs"], serde_json::json!([]));
5790    }
5791
5792    /// A streamed reply carries the token's logprob on the SAME chunk as its text, which is what
5793    /// an OpenAI client pairs together.
5794    #[tokio::test]
5795    async fn logprobs_ride_the_streaming_text_chunk() {
5796        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5797                       "stream":true,"logprobs":true,"top_logprobs":1}"#;
5798        let frames = sse_frames(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5799        let chunk = frames
5800            .iter()
5801            .filter(|f| *f != "[DONE]")
5802            .map(|f| serde_json::from_str::<serde_json::Value>(f).unwrap())
5803            .find(|v| v["choices"][0]["delta"]["content"] == "hi")
5804            .expect("a content chunk");
5805        let lp = &chunk["choices"][0]["logprobs"]["content"][0];
5806        assert_eq!(lp["token"], "hi");
5807        assert_eq!(lp["logprob"], -0.25);
5808        assert_eq!(lp["top_logprobs"][0]["token"], "ho");
5809    }
5810
5811    /// A backend that cannot report logprobs answers a `400` naming the field instead of a reply
5812    /// without them.
5813    #[tokio::test]
5814    async fn logprobs_on_a_backend_without_them_is_a_400() {
5815        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5816                       "logprobs":true}"#;
5817        let resp = post_chat(router_for(Arc::new(EchoGen("a"))), body).await;
5818        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5819        let v = body_json(resp).await;
5820        assert_eq!(v["error"]["param"], "logprobs");
5821    }
5822
5823    /// A generator whose prompt does not fit the context.
5824    struct OverflowGen;
5825    impl ChatGenerator for OverflowGen {
5826        fn status(&self) -> GeneratorStatus {
5827            cpu_status()
5828        }
5829
5830        fn vocab_size(&self) -> usize {
5831            TEST_VOCAB
5832        }
5833
5834        fn chat(
5835            &self,
5836            _messages: &[ChatMessage],
5837            _tools: Option<&serde_json::Value>,
5838            _tool_choice: Option<&str>,
5839            _params: &GenParams,
5840            _cancel: &Arc<AtomicBool>,
5841            _on_delta: &mut dyn FnMut(Delta),
5842        ) -> anyhow::Result<ChatOutcome> {
5843            Err(ContextLengthExceeded {
5844                message: "too long".into(),
5845            }
5846            .into())
5847        }
5848    }
5849
5850    /// B86: an over-long prompt is the client's to fix — `400 context_length_exceeded`, which
5851    /// OpenAI clients act on, not the `500` they retry unchanged.
5852    #[tokio::test]
5853    async fn an_over_long_prompt_is_a_400_context_length_exceeded() {
5854        let resp = post_chat(
5855            router_for(Arc::new(OverflowGen)),
5856            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5857        )
5858        .await;
5859        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5860        let v = body_json(resp).await;
5861        assert_eq!(v["error"]["type"], "invalid_request_error");
5862        assert_eq!(v["error"]["code"], "context_length_exceeded");
5863        assert_eq!(v["error"]["param"], "messages");
5864        assert_eq!(v["error"]["message"], "too long");
5865    }
5866
5867    /// B86 on a stream: the `200` is already out, so the over-long prompt arrives as the terminal
5868    /// error frame — carrying the same typed error as the non-streaming `400`, not a generic
5869    /// `server_error` a client cannot tell from a crash — and `[DONE]` still closes the stream.
5870    #[tokio::test]
5871    async fn an_over_long_prompt_on_a_stream_is_a_typed_error_frame() {
5872        let frames = sse_frames(
5873            post_chat(
5874                router_for(Arc::new(OverflowGen)),
5875                r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5876            )
5877            .await,
5878        )
5879        .await;
5880        assert_eq!(
5881            frames.last().map(String::as_str),
5882            Some("[DONE]"),
5883            "{frames:?}"
5884        );
5885        let err: serde_json::Value = frames
5886            .iter()
5887            .filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
5888            .find(|v| v.get("error").is_some())
5889            .expect("an error frame");
5890        assert_eq!(err["error"]["type"], "invalid_request_error");
5891        assert_eq!(err["error"]["code"], "context_length_exceeded");
5892        assert_eq!(err["error"]["param"], "messages");
5893        assert_eq!(err["error"]["message"], "too long");
5894    }
5895
5896    /// B86: a body over the size limit is `413` and a body without a JSON content type `415` — not
5897    /// the `400` a malformed body gets — still in the OpenAI error envelope.
5898    #[tokio::test]
5899    async fn oversized_and_untyped_bodies_keep_their_status() {
5900        let huge = format!(
5901            r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
5902            "x".repeat(3 << 20)
5903        );
5904        let resp = post_chat(router_for(Arc::new(EchoGen("a"))), &huge).await;
5905        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
5906        assert_eq!(
5907            body_json(resp).await["error"]["type"],
5908            "invalid_request_error"
5909        );
5910
5911        let resp = router_for(Arc::new(EchoGen("a")))
5912            .oneshot(
5913                Request::builder()
5914                    .method("POST")
5915                    .uri("/v1/chat/completions")
5916                    .body(Body::from(
5917                        r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5918                    ))
5919                    .unwrap(),
5920            )
5921            .await
5922            .unwrap();
5923        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
5924        assert_eq!(
5925            body_json(resp).await["error"]["type"],
5926            "invalid_request_error"
5927        );
5928
5929        // Malformed JSON stays a 400.
5930        let resp = post_chat(router_for(Arc::new(EchoGen("a"))), "{not json").await;
5931        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5932    }
5933
5934    /// B137: the bearer check runs on the headers, before the body is read. A client without a
5935    /// token whose body never finishes arriving still gets its 401 at once.
5936    #[tokio::test]
5937    async fn the_bearer_check_does_not_wait_for_the_body() {
5938        let mut cfg = Config::default();
5939        cfg.serve.api_key = Some("s3cret".into());
5940        let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
5941        let router = build_router(AppState::new(g, "m", 1, Arc::new(cfg)));
5942        let never = futures_util::stream::pending::<Result<axum::body::Bytes, std::io::Error>>();
5943        let resp = tokio::time::timeout(
5944            Duration::from_secs(2),
5945            router.oneshot(
5946                Request::builder()
5947                    .method("POST")
5948                    .uri("/v1/chat/completions")
5949                    .header("content-type", "application/json")
5950                    .body(Body::from_stream(never))
5951                    .unwrap(),
5952            ),
5953        )
5954        .await
5955        .expect("an unauthenticated request waited for its body")
5956        .unwrap();
5957        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
5958    }
5959
5960    /// B137: `-1` is the "unset" sentinel llama.cpp-style clients send for `seed` and `max_tokens`;
5961    /// it is accepted as unset, and any other negative value is still refused.
5962    #[tokio::test]
5963    async fn minus_one_seed_and_max_tokens_mean_unset() {
5964        let p = GenParams::from_request(&req(
5965            r#"{"model":"m","messages":[],"seed":-1,"max_tokens":-1,"max_completion_tokens":-1}"#,
5966        ))
5967        .unwrap();
5968        assert_eq!((p.seed, p.max_tokens), (None, None));
5969        let p = GenParams::from_request(&req(
5970            r#"{"model":"m","messages":[],"seed":18446744073709551615,"max_tokens":7}"#,
5971        ))
5972        .unwrap();
5973        assert_eq!((p.seed, p.max_tokens), (Some(u64::MAX), Some(7)));
5974        for bad in [
5975            r#""seed":-2"#,
5976            r#""max_tokens":-5"#,
5977            r#""max_tokens":4294967296"#,
5978        ] {
5979            let raw = format!(r#"{{"model":"m","messages":[],{bad}}}"#);
5980            assert!(serde_json::from_str::<ChatRequest>(&raw).is_err(), "{bad}");
5981        }
5982
5983        let resp = post_chat(
5984            router_for(Arc::new(EchoGen("a"))),
5985            r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"seed":-1,"max_tokens":-1}"#,
5986        )
5987        .await;
5988        assert_eq!(resp.status(), StatusCode::OK);
5989    }
5990
5991    /// Sits in a "prefill" that emits nothing, polling `cancel` the way a real prefill loop does,
5992    /// and records whether the latch reached it. Bounded, so a broken hang-up path fails the test
5993    /// instead of hanging it.
5994    struct HangGen {
5995        entered: Arc<AtomicBool>,
5996        cancelled: Arc<AtomicBool>,
5997    }
5998    impl ChatGenerator for HangGen {
5999        fn status(&self) -> GeneratorStatus {
6000            cpu_status()
6001        }
6002
6003        fn vocab_size(&self) -> usize {
6004            TEST_VOCAB
6005        }
6006
6007        fn chat(
6008            &self,
6009            _messages: &[ChatMessage],
6010            _tools: Option<&serde_json::Value>,
6011            _tool_choice: Option<&str>,
6012            _params: &GenParams,
6013            cancel: &Arc<AtomicBool>,
6014            _on_delta: &mut dyn FnMut(Delta),
6015        ) -> anyhow::Result<ChatOutcome> {
6016            self.entered.store(true, Ordering::Relaxed);
6017            let started = Instant::now();
6018            while started.elapsed() < Duration::from_secs(5) {
6019                if cancel.load(Ordering::Relaxed) {
6020                    self.cancelled.store(true, Ordering::Relaxed);
6021                    break;
6022                }
6023                std::thread::sleep(Duration::from_millis(2));
6024            }
6025            Ok(ChatOutcome {
6026                finish: Finish::Stop,
6027                prompt_tokens: 1,
6028                completion_tokens: 0,
6029                cached_tokens: 0,
6030            })
6031        }
6032    }
6033
6034    /// Wait (bounded) for `flag` to be set.
6035    async fn eventually(flag: &AtomicBool, within: Duration) -> bool {
6036        let started = Instant::now();
6037        while !flag.load(Ordering::Relaxed) {
6038            if started.elapsed() > within {
6039                return false;
6040            }
6041            tokio::time::sleep(Duration::from_millis(5)).await;
6042        }
6043        true
6044    }
6045
6046    /// Serve a [`HangGen`] on a real socket, send one chat request, hang up once the generation
6047    /// is running, and report whether the hang-up reached the generator's `cancel` latch.
6048    async fn hang_up_reaches_the_generator(stream: bool) -> bool {
6049        use tokio::io::AsyncWriteExt;
6050        let entered = Arc::new(AtomicBool::new(false));
6051        let cancelled = Arc::new(AtomicBool::new(false));
6052        let g: Arc<dyn ChatGenerator> = Arc::new(HangGen {
6053            entered: entered.clone(),
6054            cancelled: cancelled.clone(),
6055        });
6056        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
6057        let addr = listener.local_addr().unwrap();
6058        let router = router_for(g);
6059        let server = tokio::spawn(async move { axum::serve(listener, router).await });
6060        let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
6061        let body = format!(
6062            r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6063        );
6064        let head = format!(
6065            "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n\
6066             Content-Type: application/json\r\nContent-Length: {}\r\n\r\n",
6067            body.len()
6068        );
6069        sock.write_all(head.as_bytes()).await.unwrap();
6070        sock.write_all(body.as_bytes()).await.unwrap();
6071        assert!(
6072            eventually(&entered, Duration::from_secs(2)).await,
6073            "the generation never started"
6074        );
6075        drop(sock);
6076        let reached = eventually(&cancelled, Duration::from_secs(2)).await;
6077        server.abort();
6078        reached
6079    }
6080
6081    /// B85: a non-streaming client that hangs up mid-generation cancels it, so its slot is not
6082    /// held to `max_tokens` for nobody.
6083    #[tokio::test]
6084    async fn a_non_streaming_hang_up_cancels_the_generation() {
6085        assert!(hang_up_reaches_the_generator(false).await);
6086    }
6087
6088    /// B85: a streaming client that hangs up while nothing is being sent — a long prefill — cancels
6089    /// the generation at once, not at the next delta.
6090    #[tokio::test]
6091    async fn a_streaming_hang_up_during_prefill_cancels_the_generation() {
6092        assert!(hang_up_reaches_the_generator(true).await);
6093    }
6094
6095    // --- response_format, prompt counting, keep-alive, body limit ------------------------------
6096
6097    fn format_of(raw: &str) -> Result<Option<ResponseFormat>, ParamError> {
6098        GenParams::from_request(&req(&format!(
6099            r#"{{"model":"m","messages":[],"response_format":{raw}}}"#
6100        )))
6101        .map(|p| p.response_format)
6102    }
6103
6104    /// B137: `response_format` is validated into a value the generator acts on — `text` is no
6105    /// constraint, the two JSON kinds carry their schema — and a type or shape this server does
6106    /// not do is a `400` naming the field, never a quietly unconstrained reply.
6107    #[test]
6108    fn response_format_parses_and_refuses_what_it_cannot_do() {
6109        let schema =
6110            serde_json::json!({"type": "object", "properties": {"a": {"type": "integer"}}});
6111        assert_eq!(format_of("null"), Ok(None));
6112        assert_eq!(format_of(r#"{"type":"text"}"#), Ok(None));
6113        assert_eq!(
6114            format_of(r#"{"type":"json_object"}"#),
6115            Ok(Some(ResponseFormat::JsonObject))
6116        );
6117        assert_eq!(
6118            format_of(&format!(
6119                r#"{{"type":"json_schema",
6120                     "json_schema":{{"name":"x","strict":true,"schema":{schema}}}}}"#
6121            )),
6122            Ok(Some(ResponseFormat::JsonSchema(schema.clone())))
6123        );
6124        // llama.cpp's spelling: a schema beside `json_object`.
6125        assert_eq!(
6126            format_of(&format!(r#"{{"type":"json_object","schema":{schema}}}"#)),
6127            Ok(Some(ResponseFormat::JsonSchema(schema)))
6128        );
6129        assert_eq!(
6130            ResponseFormat::JsonObject.schema(),
6131            serde_json::json!({"type": "object"})
6132        );
6133        // `json_schema` with no schema, or a `null` one, is any JSON value.
6134        for any in [
6135            r#"{"type":"json_schema"}"#,
6136            r#"{"type":"json_schema","json_schema":{"name":"x"}}"#,
6137            r#"{"type":"json_schema","json_schema":{"name":"x","schema":null}}"#,
6138            r#"{"type":"json_schema","json_schema":null}"#,
6139        ] {
6140            assert_eq!(
6141                format_of(any),
6142                Ok(Some(ResponseFormat::JsonSchema(serde_json::json!({})))),
6143                "{any}"
6144            );
6145        }
6146        for bad in [
6147            r#"{"type":"xml"}"#,
6148            r#"{"type":"json_schema","json_schema":"x"}"#,
6149            r#"{"type":"json_schema","json_schema":{"schema":"object"}}"#,
6150            r#"{"type":"json_object","schema":[]}"#,
6151            r#""json_object""#,
6152            r#"{"kind":"json_object"}"#,
6153        ] {
6154            let e = format_of(bad).expect_err(bad);
6155            assert_eq!(e.param, "response_format", "{bad}");
6156        }
6157        assert!(format_of(r#"{"type":"xml"}"#)
6158            .unwrap_err()
6159            .message
6160            .contains("\"xml\""));
6161    }
6162
6163    /// Records the `response_format` each `chat` call was handed.
6164    #[derive(Default)]
6165    struct FormatProbe(std::sync::Mutex<Vec<Option<ResponseFormat>>>);
6166    impl ChatGenerator for FormatProbe {
6167        fn status(&self) -> GeneratorStatus {
6168            cpu_status()
6169        }
6170
6171        fn vocab_size(&self) -> usize {
6172            TEST_VOCAB
6173        }
6174
6175        fn chat(
6176            &self,
6177            _messages: &[ChatMessage],
6178            _tools: Option<&serde_json::Value>,
6179            _tool_choice: Option<&str>,
6180            params: &GenParams,
6181            _cancel: &Arc<AtomicBool>,
6182            on_delta: &mut dyn FnMut(Delta),
6183        ) -> anyhow::Result<ChatOutcome> {
6184            self.0.lock().unwrap().push(params.response_format.clone());
6185            on_delta(Delta::Content("{}".into()));
6186            Ok(ChatOutcome {
6187                finish: Finish::Stop,
6188                prompt_tokens: 1,
6189                completion_tokens: 1,
6190                cached_tokens: 0,
6191            })
6192        }
6193    }
6194
6195    /// Through the router: the validated format reaches the generator, and a bad one is a `400`
6196    /// before it does — on a stream as well, which must not open.
6197    #[tokio::test]
6198    async fn response_format_reaches_the_generator_or_is_a_400() {
6199        let probe = Arc::new(FormatProbe::default());
6200        let router = router_for(probe.clone());
6201        let ok = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
6202                     "response_format":{"type":"json_object"}}"#;
6203        assert_eq!(post_chat(router.clone(), ok).await.status(), StatusCode::OK);
6204        for stream in [false, true] {
6205            let bad = format!(
6206                r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream},
6207                     "response_format":{{"type":"yaml"}}}}"#
6208            );
6209            let resp = post_chat(router.clone(), &bad).await;
6210            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6211            let v = body_json(resp).await;
6212            assert_eq!(v["error"]["type"], "invalid_request_error");
6213            assert_eq!(v["error"]["param"], "response_format");
6214        }
6215        assert_eq!(
6216            *probe.0.lock().unwrap(),
6217            vec![Some(ResponseFormat::JsonObject)]
6218        );
6219    }
6220
6221    /// A generator that refuses every request as the client's fault, either before generating
6222    /// (`prepare`) or — like a generator without a count — only from `chat`.
6223    struct RefuseGen {
6224        in_count: bool,
6225        chats: AtomicU64,
6226    }
6227    impl RefuseGen {
6228        fn refusal() -> anyhow::Error {
6229            ParamError {
6230                param: "response_format",
6231                message: "response_format cannot be enforced: unsupported keyword".into(),
6232            }
6233            .into()
6234        }
6235    }
6236    impl ChatGenerator for RefuseGen {
6237        fn status(&self) -> GeneratorStatus {
6238            cpu_status()
6239        }
6240
6241        fn vocab_size(&self) -> usize {
6242            TEST_VOCAB
6243        }
6244
6245        fn prepare(
6246            &self,
6247            _messages: &[ChatMessage],
6248            _tools: Option<&serde_json::Value>,
6249            _tool_choice: Option<&str>,
6250            _params: &GenParams,
6251        ) -> anyhow::Result<Option<PreparedRequest>> {
6252            if self.in_count {
6253                Err(Self::refusal())
6254            } else {
6255                Ok(None)
6256            }
6257        }
6258
6259        fn chat(
6260            &self,
6261            _messages: &[ChatMessage],
6262            _tools: Option<&serde_json::Value>,
6263            _tool_choice: Option<&str>,
6264            _params: &GenParams,
6265            _cancel: &Arc<AtomicBool>,
6266            _on_delta: &mut dyn FnMut(Delta),
6267        ) -> anyhow::Result<ChatOutcome> {
6268            self.chats.fetch_add(1, Ordering::Relaxed);
6269            Err(Self::refusal())
6270        }
6271    }
6272
6273    /// A [`ParamError`] from a generator is the client's fault: a `400` naming the field. Raised
6274    /// by `prepare` it is answered before the request is queued — a streamed request gets a
6275    /// real `400`, and `chat` never runs. Raised only by `chat` (a generator that cannot count)
6276    /// it is still a `400` unstreamed, and a typed error frame on a stream.
6277    #[tokio::test]
6278    async fn a_generator_param_error_is_a_400() {
6279        let body = |stream: bool| {
6280            format!(
6281                r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6282            )
6283        };
6284        let early = Arc::new(RefuseGen {
6285            in_count: true,
6286            chats: AtomicU64::new(0),
6287        });
6288        for stream in [false, true] {
6289            let resp = post_chat(router_for(early.clone()), &body(stream)).await;
6290            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6291            let v = body_json(resp).await;
6292            assert_eq!(v["error"]["param"], "response_format");
6293            assert_eq!(v["error"]["type"], "invalid_request_error");
6294        }
6295        assert_eq!(early.chats.load(Ordering::Relaxed), 0);
6296
6297        let late = Arc::new(RefuseGen {
6298            in_count: false,
6299            chats: AtomicU64::new(0),
6300        });
6301        let resp = post_chat(router_for(late.clone()), &body(false)).await;
6302        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
6303        assert_eq!(body_json(resp).await["error"]["param"], "response_format");
6304        let frames = sse_frames(post_chat(router_for(late), &body(true)).await).await;
6305        let err: serde_json::Value = frames
6306            .iter()
6307            .filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
6308            .find(|v| v.get("error").is_some())
6309            .expect("an error frame");
6310        assert_eq!(err["error"]["type"], "invalid_request_error");
6311        assert_eq!(err["error"]["param"], "response_format");
6312    }
6313
6314    /// A generator that prepares every request — its prompt `tokens` long against a context of
6315    /// `limit` — and counts what the server calls: `prepares`, `prepared` (`chat_prepared` handed
6316    /// back its own state) and `chats` (plain `chat`).
6317    #[derive(Default)]
6318    struct CountGen {
6319        tokens: u32,
6320        limit: Option<u32>,
6321        prepares: AtomicU64,
6322        prepared: AtomicU64,
6323        chats: AtomicU64,
6324    }
6325
6326    /// The state [`CountGen`] prepares, which `chat_prepared` must get back.
6327    struct CountState(u32);
6328    impl ChatGenerator for CountGen {
6329        fn status(&self) -> GeneratorStatus {
6330            cpu_status()
6331        }
6332
6333        fn vocab_size(&self) -> usize {
6334            TEST_VOCAB
6335        }
6336
6337        fn prepare(
6338            &self,
6339            _messages: &[ChatMessage],
6340            _tools: Option<&serde_json::Value>,
6341            _tool_choice: Option<&str>,
6342            _params: &GenParams,
6343        ) -> anyhow::Result<Option<PreparedRequest>> {
6344            self.prepares.fetch_add(1, Ordering::Relaxed);
6345            Ok(Some(PreparedRequest::new(
6346                self.tokens,
6347                self.limit,
6348                CountState(self.tokens),
6349            )))
6350        }
6351
6352        fn chat_prepared(
6353            &self,
6354            prepared: PreparedRequest,
6355            _messages: &[ChatMessage],
6356            _tools: Option<&serde_json::Value>,
6357            _tool_choice: Option<&str>,
6358            _params: &GenParams,
6359            _cancel: &Arc<AtomicBool>,
6360            on_delta: &mut dyn FnMut(Delta),
6361        ) -> anyhow::Result<ChatOutcome> {
6362            let CountState(tokens) = prepared.into_state().expect("our own prepared state");
6363            self.prepared.fetch_add(1, Ordering::Relaxed);
6364            on_delta(Delta::Content("ok".into()));
6365            Ok(ChatOutcome {
6366                finish: Finish::Stop,
6367                prompt_tokens: tokens,
6368                completion_tokens: 1,
6369                cached_tokens: 0,
6370            })
6371        }
6372
6373        fn chat(
6374            &self,
6375            _messages: &[ChatMessage],
6376            _tools: Option<&serde_json::Value>,
6377            _tool_choice: Option<&str>,
6378            _params: &GenParams,
6379            _cancel: &Arc<AtomicBool>,
6380            on_delta: &mut dyn FnMut(Delta),
6381        ) -> anyhow::Result<ChatOutcome> {
6382            self.chats.fetch_add(1, Ordering::Relaxed);
6383            on_delta(Delta::Content("ok".into()));
6384            Ok(ChatOutcome {
6385                finish: Finish::Stop,
6386                prompt_tokens: self.tokens,
6387                completion_tokens: 1,
6388                cached_tokens: 0,
6389            })
6390        }
6391    }
6392
6393    /// B10a/B82: an over-long prompt is refused from its count — `400 context_length_exceeded`
6394    /// in OpenAI's wording, on a stream too (no `200` and error frame), and before it takes a
6395    /// slot: here the only slot is held throughout, and the refusal still arrives at once. A
6396    /// prompt that fits, or a generator that knows no limit, generates as before.
6397    #[tokio::test]
6398    async fn an_over_long_prompt_is_refused_before_it_takes_a_slot() {
6399        let long = Arc::new(CountGen {
6400            tokens: 100,
6401            limit: Some(99),
6402            ..Default::default()
6403        });
6404        let state = AppState::new(long.clone(), "m", 1, Arc::new(Config::default()));
6405        let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
6406        let router = build_router(state);
6407        for stream in [false, true] {
6408            let body = format!(
6409                r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6410            );
6411            let resp =
6412                tokio::time::timeout(Duration::from_secs(2), post_chat(router.clone(), &body))
6413                    .await
6414                    .expect("an over-long prompt waited for a slot");
6415            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6416            let v = body_json(resp).await;
6417            assert_eq!(v["error"]["code"], "context_length_exceeded");
6418            assert_eq!(v["error"]["param"], "messages");
6419            assert_eq!(
6420                v["error"]["message"],
6421                "This model's maximum context length is 99 tokens. However, your messages \
6422                 resulted in 100 tokens. Please reduce the length of the messages."
6423            );
6424        }
6425        drop(held);
6426        assert_eq!(long.prepared.load(Ordering::Relaxed), 0);
6427        assert_eq!(long.chats.load(Ordering::Relaxed), 0);
6428
6429        for (tokens, limit) in [(99, Some(99)), (100_000, None)] {
6430            let g = Arc::new(CountGen {
6431                tokens,
6432                limit,
6433                ..Default::default()
6434            });
6435            let resp = post_chat(
6436                router_for(g.clone()),
6437                r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6438            )
6439            .await;
6440            assert_eq!(resp.status(), StatusCode::OK, "{tokens} / {limit:?}");
6441            assert_eq!(body_json(resp).await["usage"]["prompt_tokens"], tokens);
6442        }
6443    }
6444
6445    /// Sleeps before its one delta: a long prefill, as the client sees it.
6446    struct SlowFirstToken(Duration);
6447    impl ChatGenerator for SlowFirstToken {
6448        fn status(&self) -> GeneratorStatus {
6449            cpu_status()
6450        }
6451
6452        fn vocab_size(&self) -> usize {
6453            TEST_VOCAB
6454        }
6455
6456        fn chat(
6457            &self,
6458            _messages: &[ChatMessage],
6459            _tools: Option<&serde_json::Value>,
6460            _tool_choice: Option<&str>,
6461            _params: &GenParams,
6462            _cancel: &Arc<AtomicBool>,
6463            on_delta: &mut dyn FnMut(Delta),
6464        ) -> anyhow::Result<ChatOutcome> {
6465            std::thread::sleep(self.0);
6466            on_delta(Delta::Content("late".into()));
6467            Ok(ChatOutcome {
6468                finish: Finish::Stop,
6469                prompt_tokens: 1,
6470                completion_tokens: 1,
6471                cached_tokens: 0,
6472            })
6473        }
6474    }
6475
6476    /// The raw SSE body of a streamed reply with `sse_keepalive_secs = secs`, over a first token
6477    /// that takes longer than one interval.
6478    async fn slow_stream_body(secs: u64) -> String {
6479        let mut cfg = Config::default();
6480        cfg.serve.sse_keepalive_secs = secs;
6481        let g: Arc<dyn ChatGenerator> = Arc::new(SlowFirstToken(Duration::from_millis(1600)));
6482        let resp = post_chat(
6483            build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
6484            r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
6485        )
6486        .await;
6487        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
6488        String::from_utf8(bytes.to_vec()).unwrap()
6489    }
6490
6491    /// B137: a stream that goes quiet past the keep-alive interval carries an SSE comment line,
6492    /// which parsers ignore and idle-timeout proxies count as traffic; `0` sends none. The reply
6493    /// itself is the same either way.
6494    #[tokio::test]
6495    async fn a_quiet_stream_carries_keep_alive_comments_unless_disabled() {
6496        let comment = |body: &str| body.lines().any(|l| l.starts_with(':'));
6497        let on = slow_stream_body(1).await;
6498        assert!(comment(&on), "no keep-alive comment: {on:?}");
6499        let off = slow_stream_body(0).await;
6500        assert!(!comment(&off), "keep-alive sent while disabled: {off:?}");
6501        for body in [&on, &off] {
6502            assert!(body.contains("\"late\""), "{body:?}");
6503            assert!(body.contains("[DONE]"), "{body:?}");
6504        }
6505        assert_eq!(
6506            sse_keep_alive(&Config::default()),
6507            Some(Duration::from_secs(15))
6508        );
6509    }
6510
6511    /// A keep-alive interval too large for axum's timer (`Instant::now() + interval` overflows)
6512    /// is held to [`MAX_SSE_KEEPALIVE`] rather than panicking the stream.
6513    #[tokio::test]
6514    async fn a_huge_keep_alive_interval_is_bounded_not_a_panic() {
6515        let mut cfg = Config::default();
6516        cfg.serve.sse_keepalive_secs = u64::MAX;
6517        assert_eq!(sse_keep_alive(&cfg), Some(MAX_SSE_KEEPALIVE));
6518        let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
6519        let frames = sse_frames(
6520            post_chat(
6521                build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
6522                r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
6523            )
6524            .await,
6525        )
6526        .await;
6527        assert_eq!(
6528            frames.last().map(String::as_str),
6529            Some("[DONE]"),
6530            "{frames:?}"
6531        );
6532    }
6533
6534    /// A request is prepared ONCE — the server hands the prepared state back
6535    /// through `chat_prepared` and never calls `chat`, streamed or not. A generator that
6536    /// prepares nothing keeps being served by `chat`.
6537    #[tokio::test]
6538    async fn a_request_is_prepared_once_and_generated_from_its_preparation() {
6539        for stream in [false, true] {
6540            let g = Arc::new(CountGen {
6541                tokens: 7,
6542                ..Default::default()
6543            });
6544            let body = format!(
6545                r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6546            );
6547            let resp = post_chat(router_for(g.clone()), &body).await;
6548            assert_eq!(resp.status(), StatusCode::OK);
6549            let _ = resp.into_body().collect().await.unwrap();
6550            let counts = |c: &AtomicU64| c.load(Ordering::Relaxed);
6551            assert_eq!(
6552                (counts(&g.prepares), counts(&g.prepared), counts(&g.chats)),
6553                (1, 1, 0),
6554                "stream={stream}"
6555            );
6556        }
6557        let probe = Arc::new(FormatProbe::default());
6558        let resp = post_chat(
6559            router_for(probe.clone()),
6560            r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6561        )
6562        .await;
6563        assert_eq!(resp.status(), StatusCode::OK);
6564        assert_eq!(
6565            probe.0.lock().unwrap().len(),
6566            1,
6567            "a non-preparing generator still chats"
6568        );
6569    }
6570
6571    /// A malformed tool is a `400` naming `tools`, and a named `tool_choice` for a tool not
6572    /// offered a `400` naming `tool_choice` — both before the generator sees the request.
6573    #[tokio::test]
6574    async fn malformed_tools_and_unknown_tool_choices_are_400s_naming_the_field() {
6575        let probe = Arc::new(FormatProbe::default());
6576        for (extra, param) in [
6577            (r#""tools":[{"type":"function","function":{}}]"#, "tools"),
6578            (r#""tools":{"a":1}"#, "tools"),
6579            (
6580                r#""tools":[{"type":"function","function":{"name":"f"}}],
6581                   "tool_choice":{"type":"function","function":{"name":"g"}}"#,
6582                "tool_choice",
6583            ),
6584        ] {
6585            let body =
6586                format!(r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],{extra}}}"#);
6587            let resp = post_chat(router_for(probe.clone()), &body).await;
6588            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{extra}");
6589            assert_eq!(body_json(resp).await["error"]["param"], param, "{extra}");
6590        }
6591        assert!(probe.0.lock().unwrap().is_empty());
6592    }
6593
6594    /// B82: `serve.max_body_bytes` is the body limit — a body over it is a `413`, one under it is
6595    /// served — and a zero from a file means the default rather than refusing everything.
6596    #[tokio::test]
6597    async fn the_body_limit_is_configurable() {
6598        let mut cfg = Config::default();
6599        cfg.serve.max_body_bytes = 1024;
6600        let router = build_router(AppState::new(Arc::new(EchoGen("a")), "m", 1, Arc::new(cfg)));
6601        let body = |n: usize| {
6602            format!(
6603                r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
6604                "x".repeat(n)
6605            )
6606        };
6607        let resp = post_chat(router.clone(), &body(2048)).await;
6608        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
6609        assert_eq!(
6610            body_json(resp).await["error"]["type"],
6611            "invalid_request_error"
6612        );
6613        assert_eq!(post_chat(router, &body(512)).await.status(), StatusCode::OK);
6614
6615        let mut zero = Config::default();
6616        zero.serve.max_body_bytes = 0;
6617        assert_eq!(max_body_bytes(&zero), 2 << 20);
6618    }
6619
6620    /// Counts the preparations running at once and the most there ever were; each takes a while,
6621    /// so simultaneous requests overlap if nothing bounds them.
6622    #[derive(Default)]
6623    struct SlowPrepare {
6624        running: AtomicU64,
6625        most: AtomicU64,
6626        prepares: AtomicU64,
6627    }
6628    impl SlowPrepare {
6629        fn slow_prepare(&self) {
6630            self.prepares.fetch_add(1, Ordering::Relaxed);
6631            let now = self.running.fetch_add(1, Ordering::SeqCst) + 1;
6632            self.most.fetch_max(now, Ordering::SeqCst);
6633            std::thread::sleep(Duration::from_millis(150));
6634            self.running.fetch_sub(1, Ordering::SeqCst);
6635        }
6636    }
6637    impl ChatGenerator for SlowPrepare {
6638        fn status(&self) -> GeneratorStatus {
6639            cpu_status()
6640        }
6641
6642        fn vocab_size(&self) -> usize {
6643            TEST_VOCAB
6644        }
6645
6646        fn prepare(
6647            &self,
6648            _messages: &[ChatMessage],
6649            _tools: Option<&serde_json::Value>,
6650            _tool_choice: Option<&str>,
6651            _params: &GenParams,
6652        ) -> anyhow::Result<Option<PreparedRequest>> {
6653            self.slow_prepare();
6654            Ok(None)
6655        }
6656
6657        fn prepare_completion(&self, prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
6658            self.slow_prepare();
6659            Ok(Some((prompt.len() as u32, None)))
6660        }
6661
6662        fn complete(
6663            &self,
6664            _prompt: &str,
6665            _params: &GenParams,
6666            _cancel: &Arc<AtomicBool>,
6667            on_text: &mut dyn FnMut(&str),
6668        ) -> anyhow::Result<ChatOutcome> {
6669            on_text("ok");
6670            Ok(ChatOutcome {
6671                finish: Finish::Stop,
6672                prompt_tokens: 1,
6673                completion_tokens: 1,
6674                cached_tokens: 0,
6675            })
6676        }
6677
6678        fn chat(
6679            &self,
6680            _messages: &[ChatMessage],
6681            _tools: Option<&serde_json::Value>,
6682            _tool_choice: Option<&str>,
6683            _params: &GenParams,
6684            _cancel: &Arc<AtomicBool>,
6685            on_delta: &mut dyn FnMut(Delta),
6686        ) -> anyhow::Result<ChatOutcome> {
6687            on_delta(Delta::Content("ok".into()));
6688            Ok(ChatOutcome {
6689                finish: Finish::Stop,
6690                prompt_tokens: 1,
6691                completion_tokens: 1,
6692                cached_tokens: 0,
6693            })
6694        }
6695    }
6696
6697    /// Preparation is admitted per model, as many at once as the model has slots: a burst of
6698    /// requests never runs more preparations than that, though it does run that many.
6699    #[tokio::test]
6700    async fn concurrent_preparations_are_bounded_by_the_slots() {
6701        let g = Arc::new(SlowPrepare::default());
6702        let router = build_router(AppState::new(
6703            g.clone(),
6704            "m",
6705            2,
6706            Arc::new(Config::default()),
6707        ));
6708        let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
6709        let all = (0..5).map(|_| post_chat(router.clone(), body));
6710        for resp in futures_util::future::join_all(all).await {
6711            assert_eq!(resp.status(), StatusCode::OK);
6712        }
6713        assert_eq!(g.prepares.load(Ordering::Relaxed), 5);
6714        assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
6715    }
6716
6717    /// A raw completion's prompt count runs under the same per-model bound as a chat request's
6718    /// preparation, sharing its permits: a mixed burst never prepares more at once than the model
6719    /// has slots.
6720    #[tokio::test]
6721    async fn completion_preparations_share_the_chat_bound() {
6722        let g = Arc::new(SlowPrepare::default());
6723        let router = build_router(AppState::new(
6724            g.clone(),
6725            "m",
6726            2,
6727            Arc::new(Config::default()),
6728        ));
6729        let chat = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
6730        let raw = r#"{"model":"m","prompt":"hi"}"#;
6731        let all = (0..6).map(|i| {
6732            let router = router.clone();
6733            async move {
6734                let (uri, body) = if i % 2 == 0 {
6735                    ("/v1/chat/completions", chat)
6736                } else {
6737                    ("/v1/completions", raw)
6738                };
6739                router
6740                    .oneshot(
6741                        Request::builder()
6742                            .method("POST")
6743                            .uri(uri)
6744                            .header("content-type", "application/json")
6745                            .body(Body::from(body))
6746                            .unwrap(),
6747                    )
6748                    .await
6749                    .unwrap()
6750            }
6751        });
6752        for resp in futures_util::future::join_all(all).await {
6753            assert_eq!(resp.status(), StatusCode::OK);
6754        }
6755        assert_eq!(g.prepares.load(Ordering::Relaxed), 6);
6756        assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
6757    }
6758
6759    /// A request waiting to be prepared that the client abandons gives its place back: it is never
6760    /// prepared, and the permits are all there afterwards.
6761    #[tokio::test]
6762    async fn an_abandoned_wait_for_preparation_is_cancelled() {
6763        let g = Arc::new(SlowPrepare::default());
6764        let state = AppState::new(g.clone(), "m", 1, Arc::new(Config::default()));
6765        let prepares = state.models[0].prepares.clone();
6766        let held = prepares.clone().acquire_owned().await.unwrap();
6767        let waited = tokio::time::timeout(
6768            Duration::from_millis(200),
6769            post_chat(
6770                build_router(state),
6771                r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6772            ),
6773        )
6774        .await;
6775        assert!(waited.is_err(), "the request must still be waiting");
6776        drop(held);
6777        assert_eq!(prepares.available_permits(), 1);
6778        assert_eq!(g.prepares.load(Ordering::Relaxed), 0);
6779    }
6780}