Skip to main content

infr_server/
lib.rs

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