Skip to main content

ferrox_server/
lib.rs

1//! ferrox-server: OpenAI-compatible HTTP surface (`/health`,
2//! `/v1/models`, `/v1/chat/completions`, `/v1/completions`,
3//! `/v1/tokenize`, `/v1/detokenize`, `/v1/embeddings`) over the
4//! ferrox-models decoder, plus a whole-response cache for exact-repeat
5//! requests (see `cache` module). Loads a real GGUF checkpoint and its
6//! own real tokenizer when `-m`/`--model` or `FERROX_MODEL_PATH` is set
7//! (see `model` module). Supports sampling
8//! (temperature/top_p/top_k/repetition_penalty), stop sequences, and SSE
9//! streaming (see `generate` module).
10//!
11//! Concurrency: the loaded model
12//! (`Model`) is immutable once loaded and shared via `Arc`, not locked
13//! behind a `Mutex` -- there is no shared mutable decoder state for
14//! concurrent requests to contend on or for one panicking request to
15//! poison. The *pointer* to it is swappable (`AppState::active`, behind
16//! an `RwLock` held only long enough to clone one `Arc`), which is what
17//! `/admin/models/load` swaps; a request that has already cloned its
18//! handle finishes against the exact weights it started on, and the old
19//! model is freed when the last such request lets go.
20//! Each request builds its own KV cache (see `generate::generate`)
21//! and runs its decode loop on tokio's blocking-thread pool via
22//! `spawn_blocking`, so CPU-bound generation no longer blocks the async
23//! reactor threads -- multiple requests can decode genuinely
24//! concurrently, bounded by that pool rather than serialized through one
25//! lock. Only the small whole-response cache is still mutable shared
26//! state, and it's locked only for the brief get/put around it, never
27//! across a decode.
28//!
29//! Streaming scope: when `stream: true` and tools are inactive, each
30//! decoded chunk is pushed through a bounded `mpsc` channel from the
31//! blocking generate task into the SSE writer so time-to-first-byte
32//! overlaps with ongoing decode. Tool-call requests still buffer the
33//! full response first (detection needs the stop-bounded text).
34//! Continuous-batching streaming also buffers (batcher returns one
35//! string).
36
37mod admin;
38mod anthropic;
39mod attribution;
40mod budget;
41mod cache_admin;
42mod cancel;
43mod chat_template;
44mod conversations;
45mod generate;
46mod health;
47mod journal;
48mod json_mode;
49mod limits;
50mod mcp;
51mod model;
52mod openai_extra;
53mod output;
54mod policy;
55mod response_cache;
56pub(crate) mod responses;
57mod resume;
58mod security;
59mod serving;
60mod session;
61mod sse;
62mod stats;
63mod stop;
64mod stream_events;
65mod tasks;
66
67use std::cell::RefCell;
68use std::convert::Infallible;
69use std::fmt;
70use std::net::{IpAddr, Ipv4Addr, SocketAddr};
71use std::path::PathBuf;
72use std::rc::Rc;
73use std::str::FromStr;
74use std::sync::{Arc, Mutex, MutexGuard};
75use std::time::Duration;
76
77use axum::{
78    extract::State,
79    http::StatusCode,
80    response::sse::{Event, Sse},
81    response::{IntoResponse, Response},
82    routing::{get, post},
83    Json, Router,
84};
85use clap::{Parser, ValueEnum};
86use serde::{Deserialize, Serialize};
87
88use ferrox_core::cache::KvBlockPool;
89use ferrox_models::kimi_tokenizer::KimiTokenizer;
90use ferrox_models::sampling::SamplingParams;
91use ferrox_models::tokenizer::StopTokens;
92use ferrox_models::{Decoder, Gemma4Engine, KimiEngine, MlaEngine, PrefixCache};
93use generate::{FinishReason, GenerationParams};
94use model::ServerTokenizer;
95use response_cache::{CacheKey, ResponseCache};
96
97// `PartialEq` so ferrox-cli's serve tests can assert that both front
98// ends parse a command line into the SAME arguments, rather than
99// asserting field by field and missing whichever one is added next.
100#[derive(Parser, Debug, PartialEq)]
101// No `version` here on purpose. This struct is both `ferrox-server`'s
102// own argv and the body of ferrox-cli's `serve` subcommand, and clap
103// gives an embedded subcommand its own `--version` derived from the
104// variant name: `ferrox serve --version` printed `ferrox-serve 0.10.0`,
105// naming a binary nobody ships. The front end's own `--version` is the
106// truth, and both report the same workspace version anyway.
107#[command(
108    name = "ferrox-server",
109    about = "OpenAI-compatible Ferrox inference server"
110)]
111pub struct ServerArgs {
112    /// Model path (GGUF file or Kimi checkpoint directory).
113    #[arg(short = 'm', long = "model", value_name = "FILE")]
114    model: Option<String>,
115
116    /// IP address to listen on.
117    #[arg(long, value_name = "HOST")]
118    host: Option<IpAddr>,
119
120    /// Port to listen on. `0` asks the kernel for a free one; the
121    /// actually-bound address is then announced on stdout (see
122    /// [`announce_ready`]), which is how a supervising process is meant
123    /// to learn it.
124    #[arg(long, value_name = "PORT")]
125    port: Option<u16>,
126
127    /// CPU threads (sets FERROX_CPU_THREADS and RAYON_NUM_THREADS).
128    #[arg(short = 't', long = "threads", value_name = "N")]
129    threads: Option<usize>,
130
131    /// Device used for offloading (`none` disables GPU use).
132    #[arg(
133        long = "device",
134        visible_alias = "dev",
135        value_name = "DEVICE",
136        ignore_case = true
137    )]
138    device: Option<OffloadDevice>,
139
140    /// Print available offload devices and exit.
141    #[arg(long = "list-devices", default_value_t = false)]
142    list_devices: bool,
143
144    /// GPU layers: `0`, a positive number, `auto`, or `all`.
145    ///
146    /// Partial placement is not implemented yet; any value above zero
147    /// currently enables all supported operations on the selected backend.
148    #[arg(
149        long = "n-gpu-layers",
150        visible_aliases = ["gpu-layers", "ngl"],
151        value_name = "N"
152    )]
153    n_gpu_layers: Option<GpuLayers>,
154
155    /// MCP tool-server config JSON (stub: listed in `/v1/models` metadata).
156    #[arg(long = "mcp-config", value_name = "PATH")]
157    mcp_config: Option<PathBuf>,
158
159    /// Exit when stdin reaches EOF (for a supervising parent process).
160    ///
161    /// Opt-in on purpose: a server started with stdin redirected from
162    /// `/dev/null` -- systemd, cron, `nohup` -- sees EOF immediately,
163    /// and making this the default would turn those into a server that
164    /// exits the moment it starts. A parent that *wants* the guarantee
165    /// (the desktop shell) passes the flag and keeps the pipe open.
166    #[arg(long = "exit-on-stdin-close", default_value_t = false)]
167    exit_on_stdin_close: bool,
168
169    /// Start even though another ferrox process is already holding a
170    /// model. Off by default: two models on one box do not share it,
171    /// they thrash it, and both serve slower than either would alone.
172    /// `FERROX_ALLOW_MULTIPLE_INSTANCES=1` does the same.
173    #[arg(long = "allow-multiple-instances", default_value_t = false)]
174    allow_multiple_instances: bool,
175}
176
177impl ServerArgs {
178    /// Parses `ferrox-server`'s own argv, including the llama.cpp-style
179    /// multi-character short options (`-ngl`, `-dev`) that clap cannot
180    /// express and which are rewritten to their long forms first.
181    ///
182    /// Public because ferrox-cli's `serve` subcommand hands the same
183    /// arguments to the same parser rather than reimplementing it.
184    pub fn parse_llama_style<I>(argv: I) -> Self
185    where
186        I: IntoIterator<Item = String>,
187    {
188        Self::parse_from(rewrite_llama_style_argv(argv.into_iter().collect()))
189    }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
193enum OffloadDevice {
194    Auto,
195    None,
196    Cpu,
197    Metal,
198    Cuda,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202enum GpuLayers {
203    Auto,
204    All,
205    Count(u32),
206}
207
208impl GpuLayers {
209    fn offload_enabled(self) -> bool {
210        !matches!(self, Self::Count(0))
211    }
212}
213
214impl FromStr for GpuLayers {
215    type Err = String;
216
217    fn from_str(value: &str) -> Result<Self, Self::Err> {
218        match value {
219            "auto" => Ok(Self::Auto),
220            "all" => Ok(Self::All),
221            _ => value
222                .parse::<u32>()
223                .map(Self::Count)
224                .map_err(|_| "expected 0, a positive integer, 'auto', or 'all'".into()),
225        }
226    }
227}
228
229impl fmt::Display for GpuLayers {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            Self::Auto => f.write_str("auto"),
233            Self::All => f.write_str("all"),
234            Self::Count(value) => value.fmt(f),
235        }
236    }
237}
238
239/// Whether this build of the server has the Metal kernels compiled in.
240///
241/// Exists for the front ends that link this library: ferrox-cli's
242/// `metal` feature has to forward into ferrox-server
243/// (`ferrox-server?/metal`) or `ferrox serve --device metal` refuses on
244/// a Metal host while `ferrox run` on the same binary uses it. That
245/// mismatch is one Cargo manifest edit away and compiles cleanly, so
246/// ferrox-cli asserts on this constant at compile time.
247pub const BUILT_WITH_METAL: bool = cfg!(feature = "metal");
248
249/// Whether this build of the server has the CUDA kernels compiled in.
250/// See [`BUILT_WITH_METAL`].
251pub const BUILT_WITH_CUDA: bool = cfg!(feature = "cuda");
252
253fn rewrite_llama_style_argv(args: Vec<String>) -> Vec<String> {
254    args.into_iter()
255        .map(|arg| match arg.as_str() {
256            "-ngl" => "--n-gpu-layers".into(),
257            "-dev" => "--device".into(),
258            _ => arg,
259        })
260        .collect()
261}
262
263fn print_available_devices() {
264    println!("Available devices:");
265    println!("  CPU");
266
267    let metal = ferrox_metal::MetalProfile::detect();
268    if let Some(name) = metal.device_name {
269        println!("  Metal: {name}");
270    }
271
272    let cuda = ferrox_cuda::HardwareProfile::detect();
273    if cuda.cuda_available {
274        let name = cuda.cuda_device_name.as_deref().unwrap_or("unknown device");
275        println!("  CUDA: {name}");
276        if cuda.cuda_device_count > 1 {
277            println!("        ({} devices detected)", cuda.cuda_device_count);
278        }
279    }
280}
281
282fn cli_bind_addr(args: &ServerArgs, env_addr: Option<&str>) -> Option<String> {
283    if args.host.is_none() && args.port.is_none() {
284        return None;
285    }
286
287    let existing = env_addr.and_then(|value| value.parse::<SocketAddr>().ok());
288    let host = args
289        .host
290        .or_else(|| existing.map(|addr| addr.ip()))
291        .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST));
292    let port = args
293        .port
294        .or_else(|| existing.map(|addr| addr.port()))
295        .unwrap_or(8383);
296    Some(SocketAddr::new(host, port).to_string())
297}
298
299fn apply_cli_overrides(args: &ServerArgs) -> anyhow::Result<()> {
300    if let Some(model) = &args.model {
301        // SAFETY: called before the runtime starts worker threads.
302        unsafe { std::env::set_var("FERROX_MODEL_PATH", model) };
303    }
304
305    if let Some(addr) = cli_bind_addr(args, std::env::var("FERROX_ADDR").ok().as_deref()) {
306        // SAFETY: called before the runtime starts worker threads.
307        unsafe { std::env::set_var("FERROX_ADDR", addr) };
308    }
309
310    if let Some(threads) = args.threads {
311        if threads == 0 {
312            anyhow::bail!("--threads must be greater than zero");
313        }
314        // SAFETY: called before the runtime starts worker threads.
315        unsafe {
316            std::env::set_var("FERROX_CPU_THREADS", threads.to_string());
317            std::env::set_var("RAYON_NUM_THREADS", threads.to_string());
318        }
319    }
320
321    if args.device.is_none() && args.n_gpu_layers.is_none() {
322        // device overrides skipped
323    } else {
324        let layers = args.n_gpu_layers.unwrap_or(GpuLayers::Auto);
325        let device = if layers.offload_enabled() {
326            args.device.unwrap_or(OffloadDevice::Auto)
327        } else {
328            OffloadDevice::None
329        };
330
331        match device {
332            OffloadDevice::None | OffloadDevice::Cpu => unsafe {
333                std::env::set_var("FERROX_METAL", "0");
334                std::env::set_var("FERROX_METAL_ATTN", "0");
335                std::env::set_var("FERROX_CUDA", "0");
336            },
337            OffloadDevice::Auto => unsafe {
338                std::env::set_var("FERROX_METAL", "auto");
339                std::env::set_var("FERROX_CUDA", "auto");
340                if std::env::var_os("FERROX_METAL_ATTN").is_none() {
341                    std::env::set_var("FERROX_METAL_ATTN", "1");
342                }
343            },
344            OffloadDevice::Metal => {
345                #[cfg(not(feature = "metal"))]
346                {
347                    anyhow::bail!(
348                        "Metal requested but this binary was built without --features metal"
349                    );
350                }
351                #[cfg(feature = "metal")]
352                {
353                    if !ferrox_metal::MetalProfile::detect().available {
354                        anyhow::bail!("Metal requested but no Metal device is available");
355                    }
356                    unsafe {
357                        std::env::set_var("FERROX_METAL", "1");
358                        if std::env::var_os("FERROX_METAL_ATTN").is_none() {
359                            std::env::set_var("FERROX_METAL_ATTN", "1");
360                        }
361                        std::env::set_var("FERROX_CUDA", "0");
362                    }
363                }
364            }
365            OffloadDevice::Cuda => {
366                #[cfg(not(feature = "cuda"))]
367                {
368                    anyhow::bail!(
369                        "CUDA requested but this binary was built without --features cuda"
370                    );
371                }
372                #[cfg(feature = "cuda")]
373                {
374                    if !ferrox_cuda::HardwareProfile::detect().cuda_available {
375                        anyhow::bail!("CUDA requested but no CUDA device is available");
376                    }
377                    unsafe {
378                        std::env::set_var("FERROX_CUDA", "1");
379                        std::env::set_var("FERROX_METAL", "0");
380                        std::env::set_var("FERROX_METAL_ATTN", "0");
381                    }
382                }
383            }
384        }
385    }
386
387    Ok(())
388}
389
390/// The loaded model: immutable once built, so it needs no lock at all --
391/// just cheap `Arc` sharing across concurrent request tasks. Two real
392/// checkpoint shapes exist (see `model::LoadedModel`'s doc comment for
393/// why `FERROX_MODEL_PATH` picks between them); everything that isn't
394/// engine-specific (chat template, tokenizer kind reporting, whether
395/// this is the synthetic demo) goes through the small inherent methods
396/// below rather than being matched on ad hoc at every call site.
397#[allow(clippy::large_enum_variant)] // KimiEngine/MlaEngine dwarf Arc<Decoder>; boxing would churn call sites
398pub(crate) enum Model {
399    Gguf(GgufModel),
400    Kimi(KimiModel),
401    Mla(MlaModel),
402    Gemma4(Gemma4Model),
403    Glm52(Glm52Model),
404}
405
406pub(crate) struct GgufModel {
407    decoder: Arc<Decoder>,
408    tokenizer: Arc<ServerTokenizer>,
409    stop_tokens: StopTokens,
410    bos_id: Option<usize>,
411    is_synthetic: bool,
412    chat_template: chat_template::PromptTemplate,
413}
414
415pub(crate) struct KimiModel {
416    engine: KimiEngine,
417    tokenizer: KimiTokenizer,
418    stop_tokens: StopTokens,
419    chat_template: chat_template::PromptTemplate,
420}
421
422pub(crate) struct MlaModel {
423    engine: MlaEngine,
424    tokenizer: ServerTokenizer,
425    stop_tokens: StopTokens,
426    bos_id: Option<usize>,
427    name: String,
428    chat_template: chat_template::PromptTemplate,
429}
430
431pub(crate) struct Gemma4Model {
432    engine: Gemma4Engine,
433    tokenizer: ServerTokenizer,
434    stop_tokens: StopTokens,
435    bos_id: Option<usize>,
436    name: String,
437    chat_template: chat_template::PromptTemplate,
438}
439
440pub(crate) struct Glm52Model {
441    engine: ferrox_models::Glm52Engine,
442    tokenizer: ServerTokenizer,
443    stop_tokens: StopTokens,
444    bos_id: Option<usize>,
445    name: String,
446    chat_template: chat_template::PromptTemplate,
447}
448
449impl Model {
450    pub(crate) fn chat_template(&self) -> chat_template::PromptTemplate {
451        match self {
452            Model::Gguf(m) => m.chat_template.clone(),
453            Model::Kimi(m) => m.chat_template.clone(),
454            Model::Mla(m) => m.chat_template.clone(),
455            Model::Gemma4(m) => m.chat_template.clone(),
456            Model::Glm52(m) => m.chat_template.clone(),
457        }
458    }
459
460    /// Kimi K3 / MLA / GLM-5.2 have no synthetic-weight demo path through this
461    /// server (unlike GGUF, which falls back to one when
462    /// `FERROX_MODEL_PATH` is unset) -- a loaded `Model::Kimi` /
463    /// `Model::Mla` / `Model::Glm52` is always a real checkpoint.
464    fn is_synthetic(&self) -> bool {
465        match self {
466            Model::Gguf(m) => m.is_synthetic,
467            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => false,
468        }
469    }
470
471    fn tokenizer_kind(&self) -> &'static str {
472        match self {
473            Model::Gguf(m) => m.tokenizer.kind(),
474            Model::Kimi(_) => "kimi-tiktoken-bpe",
475            Model::Mla(m) => m.tokenizer.kind(),
476            Model::Gemma4(m) => m.tokenizer.kind(),
477            Model::Glm52(m) => m.tokenizer.kind(),
478        }
479    }
480
481    /// Live counters of the bounded expert cache, when the model
482    /// streams routed experts (`FERROX_EXPERT_CACHE_BYTES`); `None`
483    /// for fully resident models.
484    fn expert_store_stats(&self) -> Option<ferrox_core::expert_store::ExpertStoreStats> {
485        match self {
486            Model::Gguf(m) => m.decoder.expert_store_stats(),
487            Model::Kimi(m) => m.engine.weights.expert_store_stats(),
488            Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
489        }
490    }
491
492    pub(crate) fn name(&self) -> &str {
493        match self {
494            Model::Gguf(m) => m.decoder.config.name,
495            Model::Kimi(_) => "kimi-k3",
496            Model::Mla(m) => m.name.as_str(),
497            Model::Gemma4(m) => m.name.as_str(),
498            Model::Glm52(m) => m.name.as_str(),
499        }
500    }
501
502    pub(crate) fn encode(&self, text: &str) -> Vec<usize> {
503        match self {
504            Model::Gguf(m) => m.tokenizer.encode(text),
505            Model::Kimi(m) => m
506                .tokenizer
507                .encode(text)
508                .into_iter()
509                .map(|id| id as usize)
510                .collect(),
511            Model::Mla(m) => m.tokenizer.encode(text),
512            Model::Gemma4(m) => m.tokenizer.encode(text),
513            Model::Glm52(m) => m.tokenizer.encode(text),
514        }
515    }
516
517    pub(crate) fn decode(&self, ids: &[usize]) -> String {
518        match self {
519            Model::Gguf(m) => m.tokenizer.decode(ids),
520            Model::Kimi(m) => {
521                let ids32: Vec<u32> = ids.iter().map(|&id| id as u32).collect();
522                m.tokenizer.decode(&ids32)
523            }
524            Model::Mla(m) => m.tokenizer.decode(ids),
525            Model::Gemma4(m) => m.tokenizer.decode(ids),
526            Model::Glm52(m) => m.tokenizer.decode(ids),
527        }
528    }
529
530    /// Final-normed last-layer hidden states for GGUF Decoder only.
531    /// Returns `None` for engines without a hidden-state hook (e.g. Kimi/MLA/GLM).
532    pub(crate) fn embed_tokens(&self, tokens: &[usize]) -> Option<Vec<Vec<f32>>> {
533        match self {
534            Model::Gguf(m) => {
535                let mut caches: Vec<_> = (0..m.decoder.layers.len())
536                    .map(|_| {
537                        ferrox_core::cache::KvCache::new(
538                            m.decoder.config.n_kv_heads,
539                            m.decoder.config.head_dim,
540                        )
541                    })
542                    .collect();
543                Some(m.decoder.forward_hidden_batch(tokens, 0, &mut caches))
544            }
545            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
546        }
547    }
548
549    pub(crate) fn vocab_size(&self) -> Option<usize> {
550        match self {
551            Model::Gguf(m) => Some(m.decoder.config.vocab_size),
552            Model::Kimi(m) => Some(m.tokenizer.vocab_size()),
553            Model::Mla(m) => Some(ferrox_models::Engine::vocab_size(&m.engine)),
554            Model::Gemma4(m) => Some(ferrox_models::Engine::vocab_size(&m.engine)),
555            Model::Glm52(m) => Some(ferrox_models::Engine::vocab_size(&m.engine)),
556        }
557    }
558}
559
560/// The model the server is serving *right now*, together with the
561/// pieces that are built from it and must be replaced with it.
562///
563/// The continuous batcher owns a worker thread holding an
564/// `Arc<Decoder>`, so it belongs to one specific model: keeping it in a
565/// separate field would let a swap leave a batcher decoding against the
566/// old weights while `Model` named the new ones. Bundling them means
567/// one `Arc` swap replaces a consistent pair.
568pub(crate) struct ActiveModel {
569    /// Admin-surface id (see `admin::discover`), or `None` for a model
570    /// that was not discovered through it -- the synthetic fallback, or
571    /// a `FERROX_MODEL_PATH` outside the scanned directory.
572    pub(crate) id: Option<String>,
573    pub(crate) model: Arc<Model>,
574    /// Opt-in continuous-batching decode worker (`FERROX_CONTINUOUS_BATCHING=1`).
575    /// Shares `forward_multi_seq` across concurrent GGUF requests. Disabled
576    /// when a KV pool or prefix cache is configured (those keep the
577    /// private-loop `generate` path).
578    pub(crate) batcher: Option<serving::batch::ContinuousBatcher>,
579    /// The per-request context ceiling this model was priced for, or
580    /// `None` when it could not be priced (see `crate::budget`).
581    ///
582    /// Lives on the *model* rather than on `AppState` because it is a
583    /// property of the checkpoint plus the machine: `/admin/models/load`
584    /// swapping in a different model must swap in its ceiling too,
585    /// never keep the old model's arithmetic. The same `Arc` is inside
586    /// this model's `batcher`, so the batched and private decode paths
587    /// admit on one object.
588    pub(crate) ceiling: Option<Arc<budget::ContextCeiling>>,
589}
590
591pub(crate) struct AppState {
592    /// The swappable active model.
593    ///
594    /// **A reader clones the `Arc` under the read lock and then runs;
595    /// the lock is never held across a decode.** That is the whole
596    /// design: `RwLock` guards the *pointer*, not the model, so
597    /// `/admin/models/load` swapping in a new `Arc` cannot stall a
598    /// request that is already generating, and a request that started
599    /// against the old model keeps decoding against the exact weights
600    /// it began with until it finishes -- the old `ActiveModel` (and
601    /// its batcher thread) is dropped only when the last in-flight
602    /// holder releases it, not when the swap happens. Requests that
603    /// arrive after the swap see the new model. There is deliberately
604    /// no attempt to migrate an in-flight request: half a completion
605    /// from one checkpoint and half from another is worse than either.
606    ///
607    /// `None` means nothing is loaded (after `/admin/models/unload`, or
608    /// a failed startup load): generation endpoints answer 503 rather
609    /// than pretending, and `/health` reports `unavailable`.
610    active: std::sync::RwLock<Option<Arc<ActiveModel>>>,
611    /// Set while a load task is in flight, so a second load request is
612    /// rejected instead of racing the first. A load is not cheap and
613    /// two concurrent ones would fight for the same memory.
614    pub(crate) load_in_progress: std::sync::atomic::AtomicBool,
615    /// Long-running jobs (download, load) -- see the `tasks` module.
616    pub(crate) tasks: Arc<tasks::TaskRegistry>,
617    /// Generations that can currently be stopped by `POST /v1/cancel`
618    /// -- see the `cancel` module for why a dropped socket alone is not
619    /// enough.
620    pub(crate) cancels: Arc<cancel::CancelRegistry>,
621    /// Recent-request ring buffer and the counters behind
622    /// `/admin/stats` -- see the `stats` module.
623    pub(crate) stats: stats::Stats,
624    /// Replay buffers for streams started with `stream_resumable`.
625    /// See the `resume` module.
626    pub(crate) streams: resume::StreamRegistry,
627    /// The directory `/admin/models` scans, when one is configured.
628    pub(crate) model_dir: Option<PathBuf>,
629    /// The only shared *mutable* state in the server. Locked only for
630    /// the brief get/put around a cache lookup, never held across a
631    /// decode -- see the module doc comment.
632    response_cache: Mutex<ResponseCache>,
633    /// `Some` when `FERROX_KV_POOL_BLOCKS`/`FERROX_KV_POOL_BLOCK_SIZE`
634    /// are set: every request's per-layer KV caches then draw from
635    /// this one shared, bounded pool instead of each growing
636    /// unboundedly. A request whose caches can't get their first block
637    /// retries for up to `FERROX_KV_POOL_QUEUE_TIMEOUT_MS` (zero by
638    /// default -- reject immediately) before being rejected with 503,
639    /// rather than being admitted regardless of how many other
640    /// requests are already decoding -- see
641    /// `ferrox_core::cache::KvBlockPool` and `generate::KvPoolConfig`.
642    /// `None` (the default) preserves the
643    /// original unbounded-per-request behavior exactly.
644    pub(crate) kv_pool: Option<generate::KvPoolConfig>,
645    /// `Some` when `FERROX_PAGED_KV_BLOCKS` is set: per-layer paged KV
646    /// storage every request draws pages from, rather than each request
647    /// owning a private contiguous buffer.
648    ///
649    /// Mutually exclusive with BOTH `kv_pool` and `prefix_cache`, and
650    /// refused at startup rather than silently preferred. Against
651    /// `kv_pool` because they are two answers to the same question.
652    /// Against `prefix_cache` because `PrefixCache` stores
653    /// `Vec<KvCache>` snapshots, which a paged request has none of, so
654    /// enabling both would give a cache that can never hit -- see
655    /// `wire-radix-prefix-cache` in the plan, which is what removes
656    /// that restriction.
657    pub(crate) paged_kv: Option<generate::PagedKvConfig>,
658    /// `Some` when `FERROX_PREFIX_CACHE_ENTRIES` is set: a shared,
659    /// LRU-bounded store of previously processed prompt+KV-state
660    /// snapshots (see `ferrox_models::PrefixCache`), consulted so a
661    /// request that *extends* an earlier one -- the common multi-turn-
662    /// chat case -- can skip recomputing the shared part. Mutually
663    /// exclusive with `kv_pool` (see `generate::generate`'s doc
664    /// comment for why); `None` (the default) means every request
665    /// processes its full prompt from scratch, exactly as before this
666    /// existed.
667    pub(crate) prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
668    /// Server-side per-session conversation history -- see
669    /// `session::SessionStore`'s doc comment.
670    /// Always present (unlike `kv_pool`/`prefix_cache`, it's not
671    /// opt-in): a request that never sends `session_id` simply never
672    /// touches it, at negligible cost (one empty `HashMap`).
673    sessions: session::SessionStore,
674    requests_total: std::sync::atomic::AtomicU64,
675    request_errors_total: std::sync::atomic::AtomicU64,
676    started_at: std::time::Instant,
677    /// Milliseconds after `started_at` at which the last request
678    /// finished; 0 means none has. Reported by `/health` as an age, so a
679    /// client that sees a slow health poll from a GPU-saturated server
680    /// has positive evidence of liveness instead of declaring it dead.
681    last_request_ms: std::sync::atomic::AtomicU64,
682    /// Backend capability probe behind `/health` (see `health` module).
683    detection: Arc<health::Detection>,
684    /// Loaded MCP config (`--mcp-config`); tool invocation not wired yet.
685    mcp: Option<mcp::LoadedMcpConfig>,
686    /// Whether a swapped-in GGUF model should get a continuous-batching
687    /// worker, decided once at startup from the same env var and
688    /// exclusions as the initial load.
689    pub(crate) continuous_batching_enabled: bool,
690    /// The model id a load task is currently working on, so
691    /// `/admin/models` can report `loading` for it. Separate from
692    /// `load_in_progress` because that is a gate and this is a label.
693    loading_model: Mutex<Option<String>>,
694    /// The last failed load, as `(model id, message)`. Sticky until the
695    /// next successful load so `/admin/models` can say *why* an entry
696    /// is in `error` without the user retrying to find out.
697    last_load_error: Mutex<Option<(String, String)>>,
698    /// Live serving counters and the two sliding-window rates behind
699    /// `/v1/stats` -- see `crate::stats::ServingStats`. Distinct from
700    /// `stats`, which is the historical ring: this is what is happening
701    /// *now*, and it decays to zero when nothing is.
702    pub(crate) serving: Mutex<crate::stats::ServingStats>,
703    /// The gate every request, cache rebuild and shutdown passes
704    /// through -- see `crate::policy::maintenance::MaintenanceGate`. Held across none
705    /// of them: each operation takes it, reads or moves the state, and
706    /// releases before doing any work.
707    pub(crate) maintenance: Mutex<crate::policy::maintenance::MaintenanceGate>,
708    /// The live memory reading behind `/v1/stats`, re-probed at most
709    /// once per [`FOOTPRINT_TTL_MS`] -- see
710    /// `cache_admin::footprint_json`. A `Mutex` and not an atomic
711    /// because holding it across the probe is what collapses concurrent
712    /// pollers onto ONE VMA walk.
713    pub(crate) footprint:
714        Mutex<crate::policy::footprint::ProbeCache<crate::policy::footprint::Footprint>>,
715    /// Wall-clock second this process started serving.
716    ///
717    /// Distinct from `started_at`, which is an `Instant` and has no
718    /// wall clock at all. This exists so an accounting receipt's id can
719    /// be derived from something stable for the life of THIS process
720    /// and different in the next one: a pid alone is reused across
721    /// restarts, and a restarted engine reusing a previous
722    /// generation's receipt id would have its own receipt silently
723    /// skipped as already written.
724    pub(crate) started_unix: u64,
725}
726
727/// How long a memory reading is served before it is taken again.
728///
729/// Two seconds: long enough that a dashboard polling once a second
730/// costs one probe rather than one per poll, short enough that an
731/// operator watching a load ramp sees it move.
732pub(crate) const FOOTPRINT_TTL_MS: u64 = 2_000;
733
734impl AppState {
735    /// Clones the active model's `Arc` and releases the lock before
736    /// returning. Every caller then runs against its own handle, so no
737    /// decode ever holds this lock -- see [`AppState::active`].
738    pub(crate) fn active(&self) -> Option<Arc<ActiveModel>> {
739        self.active
740            .read()
741            .unwrap_or_else(|p| p.into_inner())
742            .clone()
743    }
744
745    /// [`AppState::active`] for a request that cannot proceed without a
746    /// model. 503 with a `Retry-After`-shaped explanation is the honest
747    /// answer while nothing is loaded; the alternative -- keeping a
748    /// stale model around so the endpoint never fails -- would serve
749    /// tokens from a checkpoint the operator explicitly unloaded.
750    pub(crate) fn require_active(&self) -> Result<Arc<ActiveModel>, ApiError> {
751        self.active().ok_or_else(|| {
752            (
753                StatusCode::SERVICE_UNAVAILABLE,
754                Json(serde_json::json!({"error": {
755                    "message": "no model is loaded; POST /admin/models/load with an id from \
756                                GET /admin/models",
757                    "type": "model_not_loaded"
758                }})),
759            )
760        })
761    }
762
763    /// [`AppState::active`]'s model only, for the many call sites that
764    /// do not care about the batcher.
765    pub(crate) fn require_model(&self) -> Result<Arc<Model>, ApiError> {
766        Ok(Arc::clone(&self.require_active()?.model))
767    }
768
769    /// Publishes a new active model (or `None` to unload) and returns
770    /// the previous one.
771    ///
772    /// The write lock is held only for the pointer swap. The returned
773    /// value is the caller's to drop *outside* the lock: dropping a
774    /// multi-gigabyte model can take a moment, and doing it under the
775    /// lock would block every reader for exactly as long.
776    pub(crate) fn swap_active(&self, next: Option<Arc<ActiveModel>>) -> Option<Arc<ActiveModel>> {
777        let mut guard = self.active.write().unwrap_or_else(|p| p.into_inner());
778        std::mem::replace(&mut *guard, next)
779    }
780
781    /// Stamps "a request just finished" for `/health`'s liveness
782    /// vouching. Relaxed: this is a freshness hint, not a
783    /// synchronization point.
784    fn mark_request_finished(&self) {
785        let ms = self.started_at.elapsed().as_millis().min(u64::MAX as u128) as u64;
786        self.last_request_ms
787            .store(ms, std::sync::atomic::Ordering::Relaxed);
788    }
789
790    pub(crate) fn uptime(&self) -> Duration {
791        self.started_at.elapsed()
792    }
793
794    pub(crate) fn requests_total(&self) -> u64 {
795        self.requests_total
796            .load(std::sync::atomic::Ordering::Relaxed)
797    }
798
799    pub(crate) fn errors_total(&self) -> u64 {
800        self.request_errors_total
801            .load(std::sync::atomic::Ordering::Relaxed)
802    }
803
804    pub(crate) fn cache_stats(&self) -> response_cache::CacheStats {
805        lock_cache(&self.response_cache).stats()
806    }
807
808    /// Seconds since the last request finished, or `None` when none
809    /// has. Same derivation `/health` uses, so the two agree.
810    pub(crate) fn last_request_age_seconds(&self) -> Option<f64> {
811        let last = self
812            .last_request_ms
813            .load(std::sync::atomic::Ordering::Relaxed);
814        (last > 0)
815            .then(|| self.uptime().as_secs_f64() - (last as f64 / 1000.0))
816            .map(|age| age.max(0.0))
817    }
818
819    pub(crate) fn loading_model_id(&self) -> Option<String> {
820        self.loading_model
821            .lock()
822            .unwrap_or_else(|p| p.into_inner())
823            .clone()
824    }
825
826    pub(crate) fn set_loading_model(&self, id: Option<String>) {
827        *self.loading_model.lock().unwrap_or_else(|p| p.into_inner()) = id;
828    }
829
830    pub(crate) fn last_load_error(&self) -> Option<(String, String)> {
831        self.last_load_error
832            .lock()
833            .unwrap_or_else(|p| p.into_inner())
834            .clone()
835    }
836
837    pub(crate) fn set_last_load_error(&self, error: Option<(String, String)>) {
838        *self
839            .last_load_error
840            .lock()
841            .unwrap_or_else(|p| p.into_inner()) = error;
842    }
843
844    /// Records one finished request in the `/admin/stats` ring buffer.
845    ///
846    /// `attribution` is threaded from the request's own headers rather
847    /// than looked up here: by the time a generation task finishes, the
848    /// request parts are long gone, and reconstructing "who was that"
849    /// afterwards is exactly the guessing the monitor exists to avoid.
850    /// The model that would serve a request right now, as `/v1/models`
851    /// names it. `None` when nothing is loaded.
852    pub(crate) fn active_model_name(&self) -> Option<String> {
853        self.active().map(|a| a.model.name().to_string())
854    }
855
856    pub(crate) fn record_request(&self, record: stats::Record<'_>) {
857        self.stats.record(stats::entry(record));
858    }
859}
860
861/// Defense in depth: if a panic ever happened while this lock was held
862/// (none of the CPU-bound decode work runs under it, so this should be
863/// very unlikely), recovering the inner state on poison rather than
864/// `.unwrap()`ing keeps the cache from permanently bricking the server.
865fn lock_cache(cache: &Mutex<ResponseCache>) -> MutexGuard<'_, ResponseCache> {
866    cache
867        .lock()
868        .unwrap_or_else(|poisoned| poisoned.into_inner())
869}
870
871#[derive(Debug, Clone, Deserialize)]
872#[serde(untagged)]
873pub(crate) enum MessageContent {
874    Text(String),
875    Parts(Vec<ContentPart>),
876}
877
878#[derive(Debug, Clone, Deserialize)]
879struct ContentPart {
880    #[serde(rename = "type")]
881    kind: String,
882    #[serde(default)]
883    text: Option<String>,
884    #[serde(default)]
885    image_url: Option<serde_json::Value>,
886}
887
888impl MessageContent {
889    fn as_text(&self) -> String {
890        match self {
891            Self::Text(s) => s.clone(),
892            Self::Parts(parts) => parts
893                .iter()
894                .filter_map(|p| p.text.as_deref())
895                .collect::<Vec<_>>()
896                .join(""),
897        }
898    }
899
900    fn has_image(&self) -> bool {
901        match self {
902            Self::Text(_) => false,
903            Self::Parts(parts) => parts
904                .iter()
905                .any(|p| p.kind == "image_url" || p.image_url.is_some()),
906        }
907    }
908}
909
910#[derive(Debug, Clone, Deserialize)]
911pub(crate) struct ChatMessage {
912    pub(crate) role: String,
913    /// `None` for an assistant message that made tool calls instead of
914    /// replying with text (the real OpenAI convention: `content` and
915    /// `tool_calls` are mutually exclusive on an assistant message).
916    #[serde(default)]
917    pub(crate) content: Option<MessageContent>,
918    /// Present on a replayed assistant message that previously made
919    /// one or more tool calls (conversation history a client sends
920    /// back on a follow-up request).
921    #[serde(default)]
922    pub(crate) tool_calls: Option<Vec<ToolCallIn>>,
923    /// Present on a `"tool"`-role message carrying a call's result
924    /// (unused by rendering today -- `role` alone already
925    /// distinguishes it -- but accepted so real OpenAI-shaped tool-
926    /// result messages deserialize without error).
927    #[serde(default)]
928    #[allow(dead_code)]
929    pub(crate) tool_call_id: Option<String>,
930    /// A replayed assistant turn's chain of thought, kept out of
931    /// `content` on the way in and handed back to the template on the
932    /// way out.
933    ///
934    /// It has to be a field of its own rather than prose folded into
935    /// `content`, because a template that knows about reasoning wraps
936    /// it in the family's own markers -- and a template that does not
937    /// must be able to drop it. Concatenating it into `content` would
938    /// show a model its own scratchpad as if it had said it out loud,
939    /// which is exactly what the markers exist to prevent.
940    ///
941    /// Accepted under both spellings clients use: `reasoning_content`
942    /// (the vLLM/DeepSeek convention ferrox emits) and `reasoning`
943    /// (what the OpenAI Responses and Anthropic surfaces call it), so a
944    /// client can replay a turn shaped the way it received it.
945    #[serde(default, alias = "reasoning")]
946    pub(crate) reasoning_content: Option<String>,
947}
948
949impl ChatMessage {
950    /// The text this message actually contributes to a rendered
951    /// prompt: `content` verbatim for an ordinary message, or (for a
952    /// replayed assistant message carrying `tool_calls`) each call
953    /// re-rendered as the same `<tool_call>{...}</tool_call>` marker
954    /// text a model is asked to produce for a *new* call -- see
955    /// `chat_template`'s module doc comment for why.
956    fn rendered_content(&self) -> String {
957        let mut out = self
958            .content
959            .as_ref()
960            .map(MessageContent::as_text)
961            .unwrap_or_default();
962        if let Some(calls) = &self.tool_calls {
963            for call in calls {
964                out.push_str(&format!(
965                    "<tool_call>{{\"name\": \"{}\", \"arguments\": {}}}</tool_call>",
966                    call.function.name, call.function.arguments
967                ));
968            }
969        }
970        out
971    }
972}
973
974#[derive(Debug, Clone, Deserialize)]
975pub(crate) struct ToolCallIn {
976    #[serde(default)]
977    #[allow(dead_code)]
978    id: String,
979    #[serde(rename = "type", default)]
980    #[allow(dead_code)]
981    kind: String,
982    function: ToolCallFunctionIn,
983}
984
985#[derive(Debug, Clone, Deserialize)]
986struct ToolCallFunctionIn {
987    name: String,
988    /// A JSON-encoded string (the real OpenAI convention for
989    /// `tool_calls[].function.arguments`), not a nested object --
990    /// spliced directly into the re-rendered `<tool_call>{...}` marker
991    /// text since it's already valid JSON.
992    arguments: String,
993}
994
995/// A tool definition in the real OpenAI request shape:
996/// `{"type": "function", "function": {"name", "description", "parameters"}}`.
997#[derive(Debug, Clone, Deserialize)]
998struct ToolDef {
999    #[serde(rename = "type", default)]
1000    #[allow(dead_code)]
1001    kind: String,
1002    function: ToolFunctionDef,
1003}
1004
1005#[derive(Debug, Clone, Deserialize)]
1006struct ToolFunctionDef {
1007    name: String,
1008    #[serde(default)]
1009    description: Option<String>,
1010    #[serde(default)]
1011    parameters: Option<serde_json::Value>,
1012}
1013
1014/// OpenAI's `tool_choice`: `"auto"`/`"none"`/`"required"`, or an object
1015/// pinning one specific function. Only whether it's literally
1016/// `"none"` is actually consulted (to suppress tool-calling prompting
1017/// entirely) -- forcing a *specific* named call isn't implementable
1018/// honestly without grammar-constrained decoding (which doesn't exist
1019/// in this server), so `"required"` and a
1020/// specific-function choice are both treated the same as `"auto"`:
1021/// offered, not forced. A real, disclosed simplification, not silently
1022/// wrong behavior.
1023#[derive(Debug, Clone, Deserialize)]
1024#[serde(untagged)]
1025enum ToolChoice {
1026    Mode(String),
1027    #[allow(dead_code)]
1028    Specific(serde_json::Value),
1029}
1030
1031/// OpenAI's `stop` field accepts either a single string or an array of
1032/// strings.
1033#[derive(Deserialize)]
1034#[serde(untagged)]
1035enum StopParam {
1036    One(String),
1037    Many(Vec<String>),
1038}
1039
1040#[derive(Deserialize)]
1041struct ChatCompletionRequest {
1042    model: String,
1043    messages: Vec<ChatMessage>,
1044    #[serde(default = "default_max_tokens")]
1045    max_tokens: usize,
1046    #[serde(default)]
1047    temperature: Option<f32>,
1048    #[serde(default)]
1049    top_p: Option<f32>,
1050    #[serde(default)]
1051    top_k: Option<usize>,
1052    #[serde(default)]
1053    repetition_penalty: Option<f32>,
1054    #[serde(default)]
1055    seed: Option<u64>,
1056    #[serde(default)]
1057    stop: Option<StopParam>,
1058    #[serde(default)]
1059    stream: Option<bool>,
1060    /// Ferrox extension. `true` asks the server to keep a replay buffer
1061    /// for this stream so a dropped connection can be resumed from the
1062    /// last `id:` seen, or drained over the JSON polling fallback.
1063    ///
1064    /// It also changes what a dropped socket *means*. Without it, the
1065    /// connection closing cancels the generation (see the `cancel`
1066    /// module). With it, the generation keeps running into the replay
1067    /// buffer -- which is the entire point, and the reason this is the
1068    /// caller's decision rather than the server's: a tab that navigated
1069    /// away wants the CPU back, and a tab whose proxy dropped a
1070    /// 90-second answer wants the answer. `POST /v1/cancel` stops a
1071    /// resumable stream either way.
1072    #[serde(default)]
1073    stream_resumable: Option<bool>,
1074    /// Run past the model's own end-of-generation tokens, so this
1075    /// request produces exactly `max_tokens`.
1076    ///
1077    /// A serving-benchmark knob, and the vLLM/SGLang spelling of it. It
1078    /// exists because a benchmark whose requests stop at their own EOS
1079    /// finishes them at different lengths, and the slowest percentile
1080    /// is then whichever request happened to be asked for the most
1081    /// tokens -- a fact about the prompts, reported as a fact about the
1082    /// server. It does NOT withdraw the caller's own `stop` strings.
1083    #[serde(default)]
1084    ignore_eos: Option<bool>,
1085    #[serde(default)]
1086    tools: Vec<ToolDef>,
1087    #[serde(default)]
1088    tool_choice: Option<ToolChoice>,
1089    /// The OpenAI extension every reasoning-model deployment actually
1090    /// uses: whatever is in here becomes a top-level variable in the
1091    /// checkpoint's own chat template, which is how `enable_thinking`
1092    /// (Qwen3, gemma-4), `thinking` (DeepSeek) and `reasoning_effort`
1093    /// are really driven. Values here can never shadow the structural
1094    /// variables (`messages`, `tools`, `add_generation_prompt`) -- see
1095    /// `ferrox_models::chat_template::RenderOptions`.
1096    #[serde(default)]
1097    chat_template_kwargs: Option<serde_json::Map<String, serde_json::Value>>,
1098    /// OpenAI's own spelling of the same knob. It is folded into
1099    /// `chat_template_kwargs` before rendering, and loses to an explicit
1100    /// entry there: a caller who wrote both meant the specific one.
1101    ///
1102    /// `"none"` and `"off"` are not gears -- they mean *do not think*,
1103    /// and are handled by [`ChatCompletionRequest::thinking_direction`]
1104    /// before any quantization can round them onto a real one.
1105    #[serde(default)]
1106    reasoning_effort: Option<String>,
1107    /// The DeepSeek wire's thinking switch: `{"type": "enabled"}` or
1108    /// `{"type": "disabled"}`. It decides the direction outright, and
1109    /// `disabled` beats any effort the same request also carries.
1110    #[serde(default)]
1111    thinking: Option<ThinkingSwitch>,
1112    /// Server-side conversation history key (see the `session`
1113    /// module): when set, `messages` is treated as
1114    /// *only the new turn(s)* to append to this session's stored
1115    /// history, not the whole conversation.
1116    #[serde(default)]
1117    session_id: Option<String>,
1118    /// OpenAI fields we explicitly reject rather than silently ignore.
1119    #[serde(default)]
1120    logprobs: Option<bool>,
1121    #[serde(default)]
1122    top_logprobs: Option<u32>,
1123    #[serde(default)]
1124    n: Option<u32>,
1125    #[serde(default)]
1126    presence_penalty: Option<f32>,
1127    #[serde(default)]
1128    frequency_penalty: Option<f32>,
1129    #[serde(default)]
1130    response_format: Option<serde_json::Value>,
1131}
1132
1133/// The output budget a chat request gets when it names none.
1134///
1135/// Not OpenAI's legacy 16 -- that floor belongs to `/v1/completions`,
1136/// where a caller asking for a completion of a fragment usually wants a
1137/// fragment back. A chat client that omits `max_tokens` wants an
1138/// answer, and 16 tokens of one reads as a truncated server.
1139///
1140/// It is safe to be this large only because the context ceiling CLAMPS
1141/// rather than refuses (see `generate`): a request whose prompt leaves
1142/// less than this much room is served with what remains, not rejected
1143/// over a number the caller never set.
1144const DEFAULT_CHAT_MAX_TOKENS: usize = 32_768;
1145
1146/// The DeepSeek-wire thinking switch.
1147#[derive(Debug, Clone, Deserialize)]
1148pub(crate) struct ThinkingSwitch {
1149    #[serde(rename = "type")]
1150    pub(crate) kind: String,
1151}
1152
1153/// Every spelling a caller can use to steer the template's thinking
1154/// themselves. If any of these is already present in
1155/// `chat_template_kwargs`, the protocol-level knobs stand down.
1156const THINKING_KWARG_KEYS: [&str; 4] = [
1157    "enable_thinking",
1158    "thinking",
1159    "thinking_mode",
1160    "reasoning_effort",
1161];
1162
1163/// The efforts that mean "do not think" rather than naming a gear.
1164/// Compared after trimming and lowercasing, because a client that sends
1165/// `"None"` means the same thing.
1166const DISABLE_EFFORTS: [&str; 2] = ["none", "off"];
1167
1168fn default_max_tokens() -> usize {
1169    DEFAULT_CHAT_MAX_TOKENS
1170}
1171
1172impl ChatCompletionRequest {
1173    fn sampling_params(&self) -> SamplingParams {
1174        SamplingParams {
1175            temperature: self.temperature.unwrap_or(0.0),
1176            top_p: self.top_p.unwrap_or(1.0),
1177            top_k: self.top_k.unwrap_or(0),
1178            repetition_penalty: self.repetition_penalty.unwrap_or(1.0),
1179            presence_penalty: self.presence_penalty.unwrap_or(0.0),
1180            frequency_penalty: self.frequency_penalty.unwrap_or(0.0),
1181        }
1182    }
1183
1184    fn stop_sequences(&self) -> Vec<String> {
1185        self.stop
1186            .as_ref()
1187            .map(|s| match s {
1188                StopParam::One(v) => vec![v.clone()],
1189                StopParam::Many(v) => v.clone(),
1190            })
1191            .unwrap_or_default()
1192    }
1193
1194    /// Real tool-calling is only offered when `tools` is non-empty AND
1195    /// the client hasn't explicitly disabled it via `tool_choice:
1196    /// "none"` -- see `ToolChoice`'s doc comment for what the other
1197    /// values do (nothing different from `"auto"`).
1198    fn tools_active(&self) -> bool {
1199        !self.tools.is_empty()
1200            && !matches!(&self.tool_choice, Some(ToolChoice::Mode(m)) if m == "none")
1201    }
1202
1203    /// The `chat_template_kwargs` this request actually renders with.
1204    ///
1205    /// Five rules, all of them from `ferrox-edge`:
1206    ///
1207    /// * **An explicit knob wins wholesale.** A caller who already set
1208    ///   any of `enable_thinking` / `thinking` / `thinking_mode` /
1209    ///   `reasoning_effort` inside `chat_template_kwargs` has said what
1210    ///   they want; the protocol-level knobs are then ignored entirely
1211    ///   rather than merged, because a merge would let a default
1212    ///   contradict an explicit request.
1213    /// * **`none` and `off` are not gears.** `reasoning_effort: "none"`
1214    ///   means *turn thinking off* and broadcasts the off pair; it must
1215    ///   not be quantized onto the nearest gear, which would turn "do
1216    ///   not think" into "think a little". Same for the DeepSeek-wire
1217    ///   `thinking: {"type": "disabled"}`, which beats any effort.
1218    ///
1219    /// * **Thinking follows the tools.** Offering tools turns thinking
1220    ///   on even when the caller said nothing, because some encoders
1221    ///   emit well-formed tool calls only in thinking mode
1222    ///   ([`crate::policy::effort::resolve_thinking_mode`]).
1223    /// * **Effort is quantized onto what this checkpoint grades.** A
1224    ///   template that accepts only the OpenAI triple must not be sent
1225    ///   `minimal`; it is mapped to the nearest gear, or dropped when no
1226    ///   gear is close enough, rather than interpolated verbatim into
1227    ///   the prompt ([`crate::policy::effort::sanitize_effort`], against the
1228    ///   profile probed at load).
1229    /// * **One value, every spelling.** The graded-strength dialect
1230    ///   reads `reasoning_strength`; a Jinja template ignores variables
1231    ///   it does not declare, so broadcasting costs nothing and removes
1232    ///   a per-family routing table
1233    ///   ([`crate::policy::effort::broadcast_effort_spellings`]).
1234    ///
1235    /// Every render path has to do this identically -- a request that
1236    /// validates against one prompt and generates from another is the
1237    /// failure this returns a single value to prevent.
1238    /// Which way this request steers thinking, before any template is
1239    /// consulted: `Some(false)` off, `Some(true)` on, `None` unstated.
1240    ///
1241    /// `thinking: {"type": …}` decides outright and `disabled` wins over
1242    /// any effort, because a client that sent both a switch and a gear
1243    /// meant the switch -- the gear is what it would use *if* thinking
1244    /// were on.
1245    fn thinking_direction(&self) -> Option<bool> {
1246        if let Some(switch) = &self.thinking {
1247            return match switch.kind.trim().to_ascii_lowercase().as_str() {
1248                "disabled" => Some(false),
1249                "enabled" => Some(true),
1250                // An unrecognized type is not a silent default -- see
1251                // `validate_supported_fields`, which rejects it.
1252                _ => None,
1253            };
1254        }
1255        let effort = self.reasoning_effort.as_ref()?;
1256        DISABLE_EFFORTS
1257            .contains(&effort.trim().to_ascii_lowercase().as_str())
1258            .then_some(false)
1259    }
1260
1261    fn resolve_template_kwargs(
1262        &self,
1263        template: &chat_template::PromptTemplate,
1264    ) -> serde_json::Map<String, serde_json::Value> {
1265        let mut kwargs = self.chat_template_kwargs.clone().unwrap_or_default();
1266        // Whether the caller steered the template themselves. Read
1267        // BEFORE anything is added, or every request looks explicit
1268        // from the second statement on.
1269        let caller_steered = THINKING_KWARG_KEYS.iter().any(|k| kwargs.contains_key(*k));
1270
1271        if !caller_steered {
1272            match self.thinking_direction() {
1273                Some(false) => {
1274                    for (k, v) in crate::policy::effort::thinking_off_kwargs() {
1275                        kwargs.insert(k, v);
1276                    }
1277                    // Nothing below applies: an effort would re-enter a
1278                    // block this request just closed.
1279                    return kwargs;
1280                }
1281                Some(true) => {
1282                    for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1283                        kwargs.insert(k, v);
1284                    }
1285                }
1286                None => {}
1287            }
1288            if let Some(effort) = &self.reasoning_effort {
1289                kwargs
1290                    .entry("reasoning_effort".to_string())
1291                    .or_insert_with(|| serde_json::json!(effort));
1292            }
1293        }
1294
1295        let offered: Vec<serde_json::Value> = if self.tools_active() {
1296            self.tools.iter().map(chat_template::tool_json).collect()
1297        } else {
1298            Vec::new()
1299        };
1300        let thinking = crate::policy::effort::resolve_thinking_mode(Some(&kwargs), Some(&offered));
1301        if thinking == crate::policy::effort::ThinkingMode::Thinking {
1302            for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1303                kwargs.entry(k).or_insert(v);
1304            }
1305        }
1306        match crate::policy::effort::sanitize_effort(&mut kwargs, template.efforts()) {
1307            crate::policy::effort::EffortMapping::Mapped(to) => {
1308                tracing::debug!("reasoning_effort quantized to {}", to.as_str());
1309            }
1310            crate::policy::effort::EffortMapping::Dropped => {
1311                tracing::debug!(
1312                    "reasoning_effort dropped: this checkpoint's template grades no gear close \
1313                     enough, so its own default applies"
1314                );
1315            }
1316            crate::policy::effort::EffortMapping::Unchanged => {}
1317        }
1318        crate::policy::effort::broadcast_effort_spellings(&mut kwargs);
1319        kwargs
1320    }
1321
1322    /// Reject OpenAI fields we do not implement, and `tool_choice`
1323    /// values that would silently lie (required / named function).
1324    fn validate_supported_fields(&self) -> Result<(), ApiError> {
1325        // An explicit zero is a client error, not "unset". Serde already
1326        // told them apart -- an absent field became
1327        // `DEFAULT_CHAT_MAX_TOKENS` -- so a 0 here is one the caller
1328        // wrote, and the engine cannot serve a zero-token budget: the
1329        // request would never become decodable and the client would wait
1330        // for an answer that cannot arrive.
1331        if self.max_tokens == 0 {
1332            return Err(invalid_request(
1333                "max_tokens must be at least 1",
1334                "max_tokens",
1335            ));
1336        }
1337        // An unrecognized switch is refused rather than read as "on":
1338        // a client that misspells `disabled` and is served a thinking
1339        // model anyway has been silently given the opposite of what it
1340        // asked for.
1341        if let Some(switch) = &self.thinking {
1342            let kind = switch.kind.trim().to_ascii_lowercase();
1343            if kind != "enabled" && kind != "disabled" {
1344                return Err(invalid_request(
1345                    "thinking.type must be \"enabled\" or \"disabled\"",
1346                    "thinking.type",
1347                ));
1348            }
1349        }
1350        for msg in &self.messages {
1351            if msg.content.as_ref().is_some_and(MessageContent::has_image) {
1352                return Err(unsupported_feature(
1353                    "image_url content parts are not implemented (multimodal/VL deferred, see docs/API.md)",
1354                ));
1355            }
1356        }
1357        if self.logprobs == Some(true) || self.top_logprobs.is_some() {
1358            return Err(unsupported_feature(
1359                "logprobs / top_logprobs are not implemented yet (see docs/API.md)",
1360            ));
1361        }
1362        if self.n.is_some_and(|n| n > 1) {
1363            return Err(unsupported_feature(
1364                "n > 1 is not implemented (single completion only)",
1365            ));
1366        }
1367        if let Some(fmt) = &self.response_format {
1368            match fmt.get("type").and_then(|v| v.as_str()) {
1369                Some("json_object") => {}
1370                Some(other) => {
1371                    return Err((
1372                        StatusCode::BAD_REQUEST,
1373                        Json(serde_json::json!({
1374                            "error": {
1375                                "message": format!(
1376                                    "response_format type {other:?} is not supported (only json_object)"
1377                                )
1378                            }
1379                        })),
1380                    ));
1381                }
1382                None => {
1383                    return Err((
1384                        StatusCode::BAD_REQUEST,
1385                        Json(serde_json::json!({
1386                            "error": {
1387                                "message": "response_format must include \"type\" (only json_object is supported)"
1388                            }
1389                        })),
1390                    ));
1391                }
1392            }
1393        }
1394        match &self.tool_choice {
1395            Some(ToolChoice::Mode(m)) if m == "required" => {
1396                return Err(unsupported_feature(
1397                    "tool_choice=required needs constrained decoding (not implemented)",
1398                ));
1399            }
1400            Some(ToolChoice::Specific(_)) => {
1401                return Err(unsupported_feature(
1402                    "named tool_choice is not implemented (use auto/none)",
1403                ));
1404            }
1405            _ => {}
1406        }
1407        Ok(())
1408    }
1409
1410    /// `stop_sequences()` plus `</tool_call>` when tool-calling is
1411    /// active -- reusing the existing stop-sequence machinery
1412    /// (`generate::generate`'s `earliest_stop_match`) to end generation
1413    /// right after a tool call's JSON body, rather than adding any new
1414    /// decode-time logic. See `tool_preamble`'s doc comment for the
1415    /// full real, disclosed approach.
1416    fn effective_stop_sequences(&self) -> Vec<String> {
1417        let mut stop = self.stop_sequences();
1418        if self.tools_active() {
1419            stop.push("</tool_call>".to_string());
1420        }
1421        stop
1422    }
1423
1424    fn json_object_mode(&self) -> bool {
1425        self.response_format
1426            .as_ref()
1427            .and_then(|v| v.get("type"))
1428            .and_then(|v| v.as_str())
1429            == Some("json_object")
1430    }
1431
1432    fn generation_params(&self) -> GenerationParams {
1433        GenerationParams {
1434            max_tokens: self.max_tokens,
1435            sampling: self.sampling_params(),
1436            seed: self.resolved_seed(),
1437            stop: self.effective_stop_sequences(),
1438            // Resolved by `run_generation_emit`, the layer that holds a
1439            // tokenizer: a request body names stop strings, and only
1440            // the model can say which of them are single tokens.
1441            stop_token_ids: Vec::new(),
1442            json_object: self.json_object_mode(),
1443            // Filled in by the handler that owns the request id --
1444            // the request body cannot name its own cancel token.
1445            cancel: None,
1446            ignore_eos: self.ignore_eos.unwrap_or(false),
1447        }
1448    }
1449
1450    /// Like [`Self::generation_params`], plus architecture-default stop
1451    /// strings (Gemma IT emits `<end_of_turn>` before `<eos>`).
1452    fn generation_params_for_template(
1453        &self,
1454        template: &chat_template::PromptTemplate,
1455    ) -> GenerationParams {
1456        let mut params = self.generation_params();
1457        if let Some(stop) = template.end_of_turn() {
1458            if !params.stop.iter().any(|s| s == stop) {
1459                params.stop.push(stop.to_string());
1460            }
1461        }
1462        params
1463    }
1464
1465    /// A request only has a deterministic outcome -- and therefore is
1466    /// only safe to serve from or populate into the whole-response
1467    /// cache -- when it's plain greedy decode (temperature <= 0) or an
1468    /// explicit seed was given. Anything else must always regenerate:
1469    /// a "cache hit" for an unseeded sampled request would silently
1470    /// replay one random draw forever, defeating the purpose of
1471    /// sampling and surprising any client expecting fresh output per
1472    /// call.
1473    fn is_cacheable(&self) -> bool {
1474        self.temperature.unwrap_or(0.0) <= 0.0 || self.seed.is_some()
1475    }
1476
1477    fn cache_key(&self, prompt: &str) -> CacheKey {
1478        CacheKey {
1479            model: self.model.clone(),
1480            prompt: prompt.to_string(),
1481            max_tokens: self.max_tokens,
1482            temperature_bits: self.temperature.unwrap_or(0.0).to_bits(),
1483            top_p_bits: self.top_p.unwrap_or(1.0).to_bits(),
1484            top_k: self.top_k.unwrap_or(0),
1485            repetition_penalty_bits: self.repetition_penalty.unwrap_or(1.0).to_bits(),
1486            presence_penalty_bits: self.presence_penalty.unwrap_or(0.0).to_bits(),
1487            frequency_penalty_bits: self.frequency_penalty.unwrap_or(0.0).to_bits(),
1488            seed: self.seed,
1489            stop: self.effective_stop_sequences(),
1490        }
1491    }
1492
1493    fn resolved_seed(&self) -> u64 {
1494        self.seed.unwrap_or_else(|| {
1495            std::time::SystemTime::now()
1496                .duration_since(std::time::UNIX_EPOCH)
1497                .map(|d| d.as_nanos() as u64)
1498                .unwrap_or(0xDEFA017)
1499        })
1500    }
1501}
1502
1503#[derive(Serialize)]
1504struct ChatCompletionChoice {
1505    index: usize,
1506    message: ChatCompletionResponseMessage,
1507    finish_reason: &'static str,
1508}
1509
1510#[derive(Serialize)]
1511struct ChatCompletionResponseMessage {
1512    role: &'static str,
1513    #[serde(skip_serializing_if = "Option::is_none")]
1514    content: Option<String>,
1515    /// A reasoning model's chain of thought, split out of `content`.
1516    /// Absent for a model that emitted none, which is also what a
1517    /// client that does not know the field sees.
1518    #[serde(skip_serializing_if = "Option::is_none")]
1519    reasoning_content: Option<String>,
1520    #[serde(skip_serializing_if = "Option::is_none")]
1521    tool_calls: Option<Vec<ToolCallOut>>,
1522}
1523
1524#[derive(Serialize, Clone)]
1525struct ToolCallOut {
1526    id: String,
1527    #[serde(rename = "type")]
1528    kind: &'static str,
1529    function: ToolCallFunctionOut,
1530}
1531
1532/// One tool call as a **streamed delta**.
1533///
1534/// OpenAI's incremental shape: `index` correlates the pieces, and every
1535/// other field is optional because the first delta of a call carries
1536/// its identity and the ones after it carry only more argument text. A
1537/// buffered path expresses a whole call as a delta with every field
1538/// set, so there is one type on the wire rather than two.
1539#[derive(Serialize, Clone)]
1540struct ToolCallDelta {
1541    index: usize,
1542    #[serde(skip_serializing_if = "Option::is_none")]
1543    id: Option<String>,
1544    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1545    kind: Option<&'static str>,
1546    function: ToolCallFunctionDelta,
1547}
1548
1549#[derive(Serialize, Clone, Default)]
1550struct ToolCallFunctionDelta {
1551    #[serde(skip_serializing_if = "Option::is_none")]
1552    name: Option<String>,
1553    /// A literal continuation of this call's arguments JSON. A client
1554    /// concatenates them in `index` order and parses the result.
1555    #[serde(skip_serializing_if = "Option::is_none")]
1556    arguments: Option<String>,
1557}
1558
1559impl ToolCallDelta {
1560    /// The whole call in one delta, for a path that had it all along.
1561    fn whole(index: usize, name: String, arguments: String) -> Self {
1562        ToolCallDelta {
1563            index,
1564            id: Some(format!("call_{index}")),
1565            kind: Some("function"),
1566            function: ToolCallFunctionDelta {
1567                name: Some(name),
1568                arguments: Some(arguments),
1569            },
1570        }
1571    }
1572
1573    /// The opening delta: identity, and no arguments yet.
1574    fn opening(index: usize, name: String) -> Self {
1575        ToolCallDelta {
1576            index,
1577            id: Some(format!("call_{index}")),
1578            kind: Some("function"),
1579            function: ToolCallFunctionDelta {
1580                name: Some(name),
1581                arguments: Some(String::new()),
1582            },
1583        }
1584    }
1585
1586    /// A continuation: more argument text for a call already opened.
1587    fn arguments(index: usize, fragment: String) -> Self {
1588        ToolCallDelta {
1589            index,
1590            id: None,
1591            kind: None,
1592            function: ToolCallFunctionDelta {
1593                name: None,
1594                arguments: Some(fragment),
1595            },
1596        }
1597    }
1598}
1599
1600#[derive(Serialize, Clone)]
1601struct ToolCallFunctionOut {
1602    name: String,
1603    /// A JSON-encoded string, matching the real OpenAI
1604    /// `tool_calls[].function.arguments` convention (see
1605    /// `ToolCallFunctionIn::arguments`'s doc comment).
1606    arguments: String,
1607}
1608
1609#[derive(Serialize)]
1610struct ChatCompletionResponse {
1611    id: String,
1612    /// Non-standard extension: the same value as `id`, stated under the
1613    /// name the rest of ferrox keys by (metrics, logs, `POST /cancel`
1614    /// once it exists). `id` is OpenAI's completion id and a client has
1615    /// no way to know ferrox also uses it as the request key -- saying
1616    /// so costs one field and removes the guess.
1617    request_id: String,
1618    object: &'static str,
1619    model: String,
1620    choices: Vec<ChatCompletionChoice>,
1621    /// OpenAI-convention token accounting (prompt/completion/total),
1622    /// counted from the exact ids the generation loop processed. On a
1623    /// whole-response cache hit, this is the original computation's
1624    /// accounting (same prompt, same deterministic outcome).
1625    usage: generate::Usage,
1626    /// Non-standard extension field (not part of the OpenAI API
1627    /// contract, but additive and harmless to OpenAI-compatible
1628    /// clients that ignore unknown fields): "hit" if this exact
1629    /// cacheable request was already computed, "miss" if this request
1630    /// just computed and cached a fresh completion, or "skip" if the
1631    /// request wasn't cacheable at all (sampling without a seed --
1632    /// see `ChatCompletionRequest::is_cacheable`).
1633    ferrox_cache: &'static str,
1634}
1635
1636#[derive(Serialize)]
1637struct ChatCompletionChunkDelta {
1638    #[serde(skip_serializing_if = "Option::is_none")]
1639    role: Option<&'static str>,
1640    #[serde(skip_serializing_if = "Option::is_none")]
1641    content: Option<String>,
1642    /// See `ChatCompletionResponseMessage::reasoning_content`.
1643    #[serde(skip_serializing_if = "Option::is_none")]
1644    reasoning_content: Option<String>,
1645    #[serde(skip_serializing_if = "Option::is_none")]
1646    tool_calls: Option<Vec<ToolCallDelta>>,
1647}
1648
1649#[derive(Serialize)]
1650struct ChatCompletionChunkChoice {
1651    index: usize,
1652    delta: ChatCompletionChunkDelta,
1653    finish_reason: Option<&'static str>,
1654}
1655
1656#[derive(Serialize)]
1657struct ChatCompletionChunk {
1658    id: String,
1659    /// Present on the **first** chunk of a stream (see
1660    /// `ChatCompletionResponse::request_id`). A client learns the key
1661    /// for this generation before any content arrives, so a live view
1662    /// can correlate metrics with the stream it is rendering instead of
1663    /// guessing which in-flight request is "probably mine" -- a guess
1664    /// that mis-attributes the moment two chats run at once.
1665    #[serde(skip_serializing_if = "Option::is_none")]
1666    request_id: Option<String>,
1667    object: &'static str,
1668    model: String,
1669    choices: Vec<ChatCompletionChunkChoice>,
1670    /// Present only on the final chunk (the one carrying
1671    /// `finish_reason`), mirroring OpenAI's stream `usage` shape.
1672    #[serde(skip_serializing_if = "Option::is_none")]
1673    usage: Option<generate::Usage>,
1674}
1675
1676/// Liveness, readiness and capabilities in one cheap answer (see the
1677/// `health` module for why detection is a visible state rather than a
1678/// gap). Never behind auth or rate limiting, and never blocking: this is
1679/// the endpoint a supervisor asks when it is deciding whether to kill
1680/// the process.
1681async fn health(State(state): State<Arc<AppState>>) -> Response {
1682    let snapshot = state.detection.snapshot();
1683    let mut capabilities = snapshot.capabilities;
1684    let active = state.active();
1685
1686    // Model-derived capabilities need no probing, so they are answered
1687    // even while backend detection is still running.
1688    capabilities.push(match active.as_deref() {
1689        // `unavailable` was defined in Phase 1 but unreachable, because
1690        // the server only bound the port after a successful load. With
1691        // `/admin/models/unload` it is a state a client can actually
1692        // observe, and it must not read as "loaded but synthetic".
1693        None => ferrox_api::Capability::unavailable(
1694            ferrox_api::health::capability::REAL_WEIGHTS,
1695            ferrox_api::health::reason::MODEL_NOT_LOADED,
1696            "No model is loaded. POST /admin/models/load with an id from GET /admin/models.",
1697        ),
1698        Some(active) if active.model.is_synthetic() => ferrox_api::Capability::unavailable(
1699            ferrox_api::health::capability::REAL_WEIGHTS,
1700            ferrox_api::health::reason::MODEL_NOT_LOADED,
1701            "Serving synthetic random weights: set FERROX_MODEL_PATH (or -m) to a real \
1702             checkpoint. Output from this model is noise.",
1703        ),
1704        Some(active) => ferrox_api::Capability::available(
1705            ferrox_api::health::capability::REAL_WEIGHTS,
1706            format!("Serving the real checkpoint '{}'.", active.model.name()),
1707        ),
1708    });
1709    capabilities.push(if active.as_ref().is_some_and(|a| a.batcher.is_some()) {
1710        ferrox_api::Capability::available(
1711            ferrox_api::health::capability::CONTINUOUS_BATCHING,
1712            "Concurrent requests share one batched decode step.",
1713        )
1714    } else {
1715        ferrox_api::Capability::unavailable(
1716            ferrox_api::health::capability::CONTINUOUS_BATCHING,
1717            ferrox_api::health::reason::DISABLED,
1718            "Off; set FERROX_CONTINUOUS_BATCHING=1 (incompatible with a KV pool or prefix cache).",
1719        )
1720    });
1721
1722    let last_request_ms = state
1723        .last_request_ms
1724        .load(std::sync::atomic::Ordering::Relaxed);
1725    let uptime = state.started_at.elapsed();
1726    // Readiness is "can this server generate", and with nothing loaded
1727    // it cannot -- so `unavailable` (503) wins over whatever the backend
1728    // probe concluded. Phase 1 defined this state but nothing could
1729    // reach it, because the process only bound the port after a
1730    // successful load; `/admin/models/unload` makes it reachable, and a
1731    // 200 `ready` here would tell a supervisor to send traffic that is
1732    // guaranteed to 503.
1733    let health_state = if active.is_none() {
1734        ferrox_api::HealthState::Unavailable
1735    } else {
1736        snapshot.state
1737    };
1738    let body = ferrox_api::HealthResponse {
1739        state: health_state,
1740        reason: match health_state {
1741            ferrox_api::HealthState::Ready => None,
1742            ferrox_api::HealthState::Unavailable => {
1743                Some(ferrox_api::health::reason::MODEL_NOT_LOADED.to_string())
1744            }
1745            ferrox_api::HealthState::Detecting => {
1746                Some(ferrox_api::health::reason::DETECTING.to_string())
1747            }
1748        },
1749        detail: match health_state {
1750            ferrox_api::HealthState::Ready => None,
1751            ferrox_api::HealthState::Unavailable => Some(
1752                "No model is loaded. POST /admin/models/load with an id from GET /admin/models."
1753                    .to_string(),
1754            ),
1755            ferrox_api::HealthState::Detecting => {
1756                Some("Probing available compute backends.".to_string())
1757            }
1758        },
1759        model: active
1760            .as_deref()
1761            .map(|active| ferrox_api::health::ModelSummary {
1762                id: active.model.name().to_string(),
1763                tokenizer: active.model.tokenizer_kind().to_string(),
1764                synthetic_weights: active.model.is_synthetic(),
1765            }),
1766        capabilities,
1767        version: env!("CARGO_PKG_VERSION").to_string(),
1768        pid: std::process::id(),
1769        uptime_seconds: uptime.as_secs_f64(),
1770        server_time_unix_ms: std::time::SystemTime::now()
1771            .duration_since(std::time::UNIX_EPOCH)
1772            .map(|d| d.as_millis().min(u64::MAX as u128) as u64)
1773            .unwrap_or(0),
1774        last_request_age_seconds: (last_request_ms > 0)
1775            .then(|| uptime.as_secs_f64() - (last_request_ms as f64 / 1000.0))
1776            .map(|age| age.max(0.0)),
1777    };
1778
1779    let status =
1780        StatusCode::from_u16(body.state.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1781    (status, Json(body)).into_response()
1782}
1783
1784async fn list_models(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1785    // OpenAI's `/v1/models` lists what can be *used* right now, which
1786    // after an unload is nothing. The inventory of what is on disk is a
1787    // different question and lives at `/admin/models`.
1788    let Some(active) = state.active() else {
1789        return Json(serde_json::json!({ "object": "list", "data": [] }));
1790    };
1791    let mut model_entry = serde_json::json!({
1792        "id": active.model.name(),
1793        "object": "model",
1794        "ferrox_synthetic_weights": active.model.is_synthetic(),
1795        "ferrox_tokenizer": active.model.tokenizer_kind(),
1796    });
1797    // Which reasoning gears this checkpoint really has, learned by
1798    // probing its own template at load. A checkpoint that says nothing
1799    // about thinking carries NEITHER field rather than an empty list:
1800    // an empty list reads as "asked, and it has no gears", which is a
1801    // different claim from "this is not a reasoning model".
1802    let parser_configured =
1803        crate::policy::parser::ReasoningFormat::infer(active.model.name()).is_some();
1804    let gears = active.model.chat_template().think_gears(parser_configured);
1805    if !gears.is_empty() {
1806        model_entry["supported_reasoning_efforts"] = serde_json::json!(gears.supported);
1807        if let Some(default) = &gears.default {
1808            model_entry["default_reasoning_effort"] = serde_json::json!(default);
1809        }
1810        // What to SEND for each gear, so a client selects one without
1811        // knowing that "off" is two booleans and "high" is a string.
1812        model_entry["reasoning_effort_kwargs"] = serde_json::json!(gears.kwargs);
1813    }
1814    if let Some(mcp) = &state.mcp {
1815        model_entry["ferrox_mcp"] = mcp.models_metadata();
1816    }
1817    Json(serde_json::json!({
1818        "object": "list",
1819        "data": [model_entry]
1820    }))
1821}
1822
1823/// `GET /v1/stats`: what is happening *now*.
1824///
1825/// Distinct from `/admin/stats`, which is the historical ring. The two
1826/// throughput figures come from sliding windows, so an idle server
1827/// reports 0 rather than the rate it managed while it was busy -- a
1828/// cumulative average never comes back down, and a status bar showing
1829/// one is reporting the past as the present.
1830///
1831/// Latency is the ring's p95, nearest-rank, so it names a request that
1832/// really took that long. Both it and the mean time-to-first-token are
1833/// `null` rather than `0` when nothing can be said: a non-streamed
1834/// request has no TTFT, and averaging those in as zero would make the
1835/// server look faster the fewer clients stream.
1836async fn serving_stats(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1837    let now_ms = state.uptime().as_millis().min(u64::MAX as u128) as u64;
1838    let mut serving = state.serving.lock().unwrap_or_else(|p| p.into_inner());
1839    let active = state.active();
1840    Json(serde_json::json!({
1841        "model": active.as_ref().map(|a| a.model.name()),
1842        "state": state
1843            .maintenance
1844            .lock()
1845            .unwrap_or_else(|p| p.into_inner())
1846            .state()
1847            .as_str(),
1848        "uptime_s": state.uptime().as_secs(),
1849        "throughput": {
1850            "decode_tps": (serving.decode_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1851            "prefill_tps": (serving.prefill_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1852        },
1853        "requests": {
1854            "active": state.cancels.live_count(),
1855            "completed": state.stats.recorded_total(),
1856            "p95_ms": state.stats.p95_duration_ms(),
1857            "ttft_mean_ms": state.stats.ttft_mean_ms(),
1858            "prompt_tokens_total": state.stats.tokens_prompt_total(),
1859            "completion_tokens_total": state.stats.tokens_generated_total(),
1860        },
1861        // Served here so a status bar tracking throughput and pressure
1862        // makes ONE request rather than two. Upstream stamps the same
1863        // gauges on every reply of the batch; ferrox does not, because
1864        // the reply shapes here are OpenAI's and Anthropic's and a pool
1865        // gauge on a `chat.completion` is a field no client asked for.
1866        "pools": cache_admin::pool_gauges(&state),
1867        // What the engine is REALLY using, beside the budget it was
1868        // sized against. `null` when no live figure can be read.
1869        "memory": cache_admin::footprint_json(&state),
1870    }))
1871}
1872
1873#[derive(Deserialize)]
1874struct RequestsQuery {
1875    #[serde(default)]
1876    since: u64,
1877    #[serde(default = "default_requests_limit")]
1878    limit: usize,
1879}
1880
1881fn default_requests_limit() -> usize {
1882    stats::MAX_PAGE
1883}
1884
1885/// `GET /v1/requests?since=&limit=`: an incremental page of the ring.
1886///
1887/// The cursor is all-time, so a poller that keeps up reads each row
1888/// exactly once and never re-reads. `missed` is the honest half: rows
1889/// that existed and were evicted before this poll could see them. A
1890/// client polling slower than the server finishes requests needs to
1891/// know that, rather than have it hidden by a shorter page.
1892async fn recent_requests(
1893    State(state): State<Arc<AppState>>,
1894    axum::extract::Query(q): axum::extract::Query<RequestsQuery>,
1895) -> Json<serde_json::Value> {
1896    let (rows, cursor, missed) = state.stats.page(q.since, q.limit);
1897    Json(serde_json::json!({
1898        "requests": rows,
1899        "next_cursor": cursor,
1900        "missed": missed,
1901        "total": state.stats.recorded_total(),
1902    }))
1903}
1904
1905#[derive(Serialize)]
1906struct CombinedCacheStats {
1907    response_cache: response_cache::CacheStats,
1908    /// `None` when `FERROX_PREFIX_CACHE_ENTRIES` isn't set.
1909    prefix_cache: Option<ferrox_models::PrefixCacheStats>,
1910}
1911
1912async fn cache_stats(State(state): State<Arc<AppState>>) -> Json<CombinedCacheStats> {
1913    Json(CombinedCacheStats {
1914        response_cache: lock_cache(&state.response_cache).stats(),
1915        prefix_cache: state
1916            .prefix_cache
1917            .as_ref()
1918            .map(|pc| pc.lock().unwrap_or_else(|p| p.into_inner()).stats()),
1919    })
1920}
1921
1922/// Prometheus text-exposition format (`# HELP`/`# TYPE` plus
1923/// `name value` lines), so this endpoint can be scraped directly by a
1924/// Prometheus server or anything compatible with that format without
1925/// ferrox needing to speak any particular metrics client library.
1926async fn metrics(State(state): State<Arc<AppState>>) -> Response {
1927    use std::sync::atomic::Ordering;
1928
1929    let cache_stats = lock_cache(&state.response_cache).stats();
1930    let active = state.active();
1931    let requests_total = state.requests_total.load(Ordering::Relaxed);
1932    let errors_total = state.request_errors_total.load(Ordering::Relaxed);
1933    let uptime = state.started_at.elapsed().as_secs_f64();
1934
1935    let body = format!(
1936        "# HELP ferrox_requests_total Total chat completion requests received.\n\
1937         # TYPE ferrox_requests_total counter\n\
1938         ferrox_requests_total {requests_total}\n\
1939         # HELP ferrox_request_errors_total Total chat completion requests that returned an error.\n\
1940         # TYPE ferrox_request_errors_total counter\n\
1941         ferrox_request_errors_total {errors_total}\n\
1942         # HELP ferrox_cache_hits_total Whole-response cache hits.\n\
1943         # TYPE ferrox_cache_hits_total counter\n\
1944         ferrox_cache_hits_total {}\n\
1945         # HELP ferrox_cache_misses_total Whole-response cache misses.\n\
1946         # TYPE ferrox_cache_misses_total counter\n\
1947         ferrox_cache_misses_total {}\n\
1948         # HELP ferrox_cache_entries Current whole-response cache entry count.\n\
1949         # TYPE ferrox_cache_entries gauge\n\
1950         ferrox_cache_entries {}\n\
1951         # HELP ferrox_synthetic_weights 1 if serving synthetic random weights instead of a real checkpoint.\n\
1952         # TYPE ferrox_synthetic_weights gauge\n\
1953         ferrox_synthetic_weights {}\n\
1954         # HELP ferrox_uptime_seconds Seconds since this server process started.\n\
1955         # TYPE ferrox_uptime_seconds gauge\n\
1956         ferrox_uptime_seconds {uptime}\n",
1957        cache_stats.hits,
1958        cache_stats.misses,
1959        cache_stats.entries,
1960        // With nothing loaded there are no weights at all, synthetic or
1961        // otherwise; 0 is the reading that keeps the gauge meaning
1962        // "serving noise" rather than "serving nothing".
1963        active
1964            .as_ref()
1965            .map(|a| a.model.is_synthetic() as u8)
1966            .unwrap_or(0),
1967    );
1968
1969    // Expert-store counters, present only when the model streams
1970    // routed experts through the bounded cache
1971    // (FERROX_EXPERT_CACHE_BYTES).
1972    let body = match active
1973        .as_ref()
1974        .and_then(|a| a.model.expert_store_stats())
1975    {
1976        Some(es) => format!(
1977            "{body}\
1978             # HELP ferrox_expert_cache_hits_total Expert-store cache hits.\n\
1979             # TYPE ferrox_expert_cache_hits_total counter\n\
1980             ferrox_expert_cache_hits_total {}\n\
1981             # HELP ferrox_expert_cache_misses_total Expert-store cache misses (source reads).\n\
1982             # TYPE ferrox_expert_cache_misses_total counter\n\
1983             ferrox_expert_cache_misses_total {}\n\
1984             # HELP ferrox_expert_cache_evictions_total Expert-store LRU evictions.\n\
1985             # TYPE ferrox_expert_cache_evictions_total counter\n\
1986             ferrox_expert_cache_evictions_total {}\n\
1987             # HELP ferrox_expert_cache_pass_throughs_total Acquires served uncached (entry could not fit the budget).\n\
1988             # TYPE ferrox_expert_cache_pass_throughs_total counter\n\
1989             ferrox_expert_cache_pass_throughs_total {}\n\
1990             # HELP ferrox_expert_cache_bytes_read_total Bytes read from the checkpoint for expert misses.\n\
1991             # TYPE ferrox_expert_cache_bytes_read_total counter\n\
1992             ferrox_expert_cache_bytes_read_total {}\n\
1993             # HELP ferrox_expert_cache_resident_bytes Current expert-cache footprint in bytes.\n\
1994             # TYPE ferrox_expert_cache_resident_bytes gauge\n\
1995             ferrox_expert_cache_resident_bytes {}\n",
1996            es.hits, es.misses, es.evictions, es.pass_throughs, es.bytes_read, es.resident_bytes,
1997        ),
1998        None => body,
1999    };
2000
2001    // Scheduler counters, present only under continuous batching
2002    // (FERROX_CONTINUOUS_BATCHING=1). `prefill_chunks` next to
2003    // `prefill_tokens` is what makes chunked prefill observable: their
2004    // ratio is the effective chunk size the worker actually ran.
2005    let body = match active.as_ref().and_then(|a| a.batcher.as_ref()) {
2006        Some(batcher) => {
2007            let sched = batcher.stats();
2008            format!(
2009                "{body}\
2010                 # HELP ferrox_prefill_chunks_total Bounded prefill chunks the batch scheduler has run.\n\
2011                 # TYPE ferrox_prefill_chunks_total counter\n\
2012                 ferrox_prefill_chunks_total {}\n\
2013                 # HELP ferrox_prefill_tokens_total Prompt tokens run through chunked prefill.\n\
2014                 # TYPE ferrox_prefill_tokens_total counter\n\
2015                 ferrox_prefill_tokens_total {}\n\
2016                 # HELP ferrox_decode_steps_total Batched decode steps the batch scheduler has run.\n\
2017                 # TYPE ferrox_decode_steps_total counter\n\
2018                 ferrox_decode_steps_total {}\n\
2019                 # HELP ferrox_scheduler_queue_depth Requests waiting for admission to the batch scheduler.\n\
2020                 # TYPE ferrox_scheduler_queue_depth gauge\n\
2021                 ferrox_scheduler_queue_depth {}\n\
2022                 # HELP ferrox_scheduler_queue_rejected_total Requests refused with 503 because the admission queue was full.\n\
2023                 # TYPE ferrox_scheduler_queue_rejected_total counter\n\
2024                 ferrox_scheduler_queue_rejected_total {}\n\
2025                 # HELP ferrox_kv_blocks_total KV blocks in the scheduler's admission budget (0 when unconfigured).\n\
2026                 # TYPE ferrox_kv_blocks_total gauge\n\
2027                 ferrox_kv_blocks_total {}\n\
2028                 # HELP ferrox_kv_blocks_free KV blocks not reserved by an in-flight request.\n\
2029                 # TYPE ferrox_kv_blocks_free gauge\n\
2030                 ferrox_kv_blocks_free {}\n\
2031                 # HELP ferrox_kv_block_size Token positions per KV block.\n\
2032                 # TYPE ferrox_kv_block_size gauge\n\
2033                 ferrox_kv_block_size {}\n\
2034                 # HELP ferrox_kv_rejected_too_large_total Requests refused with 400 because they exceed the whole KV block budget.\n\
2035                 # TYPE ferrox_kv_rejected_too_large_total counter\n\
2036                 ferrox_kv_rejected_too_large_total {}\n\
2037                 # HELP ferrox_kv_rejected_context_length_total Requests refused with 400 for exceeding the per-request context ceiling.\n\
2038                 # TYPE ferrox_kv_rejected_context_length_total counter\n\
2039                 ferrox_kv_rejected_context_length_total {}\n\
2040                 # HELP ferrox_scheduler_aborted_total Requests the batch scheduler stopped because they were cancelled.\n\
2041                 # TYPE ferrox_scheduler_aborted_total counter\n\
2042                 ferrox_scheduler_aborted_total {}\n",
2043                sched.prefill_chunks,
2044                sched.prefill_tokens,
2045                sched.decode_steps,
2046                sched.queue_depth,
2047                sched.queue_rejected,
2048                sched.kv_blocks_total,
2049                sched.kv_blocks_free,
2050                sched.kv_block_size,
2051                sched.kv_rejected_too_large,
2052                sched.kv_rejected_context_length,
2053                sched.aborted,
2054            )
2055        }
2056        None => body,
2057    };
2058
2059    (
2060        [(
2061            axum::http::header::CONTENT_TYPE,
2062            "text/plain; version=0.0.4",
2063        )],
2064        body,
2065    )
2066        .into_response()
2067}
2068
2069pub(crate) type ApiError = (StatusCode, Json<serde_json::Value>);
2070
2071/// A field the server understands but this value of which it cannot
2072/// serve. Distinct from [`unsupported_feature`] (501, "ferrox does not
2073/// implement this") -- a 400 says the request itself is wrong, which is
2074/// the difference between a client retrying elsewhere and a client
2075/// fixing its own body.
2076pub(crate) fn invalid_request(message: &str, param: &str) -> ApiError {
2077    (
2078        StatusCode::BAD_REQUEST,
2079        Json(serde_json::json!({"error": {
2080            "message": message,
2081            "type": "invalid_request_error",
2082            "param": param,
2083            "code": null,
2084        }})),
2085    )
2086}
2087
2088pub(crate) fn unsupported_feature(message: &str) -> ApiError {
2089    (
2090        StatusCode::NOT_IMPLEMENTED,
2091        Json(serde_json::json!({"error": {"message": message, "type": "unsupported"}})),
2092    )
2093}
2094
2095pub(crate) fn decode_error_response(e: generate::DecodeError) -> ApiError {
2096    let status = match e {
2097        generate::DecodeError::TokenOutOfVocab { .. } => StatusCode::BAD_REQUEST,
2098        // The request is bigger than the server can ever serve. That
2099        // is a property of the request, so it is the client's 400 --
2100        // answering 503 would send it into a retry loop that cannot
2101        // succeed.
2102        generate::DecodeError::KvBudgetExceeded { .. } => StatusCode::BAD_REQUEST,
2103        // Not the client's fault, and true of the exact same request a
2104        // moment later once capacity frees up -- 503, not 400. The
2105        // `Retry-After` header these need is stamped centrally by
2106        // `limits::retry_after`; see that function for why it lives in a
2107        // layer rather than here.
2108        generate::DecodeError::KvPoolExhausted | generate::DecodeError::QueueFull { .. } => {
2109            StatusCode::SERVICE_UNAVAILABLE
2110        }
2111    };
2112    tracing::warn!("decode error: {e}");
2113    let mut body = serde_json::json!({"error": {"message": e.to_string()}});
2114    // A refusal against a ceiling names the ceiling and both sides of
2115    // the arithmetic. "Out of memory" (or a bare 400) tells a caller
2116    // that something did not fit; it does not tell them whether to
2117    // shorten the prompt or to run a bigger box, and those are the only
2118    // two actions available.
2119    if let generate::DecodeError::KvBudgetExceeded {
2120        binding,
2121        estimated_bytes,
2122        limit_bytes,
2123        positions,
2124        positions_limit,
2125        ..
2126    } = &e
2127    {
2128        body["error"]["type"] = serde_json::json!("invalid_request_error");
2129        body["error"]["code"] = serde_json::json!(binding);
2130        body["error"]["binding"] = serde_json::json!(binding);
2131        body["error"]["estimated_bytes"] = serde_json::json!(estimated_bytes);
2132        body["error"]["limit_bytes"] = serde_json::json!(limit_bytes);
2133        body["error"]["positions"] = serde_json::json!(positions);
2134        body["error"]["positions_limit"] = serde_json::json!(positions_limit);
2135    }
2136    // The header carries the same hint (stamped by `limits::retry_after`);
2137    // repeating it in the body is for clients that read JSON and never
2138    // look at headers, which is most of them.
2139    if let Some(secs) = e.retry_after_secs() {
2140        body["error"]["retry_after_seconds"] = serde_json::json!(secs);
2141    }
2142    (status, Json(body))
2143}
2144
2145pub(crate) fn join_error_response(e: tokio::task::JoinError) -> ApiError {
2146    tracing::error!("generation task panicked: {e}");
2147    (
2148        StatusCode::INTERNAL_SERVER_ERROR,
2149        Json(serde_json::json!({"error": {"message": "internal error during generation"}})),
2150    )
2151}
2152
2153/// Runs generation for `params` against `model`, calling `emit` for each
2154/// decoded text chunk. Returns finish reason, usage, and the concatenated
2155/// text (for sessions / tool-call detection). Pure CPU-bound work with
2156/// no I/O and no shared lock: safe to run on `spawn_blocking`.
2157#[allow(clippy::too_many_arguments)] // one clear parameter per concern:
2158                                     // model + prompt + params, then the three optional shared
2159                                     // facilities (KV pool, prefix cache, batcher), the context
2160                                     // ceiling, and the sink. Bundling them would only move the
2161                                     // same list behind a struct at two call sites.
2162fn run_generation_emit(
2163    model: &Model,
2164    prompt: &str,
2165    params: &GenerationParams,
2166    kv_pool: Option<&generate::KvPoolConfig>,
2167    paged_kv: Option<&generate::PagedKvConfig>,
2168    prefix_cache: Option<&Mutex<PrefixCache>>,
2169    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2170    ceiling: Option<&budget::ContextCeiling>,
2171    mut emit: impl FnMut(&str),
2172) -> Result<(FinishReason, generate::Usage, String), generate::DecodeError> {
2173    let synthetic = model.is_synthetic();
2174    let mut chunks = Vec::new();
2175    // Layer 1 of the stop machinery is resolved exactly here, because
2176    // this is the one place that has both the request's stop strings
2177    // and the model's tokenizer. Both the batched and the private
2178    // decode paths below read the result off the params, so there is
2179    // one answer rather than two that can drift.
2180    let params = &{
2181        let mut resolved = params.clone();
2182        resolved.stop_token_ids =
2183            crate::stop::resolve_stop_tokens(&resolved.stop, |text| model.encode(text));
2184        resolved
2185    };
2186    let used_batcher = matches!((model, continuous_batcher), (Model::Gguf(_), Some(_)));
2187    let (finish, usage) = match model {
2188        Model::Gguf(m) => {
2189            if let Some(batcher) = continuous_batcher {
2190                let mut tokens = m.tokenizer.encode(prompt);
2191                ferrox_models::tokenizer::prepend_bos(&mut tokens, m.bos_id);
2192                let (finish, _generated_ids, text, usage) =
2193                    batcher.generate(tokens, params.clone(), m.stop_tokens.clone())?;
2194                if !text.is_empty() {
2195                    chunks.push(text);
2196                }
2197                (finish, usage)
2198            } else {
2199                generate::generate(
2200                    &m.decoder,
2201                    m.tokenizer.as_ref(),
2202                    &m.stop_tokens,
2203                    m.bos_id,
2204                    prompt,
2205                    params,
2206                    kv_pool,
2207                    paged_kv,
2208                    prefix_cache,
2209                    ceiling,
2210                    |chunk| {
2211                        chunks.push(chunk.to_string());
2212                        if !synthetic {
2213                            emit(chunk);
2214                        }
2215                    },
2216                )?
2217            }
2218        }
2219        Model::Kimi(m) => generate::generate_engine(
2220            &m.engine,
2221            &m.tokenizer,
2222            &m.stop_tokens,
2223            None,
2224            prompt,
2225            params,
2226            |chunk| {
2227                chunks.push(chunk.to_string());
2228                if !synthetic {
2229                    emit(chunk);
2230                }
2231            },
2232        )?,
2233        Model::Mla(m) => generate::generate_engine(
2234            &m.engine,
2235            &m.tokenizer,
2236            &m.stop_tokens,
2237            m.bos_id,
2238            prompt,
2239            params,
2240            |chunk| {
2241                chunks.push(chunk.to_string());
2242                if !synthetic {
2243                    emit(chunk);
2244                }
2245            },
2246        )?,
2247        Model::Gemma4(m) => generate::generate_engine(
2248            &m.engine,
2249            &m.tokenizer,
2250            &m.stop_tokens,
2251            m.bos_id,
2252            prompt,
2253            params,
2254            |chunk| {
2255                chunks.push(chunk.to_string());
2256                if !synthetic {
2257                    emit(chunk);
2258                }
2259            },
2260        )?,
2261        Model::Glm52(m) => generate::generate_engine(
2262            &m.engine,
2263            &m.tokenizer,
2264            &m.stop_tokens,
2265            m.bos_id,
2266            prompt,
2267            params,
2268            |chunk| {
2269                chunks.push(chunk.to_string());
2270                if !synthetic {
2271                    emit(chunk);
2272                }
2273            },
2274        )?,
2275    };
2276
2277    let mut full = chunks.concat();
2278    if synthetic {
2279        full = format!(
2280            "[ferrox synthetic-weight demo: no real checkpoint loaded -- set FERROX_MODEL_PATH \
2281             to serve a real model. Decoded ids -> {full:?}]"
2282        );
2283        emit(&full);
2284    } else if used_batcher && !full.is_empty() {
2285        emit(&full);
2286    }
2287
2288    Ok((finish, usage, full))
2289}
2290
2291/// Collecting wrapper around [`run_generation_emit`] for non-streaming
2292/// paths and tests.
2293#[allow(clippy::too_many_arguments)] // mirrors `run_generation_emit`
2294                                     // exactly, minus the sink; see its note.
2295pub(crate) fn run_generation(
2296    model: &Model,
2297    prompt: &str,
2298    params: &GenerationParams,
2299    kv_pool: Option<&generate::KvPoolConfig>,
2300    paged_kv: Option<&generate::PagedKvConfig>,
2301    prefix_cache: Option<&Mutex<PrefixCache>>,
2302    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2303    ceiling: Option<&budget::ContextCeiling>,
2304) -> Result<(Vec<String>, FinishReason, generate::Usage), generate::DecodeError> {
2305    let (finish, usage, full) = run_generation_emit(
2306        model,
2307        prompt,
2308        params,
2309        kv_pool,
2310        paged_kv,
2311        prefix_cache,
2312        continuous_batcher,
2313        ceiling,
2314        |_| {},
2315    )?;
2316    Ok((
2317        if full.is_empty() {
2318            Vec::new()
2319        } else {
2320            vec![full]
2321        },
2322        finish,
2323        usage,
2324    ))
2325}
2326
2327/// Render a conversation into the prompt the served checkpoint expects.
2328///
2329/// Who describes the tools depends on the template: one that reads
2330/// `tools` is handed them structurally and owns the whole grammar, and
2331/// one that does not gets [`tool_preamble`] as an extra leading system
2332/// turn -- this server's original answer, and still the only one
2333/// available for a checkpoint whose template never mentions tools.
2334///
2335/// `extra` is the request's already-sanitized `chat_template_kwargs`
2336/// (see [`resolve_template_kwargs`]).
2337pub(crate) fn prompt_from_messages(
2338    messages: &[ChatMessage],
2339    template: &chat_template::PromptTemplate,
2340    tools: &[ToolDef],
2341    extra: serde_json::Map<String, serde_json::Value>,
2342) -> Result<String, ApiError> {
2343    let rendered = if tools.is_empty() || template.handles_tools() {
2344        template.render(messages, tools, extra)
2345    } else {
2346        let mut with_preamble = Vec::with_capacity(messages.len() + 1);
2347        with_preamble.push(ChatMessage {
2348            role: "system".to_string(),
2349            content: Some(MessageContent::Text(tool_preamble(tools))),
2350            tool_calls: None,
2351            tool_call_id: None,
2352            reasoning_content: None,
2353        });
2354        with_preamble.extend_from_slice(messages);
2355        template.render(&with_preamble, &[], extra)
2356    };
2357    rendered.map_err(template_error_response)
2358}
2359
2360/// A template that will not render is a request failure, never a
2361/// fallback to a guessed one: serving a checkpoint framing it has never
2362/// seen is the exact bug `chat_template` exists to delete, so the
2363/// compiler's own message goes back to the caller instead.
2364fn template_error_response(err: ferrox_models::chat_template::TemplateError) -> ApiError {
2365    (
2366        StatusCode::BAD_REQUEST,
2367        Json(serde_json::json!({
2368            "error": {
2369                "message": format!("chat template failed to render: {err}"),
2370                "type": "invalid_request_error",
2371                "param": "messages",
2372                "code": null,
2373            }
2374        })),
2375    )
2376}
2377
2378/// Real, disclosed approach for tool-calling without grammar-
2379/// constrained decoding (which doesn't exist in this server):
2380/// describe each tool in plain text and ask the
2381/// model to wrap a call in a literal `<tool_call>{...}</tool_call>`
2382/// marker, then reuse the existing stop-sequence machinery (see
2383/// `ChatCompletionRequest::effective_stop_sequences`) to end
2384/// generation right after it, and parse the captured text for that
2385/// marker afterward (`output::parse_output`, which also accepts the
2386/// format the served checkpoint's own family emits). This is
2387/// stop-bounded,
2388/// prompt-engineered JSON extraction, not enforced-valid-JSON output --
2389/// a real limitation, not overclaimed.
2390fn tool_preamble(tools: &[ToolDef]) -> String {
2391    let mut out = String::from(
2392        "You can call tools to help answer the user. To call a tool, respond with \
2393         EXACTLY one line in this format and nothing else:\n\
2394         <tool_call>{\"name\": \"<tool name>\", \"arguments\": {<arguments as a JSON \
2395         object matching that tool's parameters>}}</tool_call>\n\n\
2396         Available tools:\n",
2397    );
2398    for t in tools {
2399        out.push_str(&format!(
2400            "- {}: {}\n  parameters (JSON schema): {}\n",
2401            t.function.name,
2402            t.function.description.as_deref().unwrap_or(""),
2403            t.function
2404                .parameters
2405                .as_ref()
2406                .map(|v| v.to_string())
2407                .unwrap_or_else(|| "{}".to_string()),
2408        ));
2409    }
2410    out
2411}
2412
2413/// Fold one batch of parser events into the text to stream and the
2414/// tool-call deltas to stream beside it.
2415///
2416/// `opened` counts calls that have gone out, which is both the wire
2417/// `index` and how the terminal chunk knows whether this generation
2418/// ended in a tool call. `CallEnd` deliberately emits nothing: every
2419/// byte of the arguments has already gone out as a fragment, and
2420/// repeating them would make a client that concatenates deltas produce
2421/// the arguments twice.
2422fn tool_call_deltas(
2423    events: Vec<crate::policy::parser::ToolCallEvent>,
2424    opened: &std::cell::Cell<usize>,
2425) -> (String, Vec<ToolCallDelta>) {
2426    let mut text = String::new();
2427    let mut deltas = Vec::new();
2428    for event in events {
2429        match event {
2430            crate::policy::parser::ToolCallEvent::Text(chunk) => text.push_str(&chunk),
2431            crate::policy::parser::ToolCallEvent::CallStart { index, name } => {
2432                opened.set(opened.get().max(index + 1));
2433                deltas.push(ToolCallDelta::opening(index, name));
2434            }
2435            crate::policy::parser::ToolCallEvent::CallArguments { index, fragment } => {
2436                if !fragment.is_empty() {
2437                    deltas.push(ToolCallDelta::arguments(index, fragment));
2438                }
2439            }
2440            crate::policy::parser::ToolCallEvent::CallEnd { .. } => {}
2441        }
2442    }
2443    (text, deltas)
2444}
2445
2446/// Builds the final response message + finish reason from raw
2447/// generated text.
2448///
2449/// Three things come out of the text: a reasoning block, when the
2450/// served checkpoint's family emits one; every tool call it made, in
2451/// whichever format it used; and whatever prose is left. `base_finish`
2452/// is promoted to `"tool_calls"` only when a call was actually found --
2453/// a model can answer in plain text despite tools being offered, and
2454/// that must fall through to an ordinary text response rather than an
2455/// error.
2456fn build_response_message(
2457    text: String,
2458    tools: &[ToolDef],
2459    posture: output::OutputPosture,
2460    base_finish: &'static str,
2461) -> (ChatCompletionResponseMessage, &'static str) {
2462    let parsed = output::parse_output(&text, tools, posture);
2463    let calls: Vec<ToolCallOut> = parsed
2464        .calls
2465        .into_iter()
2466        .enumerate()
2467        .map(|(index, call)| ToolCallOut {
2468            id: format!("call_{index}"),
2469            kind: "function",
2470            function: ToolCallFunctionOut {
2471                name: call.name,
2472                arguments: call.arguments,
2473            },
2474        })
2475        .collect();
2476    if !calls.is_empty() {
2477        return (
2478            ChatCompletionResponseMessage {
2479                role: "assistant",
2480                content: None,
2481                reasoning_content: parsed.reasoning,
2482                tool_calls: Some(calls),
2483            },
2484            "tool_calls",
2485        );
2486    }
2487    (
2488        ChatCompletionResponseMessage {
2489            role: "assistant",
2490            content: Some(parsed.content),
2491            reasoning_content: parsed.reasoning,
2492            tool_calls: None,
2493        },
2494        base_finish,
2495    )
2496}
2497
2498/// Resolves the full message history a prompt should be rendered
2499/// from: `req.messages` verbatim when no session is in play, or (see
2500/// `session` module) `req.messages` appended to `session_id`'s stored
2501/// history, returning the accumulated whole.
2502fn resolve_history(state: &AppState, req: &ChatCompletionRequest) -> Vec<ChatMessage> {
2503    let mut history = match &req.session_id {
2504        Some(id) => state.sessions.extend_and_get(id, &req.messages),
2505        None => req.messages.clone(),
2506    };
2507    if req.json_object_mode() {
2508        inject_json_object_system_hint(&mut history);
2509    }
2510    history
2511}
2512
2513fn inject_json_object_system_hint(messages: &mut Vec<ChatMessage>) {
2514    const HINT: &str =
2515        "You must respond with valid JSON only (a single JSON object, no markdown fences).";
2516    if let Some(sys) = messages.iter_mut().find(|m| m.role == "system") {
2517        match &mut sys.content {
2518            Some(MessageContent::Text(s)) if !s.contains("JSON") => {
2519                s.push_str("\n\n");
2520                s.push_str(HINT);
2521            }
2522            None => {
2523                sys.content = Some(MessageContent::Text(HINT.to_string()));
2524            }
2525            _ => {}
2526        }
2527    } else {
2528        messages.insert(
2529            0,
2530            ChatMessage {
2531                role: "system".to_string(),
2532                content: Some(MessageContent::Text(HINT.to_string())),
2533                tool_calls: None,
2534                tool_call_id: None,
2535                reasoning_content: None,
2536            },
2537        );
2538    }
2539}
2540
2541async fn chat_completions(
2542    State(state): State<Arc<AppState>>,
2543    headers: axum::http::HeaderMap,
2544    Json(req): Json<ChatCompletionRequest>,
2545) -> Response {
2546    let attribution = attribution::Attribution::from_headers(&headers);
2547    state
2548        .requests_total
2549        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2550    let started = std::time::Instant::now();
2551
2552    // One id per request, assigned before any work starts -- including
2553    // before validation -- so the streaming and non-streaming paths
2554    // agree and a rejected request is still nameable in the monitor.
2555    let request_id = ferrox_api::next_request_id();
2556    let stream = req.stream.unwrap_or(false);
2557
2558    // The maintenance gate comes before validation: while the cache is
2559    // being resized or the server is draining, the honest answer is
2560    // "not now" whichever fields the body carries, and admitting a
2561    // request into a pool that is being rebuilt under it is worse than
2562    // refusing one that would have 400'd anyway.
2563    let refusal = cache_admin::check_admission(&state)
2564        .err()
2565        .or_else(|| req.validate_supported_fields().err());
2566    if let Some(err) = refusal {
2567        state
2568            .request_errors_total
2569            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2570        let response = err.into_response();
2571        state.record_request(stats::Record {
2572            request_id: &request_id,
2573            route: ferrox_api::routes::V1_CHAT_COMPLETIONS,
2574            model: state.active_model_name(),
2575            status: response.status().as_u16(),
2576            stream,
2577            duration_ms: started.elapsed().as_millis() as u64,
2578            usage: None,
2579            attribution: &attribution,
2580        });
2581        return response;
2582    }
2583
2584    let response = if stream {
2585        chat_completions_stream(
2586            Arc::clone(&state),
2587            req,
2588            request_id.clone(),
2589            started,
2590            attribution.clone(),
2591        )
2592        .await
2593        .into_response()
2594    } else {
2595        chat_completions_full(
2596            Arc::clone(&state),
2597            req,
2598            request_id.clone(),
2599            started,
2600            attribution.clone(),
2601        )
2602        .await
2603        .into_response()
2604    };
2605
2606    if response.status().is_client_error() || response.status().is_server_error() {
2607        state
2608            .request_errors_total
2609            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2610        // Only failures are recorded here. A success has already
2611        // recorded itself from the path that knows the token counts --
2612        // and, for a stream, that has not even happened yet.
2613        state.record_request(stats::Record {
2614            request_id: &request_id,
2615            route: ferrox_api::routes::V1_CHAT_COMPLETIONS,
2616            // `None` here is the 503 case and says so: nothing was
2617            // loaded, so nothing served it.
2618            model: state.active_model_name(),
2619            status: response.status().as_u16(),
2620            stream,
2621            duration_ms: started.elapsed().as_millis() as u64,
2622            usage: None,
2623            attribution: &attribution,
2624        });
2625    }
2626    state.mark_request_finished();
2627
2628    response
2629}
2630
2631async fn chat_completions_full(
2632    state: Arc<AppState>,
2633    req: ChatCompletionRequest,
2634    request_id: String,
2635    started: std::time::Instant,
2636    attribution: attribution::Attribution,
2637) -> Result<Json<ChatCompletionResponse>, ApiError> {
2638    let tools_active = req.tools_active();
2639    // Cloned once, up front: this request decodes against exactly this
2640    // model even if `/admin/models/load` swaps a different one in
2641    // halfway through (see `AppState::active`).
2642    let active = state.require_active()?;
2643    let history = resolve_history(&state, &req);
2644    let template = active.model.chat_template();
2645    let kwargs = req.resolve_template_kwargs(&template);
2646    let prompt = prompt_from_messages(&history, &template, &req.tools, kwargs)?;
2647    let key = req.is_cacheable().then(|| req.cache_key(&prompt));
2648
2649    let (completion, cache_status) = if let Some(cached) = key
2650        .as_ref()
2651        .and_then(|key| lock_cache(&state.response_cache).get(key))
2652    {
2653        tracing::debug!("cache hit for key {}", key.as_ref().unwrap().digest());
2654        (cached, "hit")
2655    } else {
2656        let model = Arc::clone(&active.model);
2657        let kv_pool = state.kv_pool.clone();
2658        let paged_kv = state.paged_kv.clone();
2659        let prefix_cache = state.prefix_cache.clone();
2660        let batcher = active.batcher.clone();
2661        let ceiling = active.ceiling.clone();
2662        let params = req.generation_params_for_template(&template);
2663        let prompt_for_task = prompt.clone();
2664        let (chunks, finish, usage) = tokio::task::spawn_blocking(move || {
2665            run_generation(
2666                &model,
2667                &prompt_for_task,
2668                &params,
2669                kv_pool.as_ref(),
2670                paged_kv.as_ref(),
2671                prefix_cache.as_deref(),
2672                batcher.as_ref(),
2673                ceiling.as_deref(),
2674            )
2675        })
2676        .await
2677        .map_err(join_error_response)?
2678        .map_err(decode_error_response)?;
2679
2680        let completion = response_cache::CachedCompletion {
2681            content: chunks.concat(),
2682            finish,
2683            usage,
2684        };
2685        let cache_status = if let Some(key) = key {
2686            tracing::debug!("cache miss for key {}", key.digest());
2687            lock_cache(&state.response_cache).put(key, completion.clone());
2688            "miss"
2689        } else {
2690            "skip"
2691        };
2692        (completion, cache_status)
2693    };
2694    let content = completion.content;
2695
2696    if req.json_object_mode() {
2697        json_mode::validate_json_object_output(&content)?;
2698    }
2699
2700    // Stored regardless of cache hit/miss, so a session's history is
2701    // always consistent with what a client would see, whether or not
2702    // this exact prompt happened to be served from cache.
2703    if let Some(id) = &req.session_id {
2704        state.sessions.store_reply(
2705            id,
2706            ChatMessage {
2707                role: "assistant".to_string(),
2708                content: Some(MessageContent::Text(content.clone())),
2709                tool_calls: None,
2710                tool_call_id: None,
2711                reasoning_content: None,
2712            },
2713        );
2714    }
2715
2716    let (message, finish_reason) = build_response_message(
2717        content,
2718        if tools_active { &req.tools } else { &[] },
2719        output::OutputPosture::resolve(active.model.name(), &prompt),
2720        completion.finish.as_str(),
2721    );
2722
2723    state.record_request(stats::Record {
2724        request_id: &request_id,
2725        route: ferrox_api::routes::V1_CHAT_COMPLETIONS,
2726        // The handle this request decoded against, not `req.model`: a
2727        // swap mid-flight does not change which weights answered.
2728        model: Some(active.model.name().to_string()),
2729        status: 200,
2730        stream: false,
2731        duration_ms: started.elapsed().as_millis() as u64,
2732        usage: Some(&completion.usage),
2733        attribution: &attribution,
2734    });
2735
2736    Ok(Json(ChatCompletionResponse {
2737        id: request_id.clone(),
2738        request_id,
2739        object: "chat.completion",
2740        model: req.model,
2741        choices: vec![ChatCompletionChoice {
2742            index: 0,
2743            message,
2744            finish_reason,
2745        }],
2746        usage: completion.usage,
2747        ferrox_cache: cache_status,
2748    }))
2749}
2750
2751async fn chat_completions_stream(
2752    state: Arc<AppState>,
2753    req: ChatCompletionRequest,
2754    request_id: String,
2755    started: std::time::Instant,
2756    attribution: attribution::Attribution,
2757) -> Result<Response, ApiError> {
2758    // Streaming requests are never served from or written to the response cache.
2759    let tools_active = req.tools_active();
2760    // See `chat_completions_full`: the handle is taken once and the
2761    // whole stream runs against it, so a mid-stream model swap cannot
2762    // splice two checkpoints into one completion.
2763    let active = state.require_active()?;
2764    let history = resolve_history(&state, &req);
2765    let template = active.model.chat_template();
2766    let kwargs = req.resolve_template_kwargs(&template);
2767    let prompt = prompt_from_messages(&history, &template, &req.tools, kwargs)?;
2768    let model_name = req.model.clone();
2769    let session_id = req.session_id.clone();
2770    let sessions = state.sessions.clone();
2771
2772    let model = Arc::clone(&active.model);
2773    let kv_pool = state.kv_pool.clone();
2774    let paged_kv = state.paged_kv.clone();
2775    let prefix_cache = state.prefix_cache.clone();
2776    let batcher = active.batcher.clone();
2777    let ceiling = active.ceiling.clone();
2778    let mut params = req.generation_params_for_template(&template);
2779    let stats_state = Arc::clone(&state);
2780    // Read now, off the handle this stream will decode against. Read
2781    // later it would name whatever a swap had made current by then.
2782    let served_model = active.model.name().to_string();
2783    // How to read this stream, fixed before the first token: the family
2784    // from the served checkpoint, and whether the prompt that was
2785    // actually rendered left the model inside a reasoning block.
2786    let posture = output::OutputPosture::resolve(&served_model, &prompt);
2787    // The offered tools, captured for the terminal parse: the request
2788    // itself does not outlive the closure that consumes it.
2789    let offered_tools: Vec<ToolDef> = if tools_active {
2790        req.tools.clone()
2791    } else {
2792        Vec::new()
2793    };
2794
2795    // Tier two of cancellation: the id is already on the wire, so the
2796    // client can name it. The guard rides with the generation task and
2797    // deregisters however that task ends, panic included -- see the
2798    // `cancel` module.
2799    let (cancel_token, cancel_guard) = state.cancels.register(&request_id);
2800    params.cancel = Some(cancel_token.clone());
2801
2802    // Tool-call detection needs the full stop-bounded text; continuous
2803    // batching returns one string. Both stay buffered. Otherwise each
2804    // decoded chunk is pushed on a channel for overlapped SSE delivery.
2805    // Incremental streaming, including when tools are offered. It used
2806    // to be `!tools_active && ...`: finding a tool call needed the
2807    // whole text. `crate::policy::parser::ToolCallParser` streams prefix-stable
2808    // argument fragments, so that reason is gone, and a coding agent
2809    // now watches an argument arrive instead of waiting for it.
2810    let overlap = batcher.is_none();
2811
2812    // Opt-in replay. Registering a buffer is also what decides whether a
2813    // dropped socket cancels this generation -- see `resume`'s module
2814    // doc for why that is the caller's call and not the server's.
2815    let slot = req
2816        .stream_resumable
2817        .unwrap_or(false)
2818        .then(|| state.streams.register(&request_id));
2819    let emitter = resume::Emitter::new(slot);
2820
2821    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);
2822    // Built here, where the id and model name are still owned by this
2823    // frame: the generation task takes both. Serialized once, because
2824    // it is byte-identical every time it goes out.
2825    let keepalive = sse::keepalive_event(&ChatCompletionChunk {
2826        id: request_id.clone(),
2827        request_id: None,
2828        object: "chat.completion.chunk",
2829        model: model_name.clone(),
2830        choices: vec![ChatCompletionChunkChoice {
2831            index: 0,
2832            delta: ChatCompletionChunkDelta {
2833                role: None,
2834                content: None,
2835                reasoning_content: None,
2836                tool_calls: None,
2837            },
2838            finish_reason: None,
2839        }],
2840        usage: None,
2841    });
2842
2843    tokio::task::spawn_blocking(move || {
2844        // Held for the whole generation; dropping it is what takes the
2845        // id back out of the cancel registry.
2846        let _cancel_guard = cancel_guard;
2847        let tx_chunks = tx.clone();
2848        // The orphan deadline (see `crate::sse`): a client that is
2849        // neither reading nor disconnected must not park this blocking
2850        // thread -- and the model handle and cancel guard it holds --
2851        // for the life of the process.
2852        let orphan_timeout = sse::orphan_timeout_from_env();
2853        let mut first = true;
2854        let head_request_id = request_id.clone();
2855        // The chain-of-thought split, applied as the tokens arrive
2856        // rather than at the end. Without this an overlapped stream --
2857        // which is the default for a reasoning model with no tools --
2858        // would deliver the whole thinking block as `content` and then
2859        // the buffered path would deliver the same request's thinking
2860        // as `reasoning_content`, so the same question would answer
2861        // differently depending on a transport detail. Shared with the
2862        // terminal flush below, which releases whatever the parser is
2863        // still withholding against a marker that never arrived.
2864        let stream_reasoning: Rc<RefCell<Option<crate::policy::parser::ReasoningParser>>> =
2865            Rc::new(RefCell::new(posture.reasoning_parser()));
2866        let emit_reasoning = Rc::clone(&stream_reasoning);
2867        // The tool-call parser, fed whatever the reasoning parser
2868        // classified as content. Absent when the request offered no
2869        // tools, in which case marker-looking text is just text.
2870        let stream_tools: Rc<RefCell<Option<crate::policy::parser::ToolCallParser>>> = Rc::new(
2871            RefCell::new(tools_active.then(|| posture.tool_call_parser(&offered_tools))),
2872        );
2873        let emit_tools = Rc::clone(&stream_tools);
2874        // How many calls have been opened on the wire, so the terminal
2875        // chunk knows whether to say `tool_calls` and does not repeat
2876        // what already went out.
2877        let streamed_calls = Rc::new(std::cell::Cell::new(0usize));
2878        let emit_streamed_calls = Rc::clone(&streamed_calls);
2879        let result = run_generation_emit(
2880            &model,
2881            &prompt,
2882            &params,
2883            kv_pool.as_ref(),
2884            paged_kv.as_ref(),
2885            prefix_cache.as_deref(),
2886            batcher.as_ref(),
2887            ceiling.as_deref(),
2888            |chunk| {
2889                if !overlap || chunk.is_empty() {
2890                    return;
2891                }
2892                let (reasoning, content) = match emit_reasoning.borrow_mut().as_mut() {
2893                    Some(parser) => {
2894                        let delta = parser.push(chunk);
2895                        (delta.reasoning, delta.content)
2896                    }
2897                    None => (String::new(), chunk.to_string()),
2898                };
2899                // Content goes through the tool parser, which holds
2900                // back anything that could still become a marker and
2901                // turns a recognized call into wire deltas.
2902                let (content, tool_calls) = match emit_tools.borrow_mut().as_mut() {
2903                    Some(parser) => {
2904                        let (text, calls) =
2905                            tool_call_deltas(parser.push(&content), &emit_streamed_calls);
2906                        (text, calls)
2907                    }
2908                    None => (content, Vec::new()),
2909                };
2910                // Both parsers withhold partial markers, so a chunk can
2911                // legitimately produce nothing at all this time round.
2912                if reasoning.is_empty() && content.is_empty() && tool_calls.is_empty() {
2913                    return;
2914                }
2915                let role = if first { Some("assistant") } else { None };
2916                let request_id = first.then(|| head_request_id.clone());
2917                first = false;
2918                let payload = ChatCompletionChunk {
2919                    id: head_request_id.clone(),
2920                    request_id,
2921                    object: "chat.completion.chunk",
2922                    model: model_name.clone(),
2923                    choices: vec![ChatCompletionChunkChoice {
2924                        index: 0,
2925                        delta: ChatCompletionChunkDelta {
2926                            role,
2927                            content: (!content.is_empty()).then_some(content),
2928                            reasoning_content: (!reasoning.is_empty()).then_some(reasoning),
2929                            tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
2930                        },
2931                        finish_reason: None,
2932                    }],
2933                    usage: None,
2934                };
2935                // Tier one of cancellation. A failed send means the SSE
2936                // receiver is gone -- the browser tab closed, the
2937                // client aborted, the connection dropped -- and until
2938                // this was checked the return value was discarded and
2939                // the decode loop happily generated the remaining
2940                // hundreds of tokens into nothing. Flipping the same
2941                // flag `/v1/cancel` sets means there is one stop path,
2942                // not two.
2943                if let Err(why) =
2944                    sse::send_or_orphan(&tx_chunks, Ok(emitter.event(&payload)), orphan_timeout)
2945                {
2946                    if why == sse::SendFailure::Orphaned {
2947                        tracing::warn!(
2948                            "SSE stream {head_request_id} accepted nothing for the orphan \
2949                             deadline; treating it as abandoned"
2950                        );
2951                    }
2952                    // Two features met here and only one of them may
2953                    // win. The orphan deadline exists to stop work
2954                    // nobody is reading. A resumable stream is exactly
2955                    // the case where a gone receiver must NOT stop the
2956                    // work: the client said it may come back, the
2957                    // buffer is still being filled for it, and
2958                    // cancelling would make every reconnect resume into
2959                    // a truncated answer. So the deadline still detects
2960                    // and logs, and only a non-resumable stream is
2961                    // cancelled by it. `POST /v1/cancel` is the stop
2962                    // path for the resumable ones.
2963                    if !emitter.is_resumable() {
2964                        cancel_token.cancel();
2965                    }
2966                }
2967            },
2968        );
2969
2970        // `first` is still true when nothing was streamed from the emit
2971        // closure (the buffered tool-call/batching path, or an empty
2972        // generation), so the id has not gone out yet. `take()` on the
2973        // way into each payload below guarantees it is announced
2974        // exactly once, on whichever chunk really is first.
2975        let mut pending_request_id = first.then(|| request_id.clone());
2976
2977        match result {
2978            Ok((finish, usage, full_text)) => {
2979                if let Some(id) = &session_id {
2980                    sessions.store_reply(
2981                        id,
2982                        ChatMessage {
2983                            role: "assistant".to_string(),
2984                            content: Some(MessageContent::Text(full_text.clone())),
2985                            tool_calls: None,
2986                            tool_call_id: None,
2987                            reasoning_content: None,
2988                        },
2989                    );
2990                }
2991                // Both parsers may still be holding a run that could
2992                // have become a marker and did not. It is ordinary
2993                // output; dropping it would truncate every answer whose
2994                // tail happens to look like the start of a `</think>`
2995                // or a `<tool_call>`.
2996                let mut streamed_finish: Option<&'static str> = None;
2997                if overlap {
2998                    let tail = stream_reasoning
2999                        .borrow_mut()
3000                        .as_mut()
3001                        .map(|parser| parser.flush())
3002                        .unwrap_or_default();
3003                    let (mut content, mut tool_calls) = (tail.content, Vec::new());
3004                    if let Some(parser) = stream_tools.borrow_mut().as_mut() {
3005                        let mut events = parser.push(&content);
3006                        events.extend(parser.finish());
3007                        let (text, calls) = tool_call_deltas(events, &streamed_calls);
3008                        content = text;
3009                        tool_calls = calls;
3010                    }
3011                    if !content.is_empty() || !tail.reasoning.is_empty() || !tool_calls.is_empty() {
3012                        let payload = ChatCompletionChunk {
3013                            id: request_id.clone(),
3014                            request_id: pending_request_id.take(),
3015                            object: "chat.completion.chunk",
3016                            model: model_name.clone(),
3017                            choices: vec![ChatCompletionChunkChoice {
3018                                index: 0,
3019                                delta: ChatCompletionChunkDelta {
3020                                    role: None,
3021                                    content: (!content.is_empty()).then_some(content),
3022                                    reasoning_content: (!tail.reasoning.is_empty())
3023                                        .then_some(tail.reasoning),
3024                                    tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3025                                },
3026                                finish_reason: None,
3027                            }],
3028                            usage: None,
3029                        };
3030                        let _ =
3031                            sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3032                    }
3033                    if streamed_calls.get() > 0 {
3034                        streamed_finish = Some("tool_calls");
3035                    }
3036                } else {
3037                    // The batched path had no incremental stream to
3038                    // ride on, so the whole answer goes out at once.
3039                    let parsed = output::parse_output(&full_text, &offered_tools, posture);
3040                    let tool_calls: Vec<ToolCallDelta> = parsed
3041                        .calls
3042                        .iter()
3043                        .enumerate()
3044                        .map(|(index, call)| {
3045                            ToolCallDelta::whole(index, call.name.clone(), call.arguments.clone())
3046                        })
3047                        .collect();
3048                    if !tool_calls.is_empty() {
3049                        streamed_finish = Some("tool_calls");
3050                    }
3051                    if !tool_calls.is_empty()
3052                        || !parsed.content.is_empty()
3053                        || parsed.reasoning.is_some()
3054                    {
3055                        let payload = ChatCompletionChunk {
3056                            id: request_id.clone(),
3057                            request_id: pending_request_id.take(),
3058                            object: "chat.completion.chunk",
3059                            model: model_name.clone(),
3060                            choices: vec![ChatCompletionChunkChoice {
3061                                index: 0,
3062                                delta: ChatCompletionChunkDelta {
3063                                    role: Some("assistant"),
3064                                    content: (!parsed.content.is_empty() && tool_calls.is_empty())
3065                                        .then(|| parsed.content.clone()),
3066                                    reasoning_content: parsed.reasoning.clone(),
3067                                    tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3068                                },
3069                                finish_reason: None,
3070                            }],
3071                            usage: None,
3072                        };
3073                        let _ =
3074                            sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3075                    }
3076                }
3077                // A truncated generation is `length` even if it managed
3078                // to open a call: the client must not treat a
3079                // half-written call as one it should execute.
3080                let final_finish_reason = match streamed_finish {
3081                    Some(reason) if finish.as_str() != "length" => reason,
3082                    _ => finish.as_str(),
3083                };
3084                let final_payload = ChatCompletionChunk {
3085                    id: request_id.clone(),
3086                    request_id: pending_request_id.take(),
3087                    object: "chat.completion.chunk",
3088                    model: model_name,
3089                    choices: vec![ChatCompletionChunkChoice {
3090                        index: 0,
3091                        delta: ChatCompletionChunkDelta {
3092                            role: None,
3093                            content: None,
3094                            reasoning_content: None,
3095                            tool_calls: None,
3096                        },
3097                        finish_reason: Some(final_finish_reason),
3098                    }],
3099                    usage: Some(usage.clone()),
3100                };
3101                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&final_payload)), orphan_timeout);
3102                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3103                // Recorded here rather than where the handler returned:
3104                // the handler returns as soon as the SSE headers go out,
3105                // which is before a single token exists, so timing it
3106                // there would report every stream as instant.
3107                stats_state.record_request(stats::Record {
3108                    request_id: &request_id,
3109                    route: ferrox_api::routes::V1_CHAT_COMPLETIONS,
3110                    model: Some(served_model.clone()),
3111                    status: 200,
3112                    stream: true,
3113                    duration_ms: started.elapsed().as_millis() as u64,
3114                    usage: Some(&usage),
3115                    attribution: &attribution,
3116                });
3117            }
3118            Err(e) => {
3119                tracing::warn!("decode error on streamed request {request_id}: {e}");
3120                // The socket carried 200 -- SSE headers precede the
3121                // first token -- but the request produced no completion.
3122                // The monitor records outcomes, and a 200 row with zero
3123                // tokens would read as a successful empty answer, so the
3124                // failure is stated as 500 here and only here.
3125                stats_state.record_request(stats::Record {
3126                    request_id: &request_id,
3127                    route: ferrox_api::routes::V1_CHAT_COMPLETIONS,
3128                    model: Some(served_model.clone()),
3129                    status: 500,
3130                    stream: true,
3131                    duration_ms: started.elapsed().as_millis() as u64,
3132                    usage: None,
3133                    attribution: &attribution,
3134                });
3135                let payload = ChatCompletionChunk {
3136                    id: request_id.clone(),
3137                    request_id: pending_request_id.take(),
3138                    object: "chat.completion.chunk",
3139                    model: model_name,
3140                    choices: vec![ChatCompletionChunkChoice {
3141                        index: 0,
3142                        delta: ChatCompletionChunkDelta {
3143                            role: Some("assistant"),
3144                            content: Some(format!("[error: {e}]")),
3145                            reasoning_content: None,
3146                            tool_calls: None,
3147                        },
3148                        finish_reason: Some("stop"),
3149                    }],
3150                    usage: None,
3151                };
3152                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3153                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3154            }
3155        }
3156        // The buffer is closed by dropping `emitter` here -- including
3157        // on a panic, which is the case an explicit call would miss.
3158        // See `resume::Emitter`'s `Drop`.
3159        drop(emitter);
3160    });
3161
3162    let stream = sse::with_keepalive(rx, keepalive, sse::KEEPALIVE_INTERVAL);
3163    // `X-Accel-Buffering: no` is the one header that actually reaches
3164    // the problem the plan names: nginx (and the proxies that copied
3165    // its convention) buffer `text/event-stream` by default, which
3166    // turns a token-by-token stream into one silent wait followed by
3167    // the whole answer at once -- indistinguishable, from the browser,
3168    // from a hung backend. axum already sets `Cache-Control: no-cache`
3169    // on an `Sse` response, so that half is covered.
3170    //
3171    // The keepalive every 15s is the other half: it gives an
3172    // idle-but-healthy stream something to send, so a client's stall
3173    // timeout measures the *connection* rather than the model's
3174    // time-to-first-token on a long prompt.
3175    //
3176    // **Not `Sse::keep_alive`.** axum's keepalive is an SSE COMMENT,
3177    // and a comment does not reach a client's event handler -- codex's
3178    // 300s stream-idle timeout only resets on a data frame, so a
3179    // comment-kept stream is reconnected mid-answer on a long prefill.
3180    // `sse::with_keepalive` sends a real `chat.completion.chunk` with
3181    // an empty delta instead: a concatenating client adds nothing, and
3182    // the transport sees traffic. It also covers the silence BEFORE
3183    // the first token, which is exactly the queue-wait and long-prefill
3184    // window where this matters most.
3185    Ok((
3186        [(
3187            axum::http::HeaderName::from_static("x-accel-buffering"),
3188            axum::http::HeaderValue::from_static("no"),
3189        )],
3190        Sse::new(stream),
3191    )
3192        .into_response())
3193}
3194
3195/// The axum pattern for one of the published path templates.
3196///
3197/// `ferrox_api::routes` writes placeholders in the OpenAPI style
3198/// because it is imported by clients that have never heard of this
3199/// server's router; axum 0.7 wants `:name`. Converting here keeps one
3200/// published spelling and one router spelling, and the test below fails
3201/// if they ever stop describing the same path.
3202///
3203/// This rewrites EVERY `{name}` it finds rather than one known
3204/// placeholder. The narrow version took `{request_id}` only, so the two
3205/// Responses templates were mounted with their braces intact and axum
3206/// read `{response_id}` as a literal segment: `GET /v1/responses/abc`
3207/// matched no route and got axum's bodiless 404 instead of the
3208/// handler's, and the one path that did match would have panicked on
3209/// `MissingPathParams`. Anything with a placeholder must go through
3210/// here.
3211fn axum_path(template: &str) -> String {
3212    let mut out = String::with_capacity(template.len());
3213    let mut rest = template;
3214    while let Some(open) = rest.find('{') {
3215        let Some(close) = rest[open..].find('}').map(|c| open + c) else {
3216            break;
3217        };
3218        out.push_str(&rest[..open]);
3219        out.push(':');
3220        out.push_str(&rest[open + 1..close]);
3221        rest = &rest[close + 1..];
3222    }
3223    out.push_str(rest);
3224    out
3225}
3226
3227/// `POST /v1/cancel` -- the explicit half of two-tier cancellation.
3228///
3229/// Answers `200` when a live generation was signalled and `404` when
3230/// the id names nothing that is running. That difference is the whole
3231/// point of the endpoint returning a body at all: "already finished"
3232/// and "stopped it" are both fine outcomes, but only one of them saved
3233/// any work, and a UI told `ok: true` for both will claim it stopped
3234/// something it did not.
3235async fn cancel_generation(
3236    State(state): State<Arc<AppState>>,
3237    Json(req): Json<ferrox_api::CancelGenerationRequest>,
3238) -> Response {
3239    let cancelled = state.cancels.cancel(&req.request_id);
3240    let status = if cancelled {
3241        StatusCode::OK
3242    } else {
3243        StatusCode::NOT_FOUND
3244    };
3245    let detail = if cancelled {
3246        "the generation was asked to stop; it ends at its next token".to_string()
3247    } else {
3248        "no generation with that request_id is running -- it has already \
3249         finished, was never issued, or was served by a path that does \
3250         not register for cancellation"
3251            .to_string()
3252    };
3253    (
3254        status,
3255        Json(ferrox_api::CancelGenerationResponse {
3256            request_id: req.request_id,
3257            cancelled,
3258            detail,
3259        }),
3260    )
3261        .into_response()
3262}
3263
3264/// What a freshly loaded checkpoint becomes when it is published as the
3265/// active model: the model itself, its optional continuous-batching
3266/// worker, and the context ceiling both decode paths admit on.
3267type Activated = (
3268    Model,
3269    Option<serving::batch::ContinuousBatcher>,
3270    Option<Arc<budget::ContextCeiling>>,
3271);
3272
3273/// The scheduler config for a freshly loaded GGUF, with the ceilings an
3274/// operator did not configure *derived* from the checkpoint instead of
3275/// left absent.
3276///
3277/// This is the server half of `mem-preload-kv-budget`: `ferrox run`
3278/// already priced weights + `n_ctx * per_token_kv` + headroom against
3279/// the device budget before loading, while `ferrox-server` admitted on
3280/// whatever `FERROX_CB_*` happened to be set and otherwise on nothing.
3281///
3282/// Precedence is one-directional and deliberate: an explicit
3283/// `FERROX_CB_MAX_CONTEXT` / `FERROX_CB_KV_BLOCKS` is never overridden,
3284/// because an operator who names a number has information this
3285/// arithmetic does not. Derivation only ever fills an *absent* ceiling,
3286/// where the alternative is no ceiling at all.
3287///
3288/// `path` is `None` for the synthetic-weights fallback, which has no
3289/// checkpoint on disk to price.
3290fn price_batcher_config(path: Option<&str>) -> serving::batch::BatcherConfig {
3291    let mut batcher = serving::batch::BatcherConfig::from_env();
3292    if batcher.max_context.is_some() && batcher.kv_blocks.is_some() {
3293        // Nothing left to derive, and pricing the checkpoint would only
3294        // print arithmetic that decides nothing.
3295        return batcher;
3296    }
3297    let Some(path) = path else {
3298        return batcher;
3299    };
3300    // `ferrox_core::cache::KvCache` is `Vec<f32>` on both decode paths,
3301    // so f32 is the width really kept, even under Metal attention where
3302    // the *device* also holds an f16 copy. Budgeting the host store is
3303    // the conservative reading: it over-charges KV and therefore
3304    // under-states the context that fits.
3305    let priced = budget::price_gguf(path, ferrox_models::KvElem::F32, 1, 1);
3306    let Some((priced, gguf_ctx, source)) = priced else {
3307        return batcher;
3308    };
3309    let Some(derived) = budget::derive_limits(&priced, gguf_ctx, batcher.kv_block_size) else {
3310        // See `budget`'s module doc: a fit of zero tokens is not a
3311        // ceiling of zero, it is an estimate saying this model should
3312        // not have loaded -- and it did. Say so and admit as before.
3313        tracing::warn!(
3314            "this checkpoint's weights leave no room for KV inside the {source}: {} weight \
3315             bytes against a {} byte budget. Serving with no derived context ceiling -- set \
3316             FERROX_DEVICE_BUDGET_BYTES if the probe is wrong, or FERROX_CB_MAX_CONTEXT to \
3317             admit on a number you choose.",
3318            priced.weights_bytes,
3319            priced.device_budget_bytes,
3320        );
3321        return batcher;
3322    };
3323    tracing::info!("{source}");
3324    tracing::info!("{}", derived.fit);
3325    let adopted = budget::apply_derived(&mut batcher, &derived);
3326    if adopted.max_context {
3327        tracing::info!(
3328            "derived per-request context ceiling: {} token positions (prompt + max_tokens); \
3329             override with FERROX_CB_MAX_CONTEXT",
3330            derived.max_context
3331        );
3332    }
3333    if adopted.kv_blocks {
3334        tracing::info!(
3335            "derived KV block budget: {} blocks x {} positions; override with FERROX_CB_KV_BLOCKS",
3336            derived.kv_blocks,
3337            batcher.kv_block_size
3338        );
3339    }
3340    batcher
3341}
3342
3343/// Turns a freshly loaded checkpoint into the parts that get published
3344/// as the active model.
3345///
3346/// Extracted from `build_app_state` so `/admin/models/load` builds its
3347/// replacement exactly the way startup builds the first one -- a second
3348/// copy of this match would be a second place for a new engine variant
3349/// to be forgotten, and the difference would only show up as a model
3350/// that silently loses continuous batching after a swap.
3351pub(crate) fn activate_loaded_model(
3352    loaded: model::LoadedModel,
3353    enable_continuous_batching: bool,
3354    path: Option<&str>,
3355    paged_kv: Option<&generate::PagedKvConfig>,
3356) -> Activated {
3357    match loaded {
3358        model::LoadedModel::Gguf(g) => {
3359            let decoder = Arc::new(g.decoder);
3360            let tokenizer = Arc::new(g.tokenizer);
3361            let config = price_batcher_config(path);
3362            // Prefill is still a per-token `forward_token` loop on both
3363            // paths (see `sched-chunked-prefill`: chunking bought
3364            // fairness, not a batched prefill kernel), so a sliding
3365            // layer really does need only `window + 1 - 1` positions
3366            // live. `chunk = 1` here is the truth, not a simplification.
3367            let shape =
3368                ferrox_models::KvShape::from_config(&decoder.config, ferrox_models::KvElem::F32, 1);
3369            let ceiling = Arc::new(budget::ContextCeiling::new(config.max_context, shape));
3370            let batcher = if enable_continuous_batching {
3371                tracing::info!(
3372                    "continuous batching enabled: decode steps share Decoder::forward_multi_seq \
3373                     (stop sequences use the same pending-buffer trim as the private generate loop)"
3374                );
3375                let tok = Arc::clone(&tokenizer);
3376                let decode = Arc::new(move |ids: &[usize]| tok.decode(ids));
3377                Some(serving::batch::ContinuousBatcher::spawn_with_ceiling(
3378                    Arc::clone(&decoder),
3379                    decode,
3380                    config,
3381                    Arc::clone(&ceiling),
3382                    paged_kv.cloned(),
3383                ))
3384            } else {
3385                None
3386            };
3387            (
3388                Model::Gguf(GgufModel {
3389                    decoder,
3390                    tokenizer,
3391                    stop_tokens: g.stop_tokens,
3392                    bos_id: g.bos_id,
3393                    is_synthetic: g.is_synthetic,
3394                    chat_template: g.chat_template,
3395                }),
3396                batcher,
3397                Some(ceiling),
3398            )
3399        }
3400        model::LoadedModel::Kimi(k) => (
3401            Model::Kimi(KimiModel {
3402                engine: k.engine,
3403                tokenizer: k.tokenizer,
3404                stop_tokens: k.stop_tokens,
3405                chat_template: k.chat_template,
3406            }),
3407            None,
3408            None,
3409        ),
3410        model::LoadedModel::Mla(m) => (
3411            Model::Mla(MlaModel {
3412                engine: m.engine,
3413                tokenizer: m.tokenizer,
3414                stop_tokens: m.stop_tokens,
3415                bos_id: m.bos_id,
3416                name: m.name,
3417                chat_template: m.chat_template,
3418            }),
3419            None,
3420            None,
3421        ),
3422        model::LoadedModel::Gemma4(m) => (
3423            Model::Gemma4(Gemma4Model {
3424                engine: m.engine,
3425                tokenizer: m.tokenizer,
3426                stop_tokens: m.stop_tokens,
3427                bos_id: m.bos_id,
3428                name: m.name,
3429                chat_template: m.chat_template,
3430            }),
3431            None,
3432            None,
3433        ),
3434        model::LoadedModel::Glm52(g) => (
3435            Model::Glm52(Glm52Model {
3436                engine: g.engine,
3437                tokenizer: g.tokenizer,
3438                stop_tokens: g.stop_tokens,
3439                bos_id: g.bos_id,
3440                name: g.name,
3441                chat_template: g.chat_template,
3442            }),
3443            None,
3444            None,
3445        ),
3446    }
3447}
3448
3449fn build_app_state(
3450    loaded: model::LoadedModel,
3451    kv_pool: Option<generate::KvPoolConfig>,
3452    paged_kv: Option<generate::PagedKvConfig>,
3453    prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
3454    enable_continuous_batching: bool,
3455    mcp: Option<mcp::LoadedMcpConfig>,
3456    detection: Arc<health::Detection>,
3457) -> AppState {
3458    let (model, batcher, ceiling) = activate_loaded_model(
3459        loaded,
3460        enable_continuous_batching,
3461        std::env::var("FERROX_MODEL_PATH").ok().as_deref(),
3462        paged_kv.as_ref(),
3463    );
3464    // The startup model's admin id is whichever discovered entry sits
3465    // at the configured path; `None` when it was not discovered (the
3466    // synthetic fallback, or a path outside the scanned directories),
3467    // in which case `/admin/models` reports nothing as active rather
3468    // than inventing an id no `load` request could name.
3469    let id = startup_model_id();
3470    AppState {
3471        active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
3472            id,
3473            model: Arc::new(model),
3474            batcher,
3475            ceiling,
3476        }))),
3477        paged_kv,
3478        load_in_progress: std::sync::atomic::AtomicBool::new(false),
3479        tasks: Arc::new(tasks::TaskRegistry::new()),
3480        cancels: Arc::new(cancel::CancelRegistry::new()),
3481        stats: stats::Stats::new(),
3482        streams: resume::StreamRegistry::new(),
3483        model_dir: admin::model_dirs().into_iter().next(),
3484        response_cache: Mutex::new(ResponseCache::new(1000, Duration::from_secs(3600))),
3485        kv_pool,
3486        prefix_cache,
3487        sessions: session::SessionStore::new(),
3488        requests_total: std::sync::atomic::AtomicU64::new(0),
3489        request_errors_total: std::sync::atomic::AtomicU64::new(0),
3490        started_at: std::time::Instant::now(),
3491        last_request_ms: std::sync::atomic::AtomicU64::new(0),
3492        detection,
3493        mcp,
3494        continuous_batching_enabled: enable_continuous_batching,
3495        loading_model: Mutex::new(None),
3496        last_load_error: Mutex::new(None),
3497        serving: Mutex::new(crate::stats::ServingStats::default()),
3498        maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
3499        footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
3500        started_unix: unix_now(),
3501    }
3502}
3503
3504/// Seconds since the epoch, or zero on a machine whose clock is set
3505/// before it. Only ever used to make an id distinct between process
3506/// generations, so a nonsense clock costs distinctness and nothing
3507/// else.
3508fn unix_now() -> u64 {
3509    std::time::SystemTime::now()
3510        .duration_since(std::time::UNIX_EPOCH)
3511        .map(|d| d.as_secs())
3512        .unwrap_or(0)
3513}
3514
3515/// The `/admin/models` id of the checkpoint `FERROX_MODEL_PATH` names,
3516/// when discovery finds it. Matching on the resolved path rather than
3517/// on the filename keeps two same-named files in different directories
3518/// from claiming each other's id.
3519fn startup_model_id() -> Option<String> {
3520    let configured = std::env::var("FERROX_MODEL_PATH").ok()?;
3521    let configured = std::fs::canonicalize(&configured).ok()?;
3522    admin::discover(&admin::model_dirs())
3523        .into_iter()
3524        .find(|d| {
3525            std::fs::canonicalize(&d.path)
3526                .map(|p| p == configured)
3527                .unwrap_or(false)
3528        })
3529        .map(|d| d.id)
3530}
3531
3532/// Builds the global rayon pool up front, on the main thread, with an
3533/// explicit width and QoS (see [`ferrox_core::threads`]).
3534///
3535/// Doing this from `main` rather than letting rayon build lazily is the
3536/// point: the first rayon call inside this server happens on a Tokio
3537/// `spawn_blocking` thread, so the workers used to inherit that thread's
3538/// QoS class -- which on macOS decides whether they land on performance
3539/// or efficiency cores.
3540fn init_cpu_pool() {
3541    match ferrox_core::threads::init_cpu_pool() {
3542        Some(n) => eprintln!(
3543            "ferrox-server: rayon pool {n} threads (perf cores {}; override with FERROX_CPU_THREADS)",
3544            ferrox_core::threads::perf_core_count()
3545        ),
3546        None => eprintln!("ferrox-server: global rayon pool already built; leaving it alone"),
3547    }
3548}
3549
3550/// Prints the machine-readable ready line (see `ferrox_api::lifecycle`)
3551/// on stdout and flushes it.
3552///
3553/// This one line is what makes `--port 0` usable, and it deletes a whole
3554/// feature from any supervising process: no "is the port free" probe, no
3555/// `lsof` to work out whether an existing listener is a stale copy of
3556/// ourselves or a stranger's server, no dialog to explain the result.
3557/// The kernel picks the port and the child says what it got.
3558///
3559/// Shares stdout with the tracing subscriber on purpose -- a parent
3560/// reads stdout line by line and ignores anything that is not the ready
3561/// event, which `ServerReady::from_line` does for it.
3562fn announce_ready(addr: SocketAddr, scheme: &str) {
3563    use std::io::Write;
3564    let ready =
3565        ferrox_api::ServerReady::new(addr, scheme, env!("CARGO_PKG_VERSION"), std::process::id());
3566    let mut stdout = std::io::stdout().lock();
3567    let _ = writeln!(stdout, "{}", ready.to_line());
3568    let _ = stdout.flush();
3569}
3570
3571/// Resolves when the server should stop serving.
3572///
3573/// Stdin-close is the one orphan-prevention mechanism that behaves
3574/// identically on macOS, Windows and Linux and survives a parent that
3575/// dies rather than exiting cleanly: the kernel closes the pipe either
3576/// way. The POSIX alternative -- a signal handler plus an exit hook plus
3577/// a reaper -- has no Windows equivalent at all, since there is no
3578/// SIGTERM there.
3579///
3580/// When disabled this future never resolves, which is exactly the
3581/// previous behaviour: serve until the process is stopped externally.
3582async fn shutdown_signal(exit_on_stdin_close: bool) {
3583    if !exit_on_stdin_close {
3584        std::future::pending::<()>().await;
3585        return;
3586    }
3587    let _ = tokio::task::spawn_blocking(|| {
3588        use std::io::Read;
3589        let mut sink = [0u8; 256];
3590        let mut stdin = std::io::stdin().lock();
3591        loop {
3592            match stdin.read(&mut sink) {
3593                // EOF: the parent is gone, or closed the pipe.
3594                Ok(0) => break,
3595                // Input on stdin is not a protocol here; drain it.
3596                Ok(_) => continue,
3597                Err(e) => {
3598                    tracing::warn!("stdin read failed ({e}); treating it as closed");
3599                    break;
3600                }
3601            }
3602        }
3603    })
3604    .await;
3605    tracing::info!("stdin closed; shutting down");
3606}
3607
3608/// Tokio worker threads. The default is one per logical core, which on a
3609/// 10-core M2 Pro means 10 async workers oversubscribing the same cores
3610/// the rayon decode pool needs. Serving work here is almost entirely I/O
3611/// plus `spawn_blocking` handoff, so a small fixed pool is enough.
3612fn tokio_worker_threads() -> usize {
3613    std::env::var("FERROX_TOKIO_WORKERS")
3614        .ok()
3615        .and_then(|v| v.trim().parse::<usize>().ok())
3616        .filter(|n| *n > 0)
3617        .unwrap_or(2)
3618}
3619
3620/// Parses llama-server-style options and applies their environment
3621/// overrides before creating Tokio or Rayon worker threads. It then
3622/// brackets the async server lifecycle with journal records.
3623/// Install rustls' `ring` crypto provider as the process default.
3624///
3625/// `axum-server` is built with `tls-rustls-no-provider`, which
3626/// deliberately does NOT pick a backend -- see the comment on the
3627/// dependency in `Cargo.toml`. rustls then has no default provider, and
3628/// building a `ServerConfig` without one fails at ACCEPT time rather
3629/// than at compile time, which is the worst place for it to surface: a
3630/// server that started cleanly and refuses every TLS connection.
3631///
3632/// So this runs unconditionally at startup, not lazily in the TLS arm.
3633/// `install_default` returns `Err` if a provider is already installed,
3634/// which is not a failure -- it means something else got there first
3635/// and the invariant we care about (there IS a provider) already holds.
3636fn install_ring_crypto_provider() {
3637    let _ = rustls::crypto::ring::default_provider().install_default();
3638}
3639
3640/// Runs the server to completion.
3641///
3642/// Takes already-parsed arguments so the same library backs both the
3643/// `ferrox-server` binary and ferrox-cli's optional `serve` feature,
3644/// and neither front end can drift into its own startup logic.
3645pub fn run_server(args: ServerArgs) -> anyhow::Result<()> {
3646    if args.list_devices {
3647        print_available_devices();
3648        return Ok(());
3649    }
3650    apply_cli_overrides(&args)?;
3651
3652    // Before the model is loaded and before the port is bound: refuse
3653    // to be the second process holding weights on this host. Held for
3654    // the life of the process -- dropping it deregisters us.
3655    let _instance = {
3656        use ferrox_core::instance::{register, InstancePolicy};
3657        let policy = if args.allow_multiple_instances {
3658            InstancePolicy::Multi
3659        } else {
3660            InstancePolicy::from_env_or(InstancePolicy::Single)
3661        };
3662        let model = std::env::var("FERROX_MODEL_PATH").ok();
3663        register(
3664            "server",
3665            model.as_deref(),
3666            ferrox_core::instance::current_backend(),
3667            policy,
3668        )
3669        .map_err(|conflict| anyhow::anyhow!("{conflict}"))?
3670    };
3671
3672    let journal = journal::Journal::from_env();
3673    eprintln!(
3674        "ferrox-server: process lifecycle journal at {:?} (override with FERROX_JOURNAL_PATH)",
3675        journal.path()
3676    );
3677    journal.append(&journal::Record::session_start(
3678        env!("CARGO_PKG_VERSION"),
3679        std::process::id(),
3680    ));
3681    journal::install_panic_hook(journal.clone());
3682
3683    let mcp_config_path = args.mcp_config.clone();
3684    let exit_on_stdin_close = args.exit_on_stdin_close
3685        || std::env::var("FERROX_EXIT_ON_STDIN_CLOSE")
3686            .map(|v| v == "1")
3687            .unwrap_or(false);
3688
3689    // Before Tokio exists, so the decode pool's threads are not spawned
3690    // from (and do not inherit the QoS of) a blocking-pool thread.
3691    // SAFETY: still single-threaded here.
3692    unsafe { ferrox_core::weight_matrix::default_cpu_int_dot_on() };
3693    init_cpu_pool();
3694
3695    let runtime = tokio::runtime::Builder::new_multi_thread()
3696        .worker_threads(tokio_worker_threads())
3697        .enable_all()
3698        .build()?;
3699    let result = runtime.block_on(run(mcp_config_path, exit_on_stdin_close));
3700
3701    let reason = match &result {
3702        Ok(()) => "normal".to_string(),
3703        Err(e) => e.to_string(),
3704    };
3705    journal.append(&journal::Record::session_exit(reason));
3706
3707    // Dropping the runtime instead would wait for blocking tasks, and
3708    // the stdin watcher parks in a blocking read that may never return
3709    // (a terminal keeps stdin open forever). The serving future has
3710    // already finished by here, so nothing useful is being abandoned.
3711    runtime.shutdown_background();
3712
3713    result
3714}
3715
3716async fn run(mcp_config_path: Option<PathBuf>, exit_on_stdin_close: bool) -> anyhow::Result<()> {
3717    // `try_init`, not `init`. As a library this runs inside a process
3718    // that may already have a subscriber: ferrox-cli installs one
3719    // before it dispatches, so `ferrox serve` would panic on startup
3720    // with "a global default trace dispatcher has already been set".
3721    // Losing the race is not an error, it means logging is configured.
3722    let _ = tracing_subscriber::fmt::try_init();
3723
3724    // Fail-closed listener check, before anything else (including
3725    // loading the model, so a misconfigured bind fails fast rather than
3726    // after however long that takes): refuse to start bound to a
3727    // non-loopback address with no API key configured, unless the
3728    // operator has explicitly opted into that via
3729    // FERROX_ALLOW_UNAUTHENTICATED_REMOTE=1 -- see
3730    // `security::check_bind_authorization`'s doc comment for why an
3731    // address that doesn't even parse as loopback is treated the same
3732    // as a confirmed non-loopback one.
3733    let addr = std::env::var("FERROX_ADDR").unwrap_or_else(|_| "127.0.0.1:8383".to_string());
3734    let api_key_configured = std::env::var("FERROX_API_KEY").is_ok();
3735    let allow_unauthenticated_remote = std::env::var("FERROX_ALLOW_UNAUTHENTICATED_REMOTE")
3736        .map(|v| v == "1")
3737        .unwrap_or(false);
3738    if let Err(msg) =
3739        security::check_bind_authorization(&addr, api_key_configured, allow_unauthenticated_remote)
3740    {
3741        anyhow::bail!(msg);
3742    }
3743
3744    let mut loaded = model::load()?;
3745    match &loaded {
3746        model::LoadedModel::Gguf(g) => tracing::info!(
3747            "loaded GGUF model '{}' (synthetic={}, tokenizer={})",
3748            g.decoder.config.name,
3749            g.is_synthetic,
3750            g.tokenizer.kind()
3751        ),
3752        model::LoadedModel::Kimi(k) => tracing::info!(
3753            "loaded Kimi K3 checkpoint (tokenizer={} base tokens)",
3754            k.tokenizer.vocab_size()
3755        ),
3756        model::LoadedModel::Mla(m) => tracing::info!(
3757            "loaded MLA GGUF '{}' (tokenizer={})",
3758            m.name,
3759            m.tokenizer.kind()
3760        ),
3761        model::LoadedModel::Gemma4(m) => tracing::info!(
3762            "loaded Gemma4 GGUF '{}' (tokenizer={})",
3763            m.name,
3764            m.tokenizer.kind()
3765        ),
3766        model::LoadedModel::Glm52(g) => tracing::info!(
3767            "loaded GLM-5.2 GGUF '{}' (tokenizer={})",
3768            g.name,
3769            g.tokenizer.kind()
3770        ),
3771    }
3772    // Opt-in VRAM budget for GPU-resident MoE experts. When unset but
3773    // Metal is active, default to a large budget so routed experts that
3774    // have Metal-capable quants run via `run_expert_placed` (Metal
3775    // matvec) instead of staying on CPU after Metal attention. Explicit
3776    // `FERROX_GPU_VRAM_BUDGET_BYTES=0` keeps the historical all-CPU MoE
3777    // placement. CUDA builds still require an explicit budget (Vast /
3778    // multi-GPU hosts vary too much for a safe default).
3779    let metal_default_moe_budget = {
3780        #[cfg(feature = "metal")]
3781        {
3782            ferrox_core::metal_dense_enabled()
3783                && std::env::var("FERROX_GPU_VRAM_BUDGET_BYTES").is_err()
3784        }
3785        #[cfg(not(feature = "metal"))]
3786        {
3787            false
3788        }
3789    };
3790    if let Ok(budget_str) = std::env::var("FERROX_GPU_VRAM_BUDGET_BYTES") {
3791        let budget: u64 = budget_str
3792            .parse()
3793            .expect("FERROX_GPU_VRAM_BUDGET_BYTES must be a non-negative integer");
3794        match &mut loaded {
3795            model::LoadedModel::Gguf(g) => {
3796                tracing::info!(
3797                    "GPU expert placement enabled: {budget} byte VRAM budget for routed experts \
3798                     (CUDA and/or Metal matvecs when built with the matching feature)"
3799                );
3800                g.decoder.gpu_vram_budget_bytes = Some(budget);
3801            }
3802            model::LoadedModel::Kimi(_) => {
3803                tracing::warn!(
3804                    "FERROX_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Kimi K3 -- not \
3805                     supported yet (its MoE stack isn't wired to PlacementPlan), ignoring"
3806                );
3807            }
3808            model::LoadedModel::Mla(_) => {
3809                tracing::warn!(
3810                    "FERROX_GPU_VRAM_BUDGET_BYTES is set but the loaded model is MLA -- dense \
3811                     FFN path only today; ignoring expert VRAM budget"
3812                );
3813            }
3814            model::LoadedModel::Gemma4(_) => {
3815                tracing::warn!(
3816                    "FERROX_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Gemma4 -- \
3817                     ignoring expert VRAM budget"
3818                );
3819            }
3820            model::LoadedModel::Glm52(_) => {
3821                tracing::warn!(
3822                    "FERROX_GPU_VRAM_BUDGET_BYTES is set but the loaded model is GLM-5.2 DSA -- \
3823                     GPU expert placement not wired yet; ignoring"
3824                );
3825            }
3826        }
3827    } else if metal_default_moe_budget {
3828        // ~64 GiB sentinel: place as many experts as the planner allows;
3829        // Metal unified memory makes a hard VRAM split less meaningful
3830        // than on discrete CUDA cards.
3831        const METAL_DEFAULT_MOE_BUDGET: u64 = 64 * 1024 * 1024 * 1024;
3832        if let model::LoadedModel::Gguf(g) = &mut loaded {
3833            tracing::info!(
3834                "Metal MoE expert placement default-on ({METAL_DEFAULT_MOE_BUDGET} byte budget); \
3835                 set FERROX_GPU_VRAM_BUDGET_BYTES=0 to force CPU experts"
3836            );
3837            g.decoder.gpu_vram_budget_bytes = Some(METAL_DEFAULT_MOE_BUDGET);
3838        }
3839    }
3840    #[cfg(feature = "cuda")]
3841    {
3842        if ferrox_core::cuda_dense_enabled() {
3843            tracing::info!(
3844                "CUDA dense matvec enabled for WeightMatrix::apply \
3845                 (FERROX_CUDA=0|cpu forces CPU; weight buffers stay resident after first upload)"
3846            );
3847        } else {
3848            tracing::info!(
3849                "CUDA dense matvec disabled (FERROX_CUDA); dense decode uses CPU or Metal"
3850            );
3851        }
3852    }
3853    #[cfg(feature = "metal")]
3854    {
3855        if ferrox_core::metal_dense_enabled() {
3856            tracing::info!(
3857                "Metal dense matvec enabled for WeightMatrix::apply \
3858                 (FERROX_METAL=0|cpu forces CPU; weight buffers stay resident after first upload)"
3859            );
3860            match std::env::var("FERROX_METAL_ATTN").ok().as_deref() {
3861                Some("1") | Some("true") | Some("on") | Some("attn") => {
3862                    tracing::info!(
3863                        "Metal fused attention requested (FERROX_METAL_ATTN): \
3864                         QKV→RoPE→GQA→O on-GPU for Norm/NeoX decode without QKV bias/QK-norm"
3865                    );
3866                }
3867                _ => {}
3868            }
3869            tracing::info!(
3870                "Metal greedy GPU argmax: temperature<=0 folds \
3871                 final_norm+lm_head+argmax into the dense stack"
3872            );
3873        } else {
3874            tracing::info!("Metal dense matvec disabled (FERROX_METAL); dense decode uses CPU");
3875        }
3876    }
3877    // Both env vars are required together to enable pooling; unset ->
3878    // caches keep their original unbounded-per-request growth. This
3879    // mirrors the FERROX_API_KEY / FERROX_RATE_LIMIT_PER_MINUTE
3880    // pattern below: opt-in, off by default.
3881    //
3882    // Block count can be set explicitly (`FERROX_KV_POOL_BLOCKS` +
3883    // `FERROX_KV_POOL_BLOCK_SIZE`) or derived from a byte budget
3884    // (`FERROX_KV_BYTE_BUDGET` + `FERROX_KV_POOL_BLOCK_SIZE`, GGUF
3885    // models only). `FERROX_KV_POOL_BLOCKS` and
3886    // `FERROX_KV_BYTE_BUDGET` are mutually exclusive.
3887    let blocks_env = std::env::var("FERROX_KV_POOL_BLOCKS");
3888    let block_size_env = std::env::var("FERROX_KV_POOL_BLOCK_SIZE");
3889    let byte_budget_env = std::env::var("FERROX_KV_BYTE_BUDGET");
3890    if blocks_env.is_ok() && byte_budget_env.is_ok() {
3891        panic!(
3892            "FERROX_KV_POOL_BLOCKS and FERROX_KV_BYTE_BUDGET are mutually exclusive \
3893             (set one block-count source plus FERROX_KV_POOL_BLOCK_SIZE, or neither to disable)"
3894        );
3895    }
3896    let kv_pool = match (blocks_env, block_size_env, byte_budget_env) {
3897        (Ok(blocks), Ok(block_size), Err(_)) => {
3898            let total_blocks: usize = blocks
3899                .parse()
3900                .expect("FERROX_KV_POOL_BLOCKS must be a positive integer");
3901            let block_size: usize = block_size
3902                .parse()
3903                .expect("FERROX_KV_POOL_BLOCK_SIZE must be a positive integer");
3904            // Optional and independent of the two above: how long a
3905            // request retries before giving up when the pool is
3906            // momentarily exhausted, instead of rejecting on the very
3907            // first failed attempt. Zero (the default if unset)
3908            // preserves the original reject-immediately behavior.
3909            let queue_wait_ms: u64 = std::env::var("FERROX_KV_POOL_QUEUE_TIMEOUT_MS")
3910                .ok()
3911                .map(|v| {
3912                    v.parse()
3913                        .expect("FERROX_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
3914                })
3915                .unwrap_or(0);
3916            tracing::info!(
3917                "KV cache block pool enabled: {total_blocks} blocks x {block_size} positions \
3918                 each, shared across all concurrent requests, {queue_wait_ms}ms admission queue wait"
3919            );
3920            Some(generate::KvPoolConfig {
3921                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
3922                queue_wait: Duration::from_millis(queue_wait_ms),
3923            })
3924        }
3925        (Err(_), Ok(block_size), Ok(byte_budget)) => {
3926            let block_size: usize = block_size
3927                .parse()
3928                .expect("FERROX_KV_POOL_BLOCK_SIZE must be a positive integer");
3929            let budget: u64 = byte_budget
3930                .parse()
3931                .expect("FERROX_KV_BYTE_BUDGET must be a positive integer");
3932            let cfg = match &loaded {
3933                model::LoadedModel::Gguf(g) => &g.decoder.config,
3934                model::LoadedModel::Kimi(_)
3935                | model::LoadedModel::Mla(_)
3936                | model::LoadedModel::Gemma4(_)
3937                | model::LoadedModel::Glm52(_) => {
3938                    panic!(
3939                        "FERROX_KV_BYTE_BUDGET requires a GGUF decoder model \
3940                         (set FERROX_MODEL_PATH to a generic-decoder .gguf file)"
3941                    );
3942                }
3943            };
3944            let bytes_per_block = block_size
3945                * cfg.n_layers
3946                * cfg.n_kv_heads
3947                * cfg.head_dim
3948                * 2
3949                * std::mem::size_of::<f32>();
3950            assert!(
3951                bytes_per_block > 0,
3952                "derived KV block byte size must be positive (check model config and block size)"
3953            );
3954            let total_blocks = (budget as usize / bytes_per_block).max(1);
3955            let queue_wait_ms: u64 = std::env::var("FERROX_KV_POOL_QUEUE_TIMEOUT_MS")
3956                .ok()
3957                .map(|v| {
3958                    v.parse()
3959                        .expect("FERROX_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
3960                })
3961                .unwrap_or(0);
3962            tracing::info!(
3963                "KV cache block pool enabled from byte budget: {budget} bytes / \
3964                 {bytes_per_block} bytes per block ({block_size} positions x {} layers) -> \
3965                 {total_blocks} blocks, {queue_wait_ms}ms admission queue wait",
3966                cfg.n_layers
3967            );
3968            Some(generate::KvPoolConfig {
3969                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
3970                queue_wait: Duration::from_millis(queue_wait_ms),
3971            })
3972        }
3973        (Err(_), Err(_), Err(_)) => None,
3974        (Err(_), Ok(_), Err(_)) => panic!(
3975            "FERROX_KV_POOL_BLOCK_SIZE requires FERROX_KV_POOL_BLOCKS or FERROX_KV_BYTE_BUDGET \
3976             (or unset all three to disable KV cache pooling)"
3977        ),
3978        (Ok(_), Ok(_), Ok(_)) => {
3979            unreachable!("FERROX_KV_POOL_BLOCKS and FERROX_KV_BYTE_BUDGET are mutually exclusive")
3980        }
3981        (Ok(_), Err(_), _) | (Err(_), Err(_), Ok(_)) => panic!(
3982            "FERROX_KV_POOL_BLOCKS/FERROX_KV_BYTE_BUDGET and FERROX_KV_POOL_BLOCK_SIZE must be \
3983             set together (or neither, to disable KV cache pooling)"
3984        ),
3985    };
3986    // Paged KV: per-layer shared page storage rather than a private
3987    // contiguous buffer per request. Refused alongside the pool and the
3988    // prefix cache rather than silently preferred over either -- an
3989    // operator who set two of these meant one of them, and picking for
3990    // them is how a deployment ends up not running what it thinks.
3991    let paged_kv = match (
3992        std::env::var("FERROX_PAGED_KV_BLOCKS"),
3993        std::env::var("FERROX_PAGED_KV_BLOCK_SIZE"),
3994    ) {
3995        (Ok(blocks), Ok(block_size)) => {
3996            assert!(
3997                kv_pool.is_none(),
3998                "FERROX_PAGED_KV_BLOCKS and FERROX_KV_POOL_BLOCKS/FERROX_KV_BYTE_BUDGET are \
3999                 mutually exclusive: both bound the same KV memory, by different means. \
4000                 Set one."
4001            );
4002            // Paged KV used to be refused here on any GPU backend,
4003            // because it returned fluent wrong tokens on Metal: the
4004            // prefill left K/V on the device and filled the host cache
4005            // with `KvCache::advance_len` placeholders, and the paged
4006            // prefill then copied those placeholders into the page
4007            // store. The decode that followed attended over a prompt
4008            // the model never saw.
4009            //
4010            // Fixed in `ferrox_models::Decoder`, which now downloads
4011            // the real rows for the caller that reads them, and pinned
4012            // on hardware by `paged_metal_parity` -- greedy ids
4013            // identical between paged and contiguous KV on a dense
4014            // model, an MoE model and a sliding-window model.
4015            let blocks_per_layer: usize = blocks
4016                .parse()
4017                .expect("FERROX_PAGED_KV_BLOCKS must be a positive integer");
4018            let block_size: usize = block_size
4019                .parse()
4020                .expect("FERROX_PAGED_KV_BLOCK_SIZE must be a positive integer");
4021            let gguf = match &loaded {
4022                model::LoadedModel::Gguf(g) => g,
4023                _ => panic!(
4024                    "FERROX_PAGED_KV_BLOCKS requires a GGUF decoder model \
4025                     (set FERROX_MODEL_PATH to a generic-decoder .gguf file)"
4026                ),
4027            };
4028            let cfg = &gguf.decoder.config;
4029            let queue_wait_ms: u64 = std::env::var("FERROX_KV_POOL_QUEUE_TIMEOUT_MS")
4030                .ok()
4031                .map(|v| {
4032                    v.parse()
4033                        .expect("FERROX_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4034                })
4035                .unwrap_or(0);
4036            tracing::info!(
4037                "Paged KV enabled: {blocks_per_layer} blocks x {block_size} positions per \
4038                 layer across {} layers, shared by all concurrent requests, \
4039                 {queue_wait_ms}ms admission queue wait",
4040                cfg.n_layers
4041            );
4042            // Prefix sharing rides on the same switch: paged KV is
4043            // what makes it possible at all, since sharing means two
4044            // sequences pointing at one page rather than one of them
4045            // holding a copy.
4046            let radix = Some(Arc::new(Mutex::new(crate::policy::radix::RadixCache::new(
4047                block_size,
4048            ))));
4049            // The anchor: the position an agentic turn will come back
4050            // to. Resolved ONCE here, from the served checkpoint's own
4051            // family and its own tokenizer, because it has to be a
4052            // single token id for the slide to recognize it on the hot
4053            // path for nothing. A checkpoint whose opener is more than
4054            // one token, or whose family has no opener at all (harmony
4055            // opens a call with an ordinary channel header), simply gets
4056            // no anchors and the slide follows the cursor.
4057            let anchor_token = crate::policy::anchor::resolve_anchor_token(
4058                crate::policy::parser::ToolCallFormat::infer(
4059                    &std::env::var("FERROX_MODEL_PATH").unwrap_or_default(),
4060                )
4061                .opener(),
4062                |text| {
4063                    gguf.tokenizer
4064                        .encode(text)
4065                        .into_iter()
4066                        .map(|t| t as u32)
4067                        .collect()
4068                },
4069            );
4070            if let Some(id) = anchor_token {
4071                tracing::info!(
4072                    "Paged KV window slide: tool-call anchor is token {id}, so a turn's \
4073                     window stops short of where its next turn rejoins"
4074                );
4075            }
4076            let slide_interval: usize = std::env::var("FERROX_PAGED_KV_SLIDE_INTERVAL")
4077                .ok()
4078                .map(|v| {
4079                    v.parse()
4080                        .expect("FERROX_PAGED_KV_SLIDE_INTERVAL must be a positive integer")
4081                })
4082                .unwrap_or(crate::policy::pool_budget::DEFAULT_SWA_EVICTION_INTERVAL);
4083            if let Some(window) = cfg.uniform_sliding_window() {
4084                tracing::info!(
4085                    "Paged KV window slide enabled: every layer slides by {window} every \
4086                     {slide_interval} decode steps, so a request holds its prompt and a \
4087                     window rather than its whole context"
4088                );
4089            } else if cfg.kv_block_window().is_some() {
4090                tracing::info!(
4091                    "Paged KV window slide NOT enabled: this model has full-attention layers, \
4092                     and a page group holds one block in every layer"
4093                );
4094            }
4095            Some(generate::PagedKvConfig {
4096                store: Arc::new(ferrox_core::cache::SharedPagedKv::new(
4097                    cfg.n_layers,
4098                    block_size,
4099                    blocks_per_layer,
4100                    cfg.n_kv_heads,
4101                    cfg.head_dim,
4102                )),
4103                queue_wait: Duration::from_millis(queue_wait_ms),
4104                radix,
4105                anchor_token,
4106                slide_interval,
4107            })
4108        }
4109        (Err(_), Err(_)) => None,
4110        _ => panic!(
4111            "FERROX_PAGED_KV_BLOCKS and FERROX_PAGED_KV_BLOCK_SIZE must be set together \
4112             (or neither, to disable paged KV)"
4113        ),
4114    };
4115    // Mutually exclusive with kv_pool (see generate::generate's doc
4116    // comment on why a pool-backed cache can't safely be restored from
4117    // a prefix-cache clone): if both are set, the KV pool wins and
4118    // prefix caching is simply never consulted -- generate() already
4119    // enforces this per-request, so this is a heads-up for the
4120    // operator, not a hard failure.
4121    let prefix_cache = std::env::var("FERROX_PREFIX_CACHE_ENTRIES").ok().map(|v| {
4122        let max_entries: usize = v
4123            .parse()
4124            .expect("FERROX_PREFIX_CACHE_ENTRIES must be a positive integer");
4125        if kv_pool.is_some() {
4126            tracing::warn!(
4127                "FERROX_PREFIX_CACHE_ENTRIES is set but so is the KV pool -- prefix \
4128                     caching will never be consulted while a KV pool is configured"
4129            );
4130        }
4131        // A hard refusal rather than the warning above, because the
4132        // outcome is worse than "never consulted": `PrefixCache` stores
4133        // `Vec<KvCache>` snapshots, and a paged request has none to
4134        // give, so every store would be skipped and every lookup miss.
4135        // An operator would see a prefix cache configured, reporting
4136        // zero hits forever, with nothing saying why.
4137        assert!(
4138            paged_kv.is_none(),
4139            "FERROX_PREFIX_CACHE_ENTRIES and FERROX_PAGED_KV_BLOCKS are mutually exclusive: \
4140             the prefix cache stores contiguous KV snapshots, which a paged request does not \
4141             produce, so the cache could never hit. Set one."
4142        );
4143        tracing::info!(
4144            "KV-prefix cache enabled: up to {max_entries} stored prefixes, shared across \
4145                 all requests"
4146        );
4147        Arc::new(Mutex::new(PrefixCache::new(max_entries)))
4148    });
4149    if matches!(
4150        loaded,
4151        model::LoadedModel::Kimi(_) | model::LoadedModel::Mla(_) | model::LoadedModel::Glm52(_)
4152    ) && (kv_pool.is_some() || prefix_cache.is_some())
4153    {
4154        tracing::warn!(
4155            "KV pool / prefix cache are configured but the loaded model is Kimi, MLA, or GLM-5.2 -- \
4156             neither is consulted for those engines (state shapes differ from Decoder KV); see \
4157             ferrox_models::engine's module docs"
4158        );
4159    }
4160    let enable_cb = std::env::var("FERROX_CONTINUOUS_BATCHING")
4161        .map(|v| v == "1")
4162        .unwrap_or(false)
4163        // Paged KV is what removed the old exclusivity: a batched row
4164        // now holds a `PagedLease`, which is pool-accounted by
4165        // construction and shares a prefix through the radix tree, so
4166        // the two things the batcher could not previously do it now
4167        // gets for free. The CONTIGUOUS pool and prefix cache still
4168        // keep the private path, because a batched row has no way to
4169        // restore a `Vec<KvCache>` snapshot.
4170        && (paged_kv.is_some() || (kv_pool.is_none() && prefix_cache.is_none()))
4171        && matches!(loaded, model::LoadedModel::Gguf(_));
4172    if std::env::var("FERROX_CONTINUOUS_BATCHING")
4173        .map(|v| v == "1")
4174        .unwrap_or(false)
4175        && (kv_pool.is_some() || prefix_cache.is_some())
4176    {
4177        tracing::warn!(
4178            "FERROX_CONTINUOUS_BATCHING=1 ignored while KV pool or prefix cache is configured \
4179             (those modes keep the private generate path)"
4180        );
4181    }
4182    if let Ok(n) = std::env::var("FERROX_CHUNKED_PREFILL") {
4183        if let Ok(chunk) = n.parse::<usize>() {
4184            if chunk > 0 {
4185                tracing::info!("chunked prefill enabled: {chunk} tokens per forward_batch chunk");
4186            }
4187        }
4188    }
4189    if matches!(
4190        std::env::var("FERROX_CPU_KV_OFFLOAD").ok().as_deref(),
4191        Some("1")
4192    ) {
4193        tracing::warn!(
4194            "FERROX_CPU_KV_OFFLOAD=1: syncing Metal KV to host after each decode step \
4195             (minimal spill; full layer offload still planned)"
4196        );
4197    }
4198
4199    let mcp = match mcp_config_path {
4200        Some(path) => {
4201            let loaded = mcp::load_mcp_config(&path)?;
4202            tracing::info!(
4203                "MCP config loaded from {} ({} server(s); invocation not wired yet)",
4204                loaded.path,
4205                loaded.servers.len()
4206            );
4207            Some(loaded)
4208        }
4209        None => None,
4210    };
4211
4212    // Started before the router is built so the probe overlaps with
4213    // binding the port: by the time a client can ask, it has usually
4214    // already landed.
4215    let detection = health::Detection::spawn();
4216
4217    let state = Arc::new(build_app_state(
4218        loaded,
4219        kv_pool,
4220        paged_kv,
4221        prefix_cache,
4222        enable_cb,
4223        mcp,
4224        detection,
4225    ));
4226
4227    // Paths come from `ferrox_api::routes` rather than string literals
4228    // so the UI, `ferrox chat` and this router cannot disagree about
4229    // what the surface is.
4230    use ferrox_api::routes;
4231
4232    // Ferrox Studio is a separate app served by its own dev/static
4233    // server (see `ui/` at the repository root); it reaches this
4234    // process over the public HTTP API like any other client, so there
4235    // is nothing to mount here and `/` stays a 404.
4236    let public = Router::new().route(routes::HEALTH, get(health));
4237
4238    let mut protected = Router::new()
4239        .route(routes::V1_MODELS, get(list_models))
4240        // The Responses surface decodes tokens, so it sits behind the
4241        // same key as `/v1/chat/completions`: it must cost what
4242        // decoding tokens costs.
4243        .route(routes::V1_RESPONSES, post(responses::responses))
4244        .route(
4245            &axum_path(routes::V1_RESPONSE),
4246            get(responses::responses_get),
4247        )
4248        .route(
4249            &axum_path(routes::V1_RESPONSE_CANCEL),
4250            post(responses::responses_cancel),
4251        )
4252        .route(routes::V1_STATS, get(serving_stats))
4253        .route(routes::V1_REQUESTS, get(recent_requests))
4254        .route(routes::V1_CACHE_STATUS, get(cache_admin::cache_status))
4255        .route(routes::V1_CACHE_REBUILD, post(cache_admin::cache_rebuild))
4256        .route(routes::ADMIN_PREPARE_STOP, post(cache_admin::prepare_stop))
4257        .route(routes::V1_CHAT_COMPLETIONS, post(chat_completions))
4258        // Behind the same key as the endpoint that started the work:
4259        // an unauthenticated caller must not be able to stop someone
4260        // else's generation by guessing at request ids.
4261        .route(routes::V1_CANCEL, post(cancel_generation))
4262        // Reconnect and the polling fallback, both behind the same key
4263        // as the request that filled the buffer: the replay window holds
4264        // the model's output, so reading it must cost what producing it
4265        // cost.
4266        .route(&axum_path(routes::V1_STREAM), get(resume::resume))
4267        .route(&axum_path(routes::V1_STREAM_POLL), get(resume::poll))
4268        .route(routes::V1_MESSAGES, post(anthropic::messages))
4269        .route(
4270            routes::V1_MESSAGES_COUNT_TOKENS,
4271            post(anthropic::count_tokens),
4272        )
4273        .route(routes::V1_COMPLETIONS, post(openai_extra::completions))
4274        .route(routes::V1_TOKENIZE, post(openai_extra::tokenize))
4275        .route(routes::V1_DETOKENIZE, post(openai_extra::detokenize))
4276        .route(routes::V1_EMBEDDINGS, post(openai_extra::embeddings))
4277        .route(routes::CACHE_STATS, get(cache_stats))
4278        .route(routes::METRICS, get(metrics))
4279        // The control surface. Registered inside `protected` on
4280        // purpose: these routes change what the server serves and write
4281        // to disk, so they get the same FERROX_API_KEY gate as /v1/*
4282        // and never the unauthenticated treatment /health has.
4283        .route(routes::ADMIN_MODELS, get(admin::models))
4284        .route(routes::ADMIN_MODELS_LOAD, post(admin::load_model))
4285        .route(routes::ADMIN_MODELS_UNLOAD, post(admin::unload_model))
4286        .route(routes::ADMIN_DOWNLOAD, post(admin::download))
4287        .route(routes::ADMIN_TASKS, get(admin::tasks))
4288        .route(&admin::cancel_route(), post(admin::cancel_task))
4289        .route(routes::ADMIN_STATS, get(admin::stats))
4290        // Server-side conversation storage, mounted here so it inherits
4291        // the same key gate as the endpoint that generated the text it
4292        // stores. Routes and store both live in `conversations`.
4293        .merge(conversations::router());
4294
4295    // Both off by default; set the corresponding env var to enable.
4296    // route_layer (not layer) so these apply only to the routes above,
4297    // never to /health, which stays reachable for liveness/readiness
4298    // probes regardless of auth or rate-limit configuration.
4299    if let Ok(key) = std::env::var("FERROX_API_KEY") {
4300        tracing::info!("API key auth enabled");
4301        let auth = limits::AuthConfig {
4302            api_key: Arc::new(key),
4303        };
4304        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4305            auth,
4306            limits::require_api_key,
4307        ));
4308    }
4309    if let Ok(rpm) = std::env::var("FERROX_RATE_LIMIT_PER_MINUTE") {
4310        let rpm: u32 = rpm
4311            .parse()
4312            .expect("FERROX_RATE_LIMIT_PER_MINUTE must be a positive integer");
4313        tracing::info!("rate limiting enabled: {rpm} requests/minute (global)");
4314        let limiter = Arc::new(limits::RateLimiter::per_minute(rpm));
4315        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4316            limiter,
4317            limits::rate_limit,
4318        ));
4319    }
4320    // Off by default; set FERROX_CORS_ORIGINS (comma-separated exact
4321    // origins) to enable. No wildcard support by design -- see
4322    // `security::parse_cors_origins`'s doc comment. Added last (so it's
4323    // the outermost route_layer, run before auth/rate-limiting): a CORS
4324    // preflight (OPTIONS) request carries no Authorization header and
4325    // is answered directly by `CorsLayer` itself, so it must not be
4326    // blocked by the auth/rate-limit layers underneath.
4327    if let Ok(spec) = std::env::var("FERROX_CORS_ORIGINS") {
4328        let origins = security::parse_cors_origins(&spec)
4329            .unwrap_or_else(|e| panic!("FERROX_CORS_ORIGINS: {e}"));
4330        tracing::info!(
4331            "CORS enabled: {} allow-listed origin(s) ({})",
4332            origins.len(),
4333            spec
4334        );
4335        let cors = tower_http::cors::CorsLayer::new()
4336            .allow_origin(tower_http::cors::AllowOrigin::list(origins))
4337            .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
4338            .allow_headers([
4339                axum::http::header::CONTENT_TYPE,
4340                axum::http::header::AUTHORIZATION,
4341                // The self-declared client label the monitor records
4342                // (see `attribution`). A custom header makes every
4343                // cross-origin call preflighted, so omitting it here
4344                // would not merely drop the label -- it would fail the
4345                // request outright.
4346                axum::http::HeaderName::from_static(attribution::CLIENT_HEADER),
4347                // Set by hand rather than by `EventSource`, because
4348                // this API needs POST and a bearer token. Same
4349                // consequence if it is missing.
4350                axum::http::HeaderName::from_static("last-event-id"),
4351            ]);
4352        protected = protected.route_layer(cors);
4353    }
4354
4355    // Outermost on purpose: every 503 this server can emit -- from a
4356    // handler, from `require_active`, or from the batch scheduler's
4357    // queue cap -- leaves with a `Retry-After` a client can act on.
4358    let app = public
4359        .merge(protected)
4360        .layer(axum::middleware::from_fn(limits::retry_after))
4361        .with_state(state);
4362
4363    // TLS is off by default -- set FERROX_TLS_CERT and FERROX_TLS_KEY
4364    // together to serve HTTPS instead of plain HTTP; unset (either or
4365    // both) preserves the original plain-HTTP behavior exactly. See
4366    // `security::tls_paths_from_env`'s doc comment for why this can't
4367    // be meaningfully unit-tested here.
4368    let tls_paths = security::tls_paths_from_env().unwrap_or_else(|e| panic!("{e}"));
4369    install_ring_crypto_provider();
4370    // Both arms bind first and read the address back off the socket
4371    // rather than trusting the requested one: with `--port 0` the
4372    // requested port is a lie by construction, and the ready line has
4373    // to carry what the kernel actually handed out.
4374    match tls_paths {
4375        Some(paths) => {
4376            let config =
4377                axum_server::tls_rustls::RustlsConfig::from_pem_file(&paths.cert, &paths.key)
4378                    .await
4379                    .map_err(|e| {
4380                        anyhow::anyhow!(
4381                            "failed to load TLS cert/key ({:?}, {:?}): {e}",
4382                            paths.cert,
4383                            paths.key
4384                        )
4385                    })?;
4386            let socket_addr: std::net::SocketAddr = addr
4387                .parse()
4388                .map_err(|e| anyhow::anyhow!("invalid FERROX_ADDR {addr:?} for TLS: {e}"))?;
4389            let listener = std::net::TcpListener::bind(socket_addr)?;
4390            // Tokio panics outright when handed a BLOCKING socket
4391            // ("Registering a blocking socket with the tokio runtime is
4392            // unsupported"), and axum-server registers this one
4393            // internally. Without this the TLS arm binds, prints its
4394            // ready line, and then panics on the first accept -- so the
4395            // failure looks like a healthy start followed by a server
4396            // that answers nothing.
4397            listener.set_nonblocking(true)?;
4398            let bound = listener.local_addr()?;
4399            tracing::info!("TLS enabled: ferrox-server listening on https://{bound}");
4400            announce_ready(bound, "https");
4401
4402            let handle = axum_server::Handle::new();
4403            let shutdown_handle = handle.clone();
4404            tokio::spawn(async move {
4405                shutdown_signal(exit_on_stdin_close).await;
4406                shutdown_handle.graceful_shutdown(Some(Duration::from_secs(5)));
4407            });
4408            axum_server::from_tcp_rustls(listener, config)?
4409                .handle(handle)
4410                .serve(app.into_make_service())
4411                .await?;
4412        }
4413        None => {
4414            let listener = tokio::net::TcpListener::bind(&addr).await?;
4415            let bound = listener.local_addr()?;
4416            tracing::info!("ferrox-server listening on {bound}");
4417            announce_ready(bound, "http");
4418            axum::serve(listener, app)
4419                .with_graceful_shutdown(shutdown_signal(exit_on_stdin_close))
4420                .await?;
4421        }
4422    }
4423    Ok(())
4424}
4425
4426#[cfg(test)]
4427mod tests {
4428    use super::*;
4429    use ferrox_models::config::test_dense_fixture;
4430
4431    #[test]
4432    fn parses_llama_server_style_options() {
4433        let argv = [
4434            "ferrox-server",
4435            "-m",
4436            "model.gguf",
4437            "--host",
4438            "::1",
4439            "--port",
4440            "9000",
4441            "-t",
4442            "4",
4443            "-dev",
4444            "Metal",
4445            "-ngl",
4446            "all",
4447        ]
4448        .into_iter()
4449        .map(String::from)
4450        .collect();
4451        let args = ServerArgs::try_parse_from(rewrite_llama_style_argv(argv)).unwrap();
4452
4453        assert_eq!(args.model.as_deref(), Some("model.gguf"));
4454        assert_eq!(args.host, Some(IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)));
4455        assert_eq!(args.port, Some(9000));
4456        assert_eq!(args.threads, Some(4));
4457        assert_eq!(args.device, Some(OffloadDevice::Metal));
4458        assert_eq!(args.n_gpu_layers, Some(GpuLayers::All));
4459        assert_eq!(
4460            cli_bind_addr(&args, Some("127.0.0.1:8383")).as_deref(),
4461            Some("[::1]:9000")
4462        );
4463    }
4464
4465    #[test]
4466    fn port_zero_survives_argument_parsing_as_a_real_request() {
4467        // `--port 0` must reach the bind call intact: it is a request
4468        // for a kernel-assigned port, not a missing value to default to
4469        // 8383. The address it produces is deliberately provisional --
4470        // the ready line reports what was actually bound.
4471        let argv = ["ferrox-server", "--port", "0"]
4472            .into_iter()
4473            .map(String::from)
4474            .collect();
4475        let args = ServerArgs::try_parse_from(rewrite_llama_style_argv(argv)).unwrap();
4476        assert_eq!(args.port, Some(0));
4477        assert_eq!(
4478            cli_bind_addr(&args, Some("127.0.0.1:8383")).as_deref(),
4479            Some("127.0.0.1:0")
4480        );
4481    }
4482
4483    #[test]
4484    fn stdin_close_exit_is_opt_in() {
4485        // Default off: a server whose stdin is /dev/null (systemd, cron,
4486        // nohup) would otherwise exit the instant it started.
4487        let args =
4488            ServerArgs::try_parse_from(["ferrox-server"].into_iter().map(String::from)).unwrap();
4489        assert!(!args.exit_on_stdin_close);
4490        let args = ServerArgs::try_parse_from(
4491            ["ferrox-server", "--exit-on-stdin-close"]
4492                .into_iter()
4493                .map(String::from),
4494        )
4495        .unwrap();
4496        assert!(args.exit_on_stdin_close);
4497    }
4498
4499    #[test]
4500    fn the_ready_line_round_trips_through_a_parent_reading_stdout() {
4501        let addr: SocketAddr = "127.0.0.1:51999".parse().unwrap();
4502        let ready = ferrox_api::ServerReady::new(addr, "http", "0.5.0", std::process::id());
4503        let parsed = ferrox_api::ServerReady::from_line(&ready.to_line()).unwrap();
4504        assert_eq!(parsed.port, 51999);
4505        assert_eq!(parsed.base_url(), "http://127.0.0.1:51999");
4506        // A parent reads stdout line by line; tracing shares the stream.
4507        assert!(ferrox_api::ServerReady::from_line("INFO ferrox-server listening").is_none());
4508    }
4509
4510    fn test_model() -> Model {
4511        // Tiny vocab (32): raw byte ids ≥32 (e.g. ASCII "hello") are OOV.
4512        // HTTP/chat-template tests that need full ASCII use
4513        // `test_model_full_byte_vocab` instead.
4514        let cfg = test_dense_fixture();
4515        Model::Gguf(GgufModel {
4516            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 32)),
4517            tokenizer: Arc::new(ServerTokenizer::Byte),
4518            stop_tokens: StopTokens::default(),
4519            bos_id: None,
4520            is_synthetic: true,
4521            chat_template: chat_template::PromptTemplate::plain(),
4522        })
4523    }
4524
4525    fn greedy_params(max_tokens: usize) -> GenerationParams {
4526        GenerationParams {
4527            max_tokens,
4528            sampling: SamplingParams::default(),
4529            seed: 1,
4530            stop: Vec::new(),
4531            stop_token_ids: Vec::new(),
4532            json_object: false,
4533            cancel: None,
4534            ignore_eos: false,
4535        }
4536    }
4537
4538    /// Declares a full 0..255 byte-compatible vocab so HTTP-level tests
4539    /// that render chat templates (ASCII role names) do not spuriously
4540    /// reject their own prompt prefixes.
4541    fn test_model_full_byte_vocab() -> Model {
4542        let mut cfg = test_dense_fixture();
4543        cfg.vocab_size = 256;
4544        Model::Gguf(GgufModel {
4545            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4546            tokenizer: Arc::new(ServerTokenizer::Byte),
4547            stop_tokens: StopTokens::default(),
4548            bos_id: None,
4549            is_synthetic: true,
4550            chat_template: chat_template::PromptTemplate::plain(),
4551        })
4552    }
4553
4554    /// One `AppState` for the HTTP-level tests, so a new field on the
4555    /// struct is added in one place rather than in every test that
4556    /// builds one.
4557    fn test_state(model: Model, response_cache: ResponseCache) -> AppState {
4558        AppState {
4559            paged_kv: None,
4560            active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
4561                id: None,
4562                model: Arc::new(model),
4563                batcher: None,
4564                ceiling: None,
4565            }))),
4566            load_in_progress: std::sync::atomic::AtomicBool::new(false),
4567            tasks: Arc::new(tasks::TaskRegistry::new()),
4568            cancels: Arc::new(cancel::CancelRegistry::new()),
4569            stats: stats::Stats::new(),
4570            streams: resume::StreamRegistry::new(),
4571            model_dir: None,
4572            response_cache: Mutex::new(response_cache),
4573            kv_pool: None,
4574            prefix_cache: None,
4575            sessions: session::SessionStore::new(),
4576            requests_total: std::sync::atomic::AtomicU64::new(0),
4577            request_errors_total: std::sync::atomic::AtomicU64::new(0),
4578            started_at: std::time::Instant::now(),
4579            last_request_ms: std::sync::atomic::AtomicU64::new(0),
4580            detection: Arc::new(health::Detection::ready(health::probe_backends())),
4581            mcp: None,
4582            continuous_batching_enabled: false,
4583            loading_model: Mutex::new(None),
4584            last_load_error: Mutex::new(None),
4585            serving: Mutex::new(crate::stats::ServingStats::default()),
4586            maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
4587            footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
4588            started_unix: unix_now(),
4589        }
4590    }
4591
4592    /// A real axum `Router` wired exactly like `main()`'s (minus auth/
4593    /// rate-limiting, which are orthogonal and already covered by
4594    /// `limits`'s own tests), backed by a fresh
4595    /// `test_model_full_byte_vocab()` -- so tool-calling/session tests
4596    /// exercise the real HTTP request/response path (JSON
4597    /// (de)serialization, routing, handler wiring, chat-template
4598    /// rendering) via `tower::ServiceExt::oneshot`, not just the inner
4599    /// functions directly.
4600    fn test_app() -> Router {
4601        test_app_with_state(Arc::new(test_state(
4602            test_model_full_byte_vocab(),
4603            ResponseCache::new(1000, Duration::from_secs(3600)),
4604        )))
4605    }
4606
4607    /// [`test_app`] over a caller-owned state, so a test can reach in
4608    /// and swap or unload the model behind a live router.
4609    fn test_app_with_state(state: Arc<AppState>) -> Router {
4610        Router::new()
4611            .route(ferrox_api::routes::HEALTH, get(health))
4612            .route(ferrox_api::routes::V1_MODELS, get(list_models))
4613            .route(ferrox_api::routes::V1_RESPONSES, post(responses::responses))
4614            .route(
4615                &axum_path(ferrox_api::routes::V1_RESPONSE),
4616                get(responses::responses_get),
4617            )
4618            .route(
4619                &axum_path(ferrox_api::routes::V1_RESPONSE_CANCEL),
4620                post(responses::responses_cancel),
4621            )
4622            .route(ferrox_api::routes::V1_STATS, get(serving_stats))
4623            .route(ferrox_api::routes::V1_REQUESTS, get(recent_requests))
4624            .route(
4625                ferrox_api::routes::V1_CACHE_STATUS,
4626                get(cache_admin::cache_status),
4627            )
4628            .route(
4629                ferrox_api::routes::V1_CACHE_REBUILD,
4630                post(cache_admin::cache_rebuild),
4631            )
4632            .route(
4633                ferrox_api::routes::ADMIN_PREPARE_STOP,
4634                post(cache_admin::prepare_stop),
4635            )
4636            .route("/v1/chat/completions", post(chat_completions))
4637            .route(ferrox_api::routes::V1_MESSAGES, post(anthropic::messages))
4638            .route(
4639                ferrox_api::routes::V1_MESSAGES_COUNT_TOKENS,
4640                post(anthropic::count_tokens),
4641            )
4642            .route("/v1/tokenize", post(openai_extra::tokenize))
4643            .route("/v1/detokenize", post(openai_extra::detokenize))
4644            .route("/v1/embeddings", post(openai_extra::embeddings))
4645            .route("/v1/completions", post(openai_extra::completions))
4646            .route(
4647                ferrox_api::routes::ADMIN_MODELS_UNLOAD,
4648                post(admin::unload_model),
4649            )
4650            .route(ferrox_api::routes::ADMIN_TASKS, get(admin::tasks))
4651            .route(ferrox_api::routes::ADMIN_STATS, get(admin::stats))
4652            .route(ferrox_api::routes::V1_CANCEL, post(cancel_generation))
4653            .route(
4654                &axum_path(ferrox_api::routes::V1_STREAM),
4655                get(resume::resume),
4656            )
4657            .route(
4658                &axum_path(ferrox_api::routes::V1_STREAM_POLL),
4659                get(resume::poll),
4660            )
4661            .with_state(state)
4662    }
4663
4664    fn named_test_model(name: &'static str, vocab_size: usize) -> Model {
4665        let mut cfg = test_dense_fixture();
4666        cfg.name = name;
4667        cfg.vocab_size = vocab_size;
4668        Model::Gguf(GgufModel {
4669            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4670            tokenizer: Arc::new(ServerTokenizer::Byte),
4671            stop_tokens: StopTokens::default(),
4672            bos_id: None,
4673            is_synthetic: true,
4674            chat_template: chat_template::PromptTemplate::plain(),
4675        })
4676    }
4677
4678    /// The same model, served through a real checkpoint's template
4679    /// rather than the role-labeled builtin -- so a test can ask what
4680    /// gets advertised for a checkpoint that actually has gears.
4681    fn model_with_template(name: &'static str, source: &str) -> Model {
4682        let mut cfg = test_dense_fixture();
4683        cfg.name = name;
4684        cfg.vocab_size = 256;
4685        Model::Gguf(GgufModel {
4686            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4687            tokenizer: Arc::new(ServerTokenizer::Byte),
4688            stop_tokens: StopTokens::default(),
4689            bos_id: None,
4690            is_synthetic: true,
4691            chat_template: chat_template::PromptTemplate::from_gguf_metadata(
4692                Some(source),
4693                Some("qwen3"),
4694                false,
4695                None,
4696                None,
4697            ),
4698        })
4699    }
4700
4701    /// Once a `200` and `text/event-stream` are on the wire, a
4702    /// rejection can only ride *in* the stream, where several agents
4703    /// render it as an empty response. So the prompt is rendered before
4704    /// the stream is committed, and a template that rejects this
4705    /// particular conversation is an ordinary 400 with a body.
4706    ///
4707    /// Fails if `prompt_from_messages` moves back inside the spawned
4708    /// generation task.
4709    #[tokio::test]
4710    async fn a_template_that_rejects_the_conversation_is_a_400_on_the_streaming_path() {
4711        // Raises on a second user turn, the way a real strict template
4712        // rejects an ordering it was never trained on.
4713        let strict = "{% if messages | length > 1 %}\
4714             {{ raise_exception('this template takes one turn') }}\
4715             {% endif %}{{ messages[0].content }}";
4716        let state = Arc::new(test_state(
4717            model_with_template("strict", strict),
4718            ResponseCache::new(4, Duration::from_secs(60)),
4719        ));
4720        let app = test_app_with_state(state);
4721
4722        let (status, body) = post_json_uri(
4723            &app,
4724            "/v1/chat/completions",
4725            serde_json::json!({
4726                "model": "strict",
4727                "stream": true,
4728                "messages": [
4729                    {"role": "user", "content": "one"},
4730                    {"role": "user", "content": "two"},
4731                ],
4732            }),
4733        )
4734        .await;
4735        assert_eq!(status, StatusCode::BAD_REQUEST);
4736        assert_eq!(body["error"]["param"], serde_json::json!("messages"));
4737        assert!(
4738            body["error"]["message"]
4739                .as_str()
4740                .unwrap()
4741                .contains("one turn"),
4742            "the template's own message must reach the caller: {body}"
4743        );
4744
4745        // And the same template serves a conversation it accepts.
4746        let (status, _) = post_json_uri(
4747            &app,
4748            "/v1/chat/completions",
4749            serde_json::json!({
4750                "model": "strict",
4751                "stream": true,
4752                "max_tokens": 1,
4753                "messages": [{"role": "user", "content": "one"}],
4754            }),
4755        )
4756        .await;
4757        assert_eq!(status, StatusCode::OK);
4758    }
4759
4760    /// A client should not have to guess which gears a checkpoint has.
4761    #[tokio::test]
4762    async fn models_advertises_the_gears_this_checkpoint_actually_has() {
4763        let reasoning = "{% if enable_thinking %}<think>{% endif %}\
4764             {% if reasoning_effort %}\
4765               {% if reasoning_effort not in ['low','medium','high'] %}\
4766                 {{ raise_exception('bad effort') }}\
4767               {% endif %}[{{ reasoning_effort }}]\
4768             {% endif %}{{ messages[0].content }}";
4769        let state = Arc::new(test_state(
4770            model_with_template("thinker", reasoning),
4771            ResponseCache::new(4, Duration::from_secs(60)),
4772        ));
4773        let app = test_app_with_state(state);
4774        let (status, models) = get_json(&app, ferrox_api::routes::V1_MODELS).await;
4775        assert_eq!(status, StatusCode::OK);
4776        let entry = &models["data"][0];
4777        assert_eq!(
4778            entry["supported_reasoning_efforts"],
4779            serde_json::json!(["off", "low", "medium", "high"])
4780        );
4781        assert_eq!(entry["default_reasoning_effort"], serde_json::json!("off"));
4782    }
4783
4784    /// The other half of the acceptance criterion: neither field, not
4785    /// an empty one. An empty list would say the question was asked and
4786    /// the answer was "no gears"; absence says it is not that kind of
4787    /// model.
4788    #[tokio::test]
4789    async fn a_checkpoint_with_no_thinking_controls_advertises_neither_field() {
4790        let app = test_app();
4791        let (_, models) = get_json(&app, ferrox_api::routes::V1_MODELS).await;
4792        let entry = &models["data"][0];
4793        assert!(entry.get("supported_reasoning_efforts").is_none());
4794        assert!(entry.get("default_reasoning_effort").is_none());
4795    }
4796
4797    fn active_model(state: &AppState, name: &'static str) -> Arc<ActiveModel> {
4798        Arc::new(ActiveModel {
4799            id: Some(name.to_string()),
4800            model: Arc::new(named_test_model(name, 256)),
4801            batcher: None,
4802            ceiling: None,
4803        })
4804        .tap_into(state)
4805    }
4806
4807    /// Small helper so the swap tests read as "publish this model".
4808    trait TapInto {
4809        fn tap_into(self, state: &AppState) -> Self;
4810    }
4811    impl TapInto for Arc<ActiveModel> {
4812        fn tap_into(self, state: &AppState) -> Self {
4813            state.swap_active(Some(Arc::clone(&self)));
4814            self
4815        }
4816    }
4817
4818    /// The load-order guarantee the whole swap design exists to make:
4819    /// a request that has already taken its handle finishes against the
4820    /// weights it started on, even though a different model has since
4821    /// been published. Anything else would splice two checkpoints into
4822    /// one completion.
4823    #[test]
4824    fn an_in_flight_request_keeps_the_model_it_started_on() {
4825        let state = test_state(
4826            named_test_model("model-a", 256),
4827            ResponseCache::new(4, Duration::from_secs(60)),
4828        );
4829
4830        // A request that has begun: it has cloned the handle and is
4831        // about to decode against it.
4832        let in_flight = state.active().expect("a model is loaded");
4833        assert_eq!(in_flight.model.name(), "model-a");
4834
4835        active_model(&state, "model-b");
4836
4837        // The swap is visible to anything that asks *now*...
4838        assert_eq!(state.active().unwrap().model.name(), "model-b");
4839        // ...and completely invisible to the request already running.
4840        assert_eq!(in_flight.model.name(), "model-a");
4841        let (_chunks, finish, _usage) = run_generation(
4842            &in_flight.model,
4843            "hi",
4844            &greedy_params(3),
4845            None,
4846            None,
4847            None,
4848            None,
4849            None,
4850        )
4851        .expect("the old model must still decode after being swapped out");
4852        assert!(matches!(finish, FinishReason::Length | FinishReason::Stop));
4853    }
4854
4855    /// The other half of the same guarantee: the old model is not freed
4856    /// at swap time, it is freed when the last holder lets go. A design
4857    /// that dropped it eagerly would free weights out from under a
4858    /// decode loop.
4859    #[test]
4860    fn a_swapped_out_model_lives_until_its_last_holder_releases_it() {
4861        let state = test_state(
4862            named_test_model("model-a", 256),
4863            ResponseCache::new(4, Duration::from_secs(60)),
4864        );
4865        let in_flight = state.active().expect("a model is loaded");
4866        let weights = Arc::clone(&in_flight.model);
4867        assert!(Arc::strong_count(&weights) >= 2);
4868
4869        let previous = state.swap_active(Some(Arc::new(ActiveModel {
4870            id: Some("model-b".to_string()),
4871            model: Arc::new(named_test_model("model-b", 256)),
4872            batcher: None,
4873            ceiling: None,
4874        })));
4875        drop(previous);
4876        // The registry has let go; the in-flight request has not.
4877        assert!(Arc::strong_count(&weights) >= 2);
4878        drop(in_flight);
4879        assert_eq!(Arc::strong_count(&weights), 1);
4880    }
4881
4882    /// Unload is not "keep serving the last thing loaded". A request
4883    /// that arrives afterwards must be told there is no model, not
4884    /// quietly served by a checkpoint the operator dropped.
4885    #[tokio::test]
4886    async fn unloading_answers_503_instead_of_serving_the_dropped_model() {
4887        let state = Arc::new(test_state(
4888            named_test_model("model-a", 256),
4889            ResponseCache::new(4, Duration::from_secs(60)),
4890        ));
4891        let app = test_app_with_state(Arc::clone(&state));
4892
4893        let (status, body) = post_json_uri(
4894            &app,
4895            ferrox_api::routes::ADMIN_MODELS_UNLOAD,
4896            serde_json::json!({}),
4897        )
4898        .await;
4899        assert_eq!(status, StatusCode::OK);
4900        assert_eq!(body["ok"], true);
4901        assert!(body["active"].is_null());
4902        assert!(state.active().is_none());
4903
4904        let (status, _) = get_json(&app, ferrox_api::routes::V1_MODELS).await;
4905        assert_eq!(status, StatusCode::OK);
4906        let (_, models) = get_json(&app, ferrox_api::routes::V1_MODELS).await;
4907        assert_eq!(models["data"].as_array().unwrap().len(), 0);
4908
4909        let (status, body) = post_json_uri(
4910            &app,
4911            "/v1/chat/completions",
4912            serde_json::json!({
4913                "model": "x",
4914                "messages": [{"role": "user", "content": "hi"}]
4915            }),
4916        )
4917        .await;
4918        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
4919        assert_eq!(body["error"]["type"], "model_not_loaded");
4920    }
4921
4922    /// `/health` must keep answering with nothing loaded -- a supervisor
4923    /// polls it to decide whether to kill the process, and "no model"
4924    /// is not "no server".
4925    #[tokio::test]
4926    async fn health_reports_the_unloaded_state_rather_than_going_silent() {
4927        let state = Arc::new(test_state(
4928            named_test_model("model-a", 256),
4929            ResponseCache::new(4, Duration::from_secs(60)),
4930        ));
4931        let app = test_app_with_state(Arc::clone(&state));
4932        state.swap_active(None);
4933
4934        let (status, body) = get_json(&app, ferrox_api::routes::HEALTH).await;
4935        // Not `ready`: a supervisor reading 200 here would route traffic
4936        // that is guaranteed to 503 on arrival.
4937        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
4938        assert_eq!(body["state"], "unavailable");
4939        assert_eq!(body["reason"], "model_not_loaded");
4940        assert!(body["model"].is_null());
4941        let real_weights = body["capabilities"]
4942            .as_array()
4943            .unwrap()
4944            .iter()
4945            .find(|c| c["id"] == "real_weights")
4946            .cloned()
4947            .expect("real_weights is always reported");
4948        assert_eq!(real_weights["available"], false);
4949        assert_eq!(real_weights["reason"], "model_not_loaded");
4950    }
4951
4952    /// The API-monitor contract: a finished request lands in the ring
4953    /// buffer keyed by the id the response carried, with the two
4954    /// durations reported separately.
4955    #[tokio::test]
4956    async fn a_finished_request_lands_in_the_stats_ring_with_both_durations() {
4957        let app = test_app();
4958
4959        let (status, completion) = post_json_uri(
4960            &app,
4961            "/v1/chat/completions",
4962            serde_json::json!({
4963                "model": "x",
4964                "messages": [{"role": "user", "content": "hi"}],
4965                "max_tokens": 4
4966            }),
4967        )
4968        .await;
4969        assert_eq!(status, StatusCode::OK);
4970        let request_id = completion["request_id"].as_str().unwrap().to_string();
4971
4972        let (status, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
4973        assert_eq!(status, StatusCode::OK);
4974        let recent = stats["recent"].as_array().unwrap();
4975        assert_eq!(recent.len(), 1);
4976        let row = &recent[0];
4977        assert_eq!(row["request_id"], request_id);
4978        assert_eq!(row["route"], ferrox_api::routes::V1_CHAT_COMPLETIONS);
4979        assert_eq!(row["status"], 200);
4980        assert_eq!(row["stream"], false);
4981        // Separate fields, and the decode phase is a real measurement
4982        // rather than a copy of the total.
4983        assert!(row["duration_ms"].is_number());
4984        assert!(row["decode_ms"].is_number());
4985        assert!(stats["tokens_generated_total"].as_u64().unwrap() > 0);
4986        assert_eq!(
4987            stats["tokens_prompt_total"].as_u64().unwrap(),
4988            row["prompt_tokens"].as_u64().unwrap()
4989        );
4990    }
4991
4992    /// A rejected request is still a request the monitor should show;
4993    /// otherwise the screen quietly omits exactly the traffic someone
4994    /// is debugging.
4995    #[tokio::test]
4996    async fn a_rejected_request_is_recorded_too() {
4997        let state = Arc::new(test_state(
4998            named_test_model("model-a", 256),
4999            ResponseCache::new(4, Duration::from_secs(60)),
5000        ));
5001        let app = test_app_with_state(Arc::clone(&state));
5002        state.swap_active(None);
5003
5004        let (status, _) = post_json_uri(
5005            &app,
5006            "/v1/chat/completions",
5007            serde_json::json!({"model": "x", "messages": [{"role": "user", "content": "hi"}]}),
5008        )
5009        .await;
5010        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5011
5012        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5013        let recent = stats["recent"].as_array().unwrap();
5014        assert_eq!(recent.len(), 1);
5015        assert_eq!(recent[0]["status"], 503);
5016        assert_eq!(recent[0]["completion_tokens"], 0);
5017        assert!(recent[0]["decode_ms"].is_null());
5018        assert_eq!(stats["errors_total"], 1);
5019    }
5020
5021    /// POSTs with caller-supplied headers, so the attribution tests
5022    /// exercise the same header parsing a real client's request goes
5023    /// through rather than calling `Attribution::from_headers` twice.
5024    async fn post_json_with_headers(
5025        app: &Router,
5026        uri: &str,
5027        body: serde_json::Value,
5028        headers: &[(&str, &str)],
5029    ) -> (StatusCode, serde_json::Value) {
5030        use http_body_util::BodyExt;
5031        use tower::ServiceExt;
5032
5033        let mut builder = axum::http::Request::builder()
5034            .method("POST")
5035            .uri(uri)
5036            .header("content-type", "application/json");
5037        for (name, value) in headers {
5038            builder = builder.header(*name, *value);
5039        }
5040        let response = app
5041            .clone()
5042            .oneshot(
5043                builder
5044                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5045                    .unwrap(),
5046            )
5047            .await
5048            .unwrap();
5049        let status = response.status();
5050        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5051        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
5052        (status, json)
5053    }
5054
5055    /// The three small endpoints used to be served and never recorded,
5056    /// which made the monitor wrong rather than incomplete: an editor
5057    /// hammering `/v1/embeddings` showed up as an idle server.
5058    #[tokio::test]
5059    async fn tokenize_detokenize_and_embeddings_all_land_in_the_ring() {
5060        let app = test_app();
5061
5062        let (status, _) = post_json_uri(
5063            &app,
5064            ferrox_api::routes::V1_TOKENIZE,
5065            serde_json::json!({"prompt": "hello"}),
5066        )
5067        .await;
5068        assert_eq!(status, StatusCode::OK);
5069        let (status, _) = post_json_uri(
5070            &app,
5071            ferrox_api::routes::V1_DETOKENIZE,
5072            serde_json::json!({"tokens": [104, 105]}),
5073        )
5074        .await;
5075        assert_eq!(status, StatusCode::OK);
5076        let (status, _) = post_json_uri(
5077            &app,
5078            ferrox_api::routes::V1_EMBEDDINGS,
5079            serde_json::json!({"input": "hello"}),
5080        )
5081        .await;
5082        assert_eq!(status, StatusCode::OK);
5083
5084        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5085        let routes: Vec<&str> = stats["recent"]
5086            .as_array()
5087            .unwrap()
5088            .iter()
5089            .map(|row| row["route"].as_str().unwrap())
5090            .collect();
5091        for expected in [
5092            ferrox_api::routes::V1_TOKENIZE,
5093            ferrox_api::routes::V1_DETOKENIZE,
5094            ferrox_api::routes::V1_EMBEDDINGS,
5095        ] {
5096            assert!(
5097                routes.contains(&expected),
5098                "{expected} is missing: {routes:?}"
5099            );
5100        }
5101
5102        let row = |route: &str| {
5103            stats["recent"]
5104                .as_array()
5105                .unwrap()
5106                .iter()
5107                .find(|r| r["route"] == route)
5108                .cloned()
5109                .unwrap()
5110        };
5111        // Embeddings run a forward pass, so their prompt tokens are
5112        // real prompt tokens. There is no decode loop, so `decode_ms`
5113        // stays null instead of borrowing the total.
5114        let embed = row(ferrox_api::routes::V1_EMBEDDINGS);
5115        assert!(embed["prompt_tokens"].as_u64().unwrap() > 0);
5116        assert!(embed["decode_ms"].is_null());
5117        assert_eq!(embed["completion_tokens"], 0);
5118        // Tokenizing runs the tokenizer and not the model, so it
5119        // contributes nothing to the token counters those counters
5120        // claim to measure.
5121        assert_eq!(row(ferrox_api::routes::V1_TOKENIZE)["prompt_tokens"], 0);
5122        assert_eq!(
5123            stats["tokens_prompt_total"].as_u64().unwrap(),
5124            embed["prompt_tokens"].as_u64().unwrap(),
5125            "only the forward pass counted"
5126        );
5127    }
5128
5129    /// A failed small-endpoint call is still traffic. A 400 that leaves
5130    /// no row is indistinguishable from a request that was never sent.
5131    #[tokio::test]
5132    async fn a_rejected_embeddings_request_is_recorded_with_its_status() {
5133        let app = test_app();
5134        let (status, _) = post_json_uri(
5135            &app,
5136            ferrox_api::routes::V1_EMBEDDINGS,
5137            serde_json::json!({"input": "hi", "encoding_format": "base64"}),
5138        )
5139        .await;
5140        assert_eq!(status, StatusCode::BAD_REQUEST);
5141
5142        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5143        let recent = stats["recent"].as_array().unwrap();
5144        assert_eq!(recent.len(), 1);
5145        assert_eq!(recent[0]["route"], ferrox_api::routes::V1_EMBEDDINGS);
5146        assert_eq!(recent[0]["status"], 400);
5147        assert_eq!(
5148            recent[0]["prompt_tokens"], 0,
5149            "a rejected call embedded nothing"
5150        );
5151    }
5152
5153    /// Attribution: which key served a request, and what the caller
5154    /// says it is. The key itself must never appear.
5155    #[tokio::test]
5156    async fn a_row_names_the_key_that_served_it_without_carrying_the_key() {
5157        let app = test_app();
5158        let key = "sk-monitor-secret";
5159        let (status, _) = post_json_with_headers(
5160            &app,
5161            "/v1/chat/completions",
5162            serde_json::json!({
5163                "model": "x",
5164                "messages": [{"role": "user", "content": "hi"}],
5165                "max_tokens": 2
5166            }),
5167            &[
5168                ("authorization", &format!("Bearer {key}")),
5169                ("x-ferrox-client", "ferrox-studio"),
5170            ],
5171        )
5172        .await;
5173        assert_eq!(status, StatusCode::OK);
5174
5175        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5176        let row = stats["recent"].as_array().unwrap()[0].clone();
5177        let fingerprint = row["via_api_key"]
5178            .as_str()
5179            .expect("the row names the key that served it")
5180            .to_string();
5181        assert_eq!(fingerprint, attribution::key_fingerprint(key));
5182        assert!(!fingerprint.contains(key));
5183        assert!(
5184            !serde_json::to_string(&stats).unwrap().contains(key),
5185            "the stats payload must not carry the key in any form"
5186        );
5187        assert_eq!(row["client"], "ferrox-studio");
5188    }
5189
5190    /// Two different keys are two different callers, and no key at all
5191    /// is a third answer -- not a copy of either.
5192    #[tokio::test]
5193    async fn different_keys_are_different_callers_and_no_key_is_null() {
5194        let app = test_app();
5195        let body = serde_json::json!({
5196            "model": "x",
5197            "messages": [{"role": "user", "content": "hi"}],
5198            "max_tokens": 1
5199        });
5200        for headers in [
5201            vec![("authorization", "Bearer key-one")],
5202            vec![("authorization", "Bearer key-two")],
5203            vec![],
5204        ] {
5205            let (status, _) =
5206                post_json_with_headers(&app, "/v1/chat/completions", body.clone(), &headers).await;
5207            assert_eq!(status, StatusCode::OK);
5208        }
5209
5210        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5211        let recent = stats["recent"].as_array().unwrap();
5212        assert_eq!(recent.len(), 3);
5213        let one = recent[0]["via_api_key"].as_str().unwrap();
5214        let two = recent[1]["via_api_key"].as_str().unwrap();
5215        assert_ne!(one, two, "two keys must not collapse into one caller");
5216        assert!(
5217            recent[2]["via_api_key"].is_null(),
5218            "an unauthenticated call is null, not a fingerprint of nothing"
5219        );
5220        assert!(recent[2]["client"].is_null());
5221    }
5222
5223    /// The row names the model that SERVED the request. `req.model` is
5224    /// ignored by this server -- it decodes against whatever is loaded
5225    /// -- so echoing that string back would make the log agree with the
5226    /// caller's belief instead of with what happened.
5227    #[tokio::test]
5228    async fn a_row_names_the_model_that_served_it_not_the_one_requested() {
5229        let state = Arc::new(test_state(
5230            named_test_model("really-loaded", 256),
5231            ResponseCache::new(4, Duration::from_secs(60)),
5232        ));
5233        let app = test_app_with_state(Arc::clone(&state));
5234
5235        let (status, _) = post_json_uri(
5236            &app,
5237            "/v1/chat/completions",
5238            serde_json::json!({
5239                "model": "gpt-4-turbo-that-is-not-here",
5240                "messages": [{"role": "user", "content": "hi"}],
5241                "max_tokens": 2
5242            }),
5243        )
5244        .await;
5245        assert_eq!(status, StatusCode::OK);
5246
5247        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5248        assert_eq!(stats["recent"][0]["model"], "really-loaded");
5249
5250        // Nothing loaded: nothing served it, and the row says so rather
5251        // than repeating what the request asked for.
5252        state.swap_active(None);
5253        let (status, _) = post_json_uri(
5254            &app,
5255            "/v1/chat/completions",
5256            serde_json::json!({
5257                "model": "gpt-4-turbo-that-is-not-here",
5258                "messages": [{"role": "user", "content": "hi"}]
5259            }),
5260        )
5261        .await;
5262        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5263        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5264        let recent = stats["recent"].as_array().unwrap();
5265        assert!(recent[recent.len() - 1]["model"].is_null());
5266    }
5267
5268    /// A streamed request names its model too, and names the handle it
5269    /// decoded against rather than whatever a swap made current while it
5270    /// was running.
5271    #[tokio::test]
5272    async fn a_streamed_row_names_the_model_it_decoded_against() {
5273        let state = Arc::new(test_state(
5274            named_test_model("model-before", 256),
5275            ResponseCache::new(4, Duration::from_secs(60)),
5276        ));
5277        let app = test_app_with_state(Arc::clone(&state));
5278        let _ = post_sse_raw(&app, resumable_request()).await;
5279        // The stream has finished; a swap now must not rewrite history.
5280        active_model(&state, "model-after");
5281
5282        let (_, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5283        assert_eq!(stats["recent"][0]["model"], "model-before");
5284    }
5285
5286    /// The queue gauge reports a queue that exists or says there is
5287    /// none. `0` would claim an empty queue was measured.
5288    #[tokio::test]
5289    async fn the_queue_gauge_is_null_when_nothing_can_queue() {
5290        let app = test_app();
5291        let (status, stats) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5292        assert_eq!(status, StatusCode::OK);
5293        assert!(
5294            stats["queue_depth"].is_null(),
5295            "without continuous batching nothing queues, so there is nothing to measure"
5296        );
5297        assert!(stats["queue_rejected_total"].is_null());
5298        assert_eq!(
5299            stats["generating_now"], 0,
5300            "work in progress is measured and really is zero here"
5301        );
5302    }
5303
5304    /// The raw SSE body, so the tests below can assert on the `id:` and
5305    /// `retry:` fields themselves rather than only on the JSON inside
5306    /// `data:`. Those two fields are the whole of the replay contract
5307    /// on the wire.
5308    async fn post_sse_raw(app: &Router, body: serde_json::Value) -> String {
5309        use http_body_util::BodyExt;
5310        use tower::ServiceExt;
5311
5312        let response = app
5313            .clone()
5314            .oneshot(
5315                axum::http::Request::builder()
5316                    .method("POST")
5317                    .uri("/v1/chat/completions")
5318                    .header("content-type", "application/json")
5319                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5320                    .unwrap(),
5321            )
5322            .await
5323            .unwrap();
5324        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5325        String::from_utf8(bytes.to_vec()).unwrap()
5326    }
5327
5328    async fn get_json_with_headers(
5329        app: &Router,
5330        uri: &str,
5331        headers: &[(&str, &str)],
5332    ) -> (StatusCode, serde_json::Value) {
5333        use http_body_util::BodyExt;
5334        use tower::ServiceExt;
5335
5336        let mut builder = axum::http::Request::builder().method("GET").uri(uri);
5337        for (name, value) in headers {
5338            builder = builder.header(*name, *value);
5339        }
5340        let response = app
5341            .clone()
5342            .oneshot(builder.body(axum::body::Body::empty()).unwrap())
5343            .await
5344            .unwrap();
5345        let status = response.status();
5346        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5347        (
5348            status,
5349            serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({})),
5350        )
5351    }
5352
5353    fn sse_field<'a>(body: &'a str, field: &str) -> Vec<&'a str> {
5354        body.lines()
5355            .filter_map(|line| line.strip_prefix(field))
5356            .map(str::trim)
5357            .collect()
5358    }
5359
5360    fn resumable_request() -> serde_json::Value {
5361        serde_json::json!({
5362            "model": "m",
5363            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
5364            "max_tokens": 4,
5365            "temperature": 0,
5366            "stream": true,
5367            "stream_resumable": true,
5368        })
5369    }
5370
5371    /// The wire half of the replay contract: every event is numbered,
5372    /// the numbers are qualified by the request so a `Last-Event-ID`
5373    /// cannot be mistaken for a position in another stream, and the
5374    /// reconnect delay is stated once.
5375    #[tokio::test]
5376    async fn a_resumable_stream_numbers_every_event_and_states_retry_once() {
5377        let app = test_app();
5378        let body = post_sse_raw(&app, resumable_request()).await;
5379
5380        let request_id = body
5381            .lines()
5382            .find_map(|l| l.strip_prefix("data: "))
5383            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
5384            .and_then(|v| v["request_id"].as_str().map(str::to_string))
5385            .expect("the first chunk names the request");
5386
5387        let ids = sse_field(&body, "id:");
5388        let datas = sse_field(&body, "data:");
5389        assert_eq!(
5390            ids.len(),
5391            datas.len(),
5392            "every event carries an id, or a reconnect cannot name where it stopped"
5393        );
5394        for (i, id) in ids.iter().enumerate() {
5395            assert_eq!(*id, format!("{request_id}:{i}"));
5396        }
5397        let retries = sse_field(&body, "retry:");
5398        assert_eq!(
5399            retries.len(),
5400            1,
5401            "the reconnect delay is stated once, not on every event"
5402        );
5403        assert_eq!(retries[0], "1500");
5404        assert!(
5405            body.contains("data: [DONE]"),
5406            "the end of stream is still stated"
5407        );
5408    }
5409
5410    /// The refusal this feature was written around: an `id:` with no
5411    /// replay buffer behind it tells a client it may reconnect into
5412    /// something that does not exist.
5413    #[tokio::test]
5414    async fn a_plain_stream_carries_no_id_because_nothing_could_replay_it() {
5415        let app = test_app();
5416        let mut request = resumable_request();
5417        request["stream_resumable"] = serde_json::json!(false);
5418        let body = post_sse_raw(&app, request).await;
5419        assert!(!sse_field(&body, "data:").is_empty(), "it still streams");
5420        assert!(
5421            sse_field(&body, "id:").is_empty(),
5422            "an id promises a replay this stream cannot serve"
5423        );
5424        assert!(sse_field(&body, "retry:").is_empty());
5425    }
5426
5427    /// The polling fallback, which is the answer to the proxy that
5428    /// buffers `text/event-stream`: the same events, over a short JSON
5429    /// response nothing can hold back.
5430    #[tokio::test]
5431    async fn the_polling_fallback_serves_exactly_what_the_stream_delivered() {
5432        let app = test_app();
5433        let body = post_sse_raw(&app, resumable_request()).await;
5434        let request_id = sse_field(&body, "id:")[0]
5435            .rsplit_once(':')
5436            .unwrap()
5437            .0
5438            .to_string();
5439        let streamed: Vec<String> = sse_field(&body, "data:")
5440            .iter()
5441            .map(|d| d.to_string())
5442            .collect();
5443
5444        let (status, polled) = get_json(
5445            &app,
5446            &format!("{}?from=0", ferrox_api::routes::v1_stream_poll(&request_id)),
5447        )
5448        .await;
5449        assert_eq!(status, StatusCode::OK);
5450        let events: Vec<String> = polled["events"]
5451            .as_array()
5452            .unwrap()
5453            .iter()
5454            .map(|e| e["data"].as_str().unwrap().to_string())
5455            .collect();
5456        assert_eq!(
5457            events, streamed,
5458            "the fallback must deliver the same answer, not a re-run of it"
5459        );
5460        assert_eq!(polled["request_id"], request_id);
5461        assert_eq!(
5462            polled["done"], false,
5463            "events were still being handed out, so the client must ask again"
5464        );
5465
5466        // Drained: only now is it done, so a client that stops on
5467        // `done` never discards events it was not given.
5468        let next = polled["next_index"].as_u64().unwrap();
5469        let (_, drained) = get_json(
5470            &app,
5471            &format!(
5472                "{}?from={next}",
5473                ferrox_api::routes::v1_stream_poll(&request_id)
5474            ),
5475        )
5476        .await;
5477        assert_eq!(drained["done"], true);
5478        assert_eq!(drained["events"].as_array().unwrap().len(), 0);
5479    }
5480
5481    /// A resume returns what was missed and not what was already
5482    /// rendered -- repeating delivered tokens would make replay worse
5483    /// than starting over.
5484    #[tokio::test]
5485    async fn a_resume_continues_after_the_last_event_id_rather_than_repeating() {
5486        let app = test_app();
5487        let body = post_sse_raw(&app, resumable_request()).await;
5488        let ids = sse_field(&body, "id:");
5489        let datas: Vec<String> = sse_field(&body, "data:")
5490            .iter()
5491            .map(|d| d.to_string())
5492            .collect();
5493        assert!(
5494            ids.len() >= 3,
5495            "need a few events to resume into the middle"
5496        );
5497        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
5498
5499        let (status, resumed) = get_json_with_headers(
5500            &app,
5501            &format!("{}/poll", ferrox_api::routes::v1_stream(&request_id)),
5502            &[],
5503        )
5504        .await;
5505        assert_eq!(status, StatusCode::OK);
5506        assert_eq!(resumed["events"].as_array().unwrap().len(), datas.len());
5507
5508        // Now from the middle, the way a reconnect would.
5509        let (_, tail) = get_json(
5510            &app,
5511            &format!("{}?from=2", ferrox_api::routes::v1_stream_poll(&request_id)),
5512        )
5513        .await;
5514        let tail_events: Vec<String> = tail["events"]
5515            .as_array()
5516            .unwrap()
5517            .iter()
5518            .map(|e| e["data"].as_str().unwrap().to_string())
5519            .collect();
5520        assert_eq!(tail_events, datas[2..].to_vec());
5521    }
5522
5523    /// Reconnecting over SSE picks up where the last id left off, with
5524    /// the ids still attached so a second drop can be resumed too.
5525    #[tokio::test]
5526    async fn an_sse_reconnect_resumes_from_the_last_event_id() {
5527        use http_body_util::BodyExt;
5528        use tower::ServiceExt;
5529
5530        let app = test_app();
5531        let body = post_sse_raw(&app, resumable_request()).await;
5532        let ids = sse_field(&body, "id:");
5533        let datas: Vec<String> = sse_field(&body, "data:")
5534            .iter()
5535            .map(|d| d.to_string())
5536            .collect();
5537        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
5538
5539        let response = app
5540            .clone()
5541            .oneshot(
5542                axum::http::Request::builder()
5543                    .method("GET")
5544                    .uri(ferrox_api::routes::v1_stream(&request_id))
5545                    .header("last-event-id", format!("{request_id}:0"))
5546                    .body(axum::body::Body::empty())
5547                    .unwrap(),
5548            )
5549            .await
5550            .unwrap();
5551        assert_eq!(response.status(), StatusCode::OK);
5552        assert_eq!(
5553            response
5554                .headers()
5555                .get("x-accel-buffering")
5556                .and_then(|v| v.to_str().ok()),
5557            Some("no"),
5558            "the reconnect needs the same anti-buffering header as the stream"
5559        );
5560        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5561        let resumed = String::from_utf8(bytes.to_vec()).unwrap();
5562        assert_eq!(
5563            sse_field(&resumed, "data:")
5564                .iter()
5565                .map(|d| d.to_string())
5566                .collect::<Vec<_>>(),
5567            datas[1..].to_vec()
5568        );
5569        assert_eq!(sse_field(&resumed, "id:")[0], format!("{request_id}:1"));
5570    }
5571
5572    /// A `Last-Event-ID` from another stream is refused rather than
5573    /// rounded down to zero: replaying a whole different answer would
5574    /// be a silent, confident lie.
5575    #[tokio::test]
5576    async fn a_last_event_id_from_another_stream_is_refused() {
5577        let app = test_app();
5578        let body = post_sse_raw(&app, resumable_request()).await;
5579        let request_id = sse_field(&body, "id:")[0]
5580            .rsplit_once(':')
5581            .unwrap()
5582            .0
5583            .to_string();
5584
5585        let (status, err) = get_json_with_headers(
5586            &app,
5587            &ferrox_api::routes::v1_stream(&request_id),
5588            &[("last-event-id", "chatcmpl-someone-else:3")],
5589        )
5590        .await;
5591        assert_eq!(status, StatusCode::BAD_REQUEST);
5592        assert_eq!(err["error"]["code"], "bad_last_event_id");
5593    }
5594
5595    /// A stream that was never resumable, or has been forgotten, is a
5596    /// 404 that says which -- not an empty stream that reads as an
5597    /// answer with no tokens in it.
5598    #[tokio::test]
5599    async fn resuming_a_stream_that_was_never_resumable_is_a_404_that_says_why() {
5600        let app = test_app();
5601        let mut request = resumable_request();
5602        request["stream_resumable"] = serde_json::json!(false);
5603        let body = post_sse_raw(&app, request).await;
5604        let request_id = body
5605            .lines()
5606            .find_map(|l| l.strip_prefix("data: "))
5607            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
5608            .and_then(|v| v["request_id"].as_str().map(str::to_string))
5609            .unwrap();
5610
5611        let (status, err) = get_json(&app, &ferrox_api::routes::v1_stream_poll(&request_id)).await;
5612        assert_eq!(status, StatusCode::NOT_FOUND);
5613        assert_eq!(err["error"]["code"], "stream_not_found");
5614        assert!(err["error"]["message"]
5615            .as_str()
5616            .unwrap()
5617            .contains("stream_resumable"));
5618    }
5619
5620    /// The published template and the router's pattern must describe
5621    /// the same path, or a client built from `ferrox_api::routes` asks
5622    /// for something this server does not serve.
5623    #[test]
5624    fn the_axum_stream_patterns_match_the_published_templates() {
5625        assert_eq!(
5626            axum_path(ferrox_api::routes::V1_STREAM),
5627            "/v1/stream/:request_id"
5628        );
5629        assert_eq!(
5630            axum_path(ferrox_api::routes::V1_STREAM_POLL),
5631            "/v1/stream/:request_id/poll"
5632        );
5633        assert_eq!(
5634            ferrox_api::routes::v1_stream("abc"),
5635            axum_path(ferrox_api::routes::V1_STREAM).replace(":request_id", "abc")
5636        );
5637    }
5638
5639    /// Every published template goes through the converter, and what
5640    /// comes out has no braces left in it.
5641    ///
5642    /// The two Responses routes were mounted raw, so axum matched the
5643    /// literal segment `{response_id}` and a real id fell through to a
5644    /// bodiless 404. The test router had the same two lines, which is
5645    /// why nothing caught it. This walks the templates instead of
5646    /// naming them, so the next one added is covered without anybody
5647    /// remembering to come back here.
5648    #[test]
5649    fn no_published_template_reaches_the_router_with_its_braces() {
5650        for template in [
5651            ferrox_api::routes::V1_STREAM,
5652            ferrox_api::routes::V1_STREAM_POLL,
5653            ferrox_api::routes::V1_RESPONSE,
5654            ferrox_api::routes::V1_RESPONSE_CANCEL,
5655            ferrox_api::routes::ADMIN_TASK_CANCEL,
5656        ] {
5657            assert!(
5658                template.contains('{'),
5659                "{template} is in the template list but has no placeholder"
5660            );
5661            let mounted = axum_path(template);
5662            assert!(
5663                !mounted.contains('{') && !mounted.contains('}'),
5664                "{template} would be mounted as {mounted}, whose braces axum reads as a literal segment"
5665            );
5666            assert!(
5667                mounted.contains(':'),
5668                "{template} lost its placeholder entirely and would match one path only"
5669            );
5670        }
5671    }
5672
5673    /// A real id must reach the handler, not axum's catch-all 404.
5674    ///
5675    /// The distinction is the whole point: axum answers an unmatched
5676    /// path with an empty body, while the handler answers an unknown id
5677    /// with a reasoned JSON error. Asserting on the body rather than
5678    /// the status is what separates "the route is missing" from "the
5679    /// response is not here".
5680    #[tokio::test]
5681    async fn an_unknown_response_id_gets_the_handler_not_a_bare_404() {
5682        let app = test_app();
5683        let (status, body) = get_json(&app, "/v1/responses/resp_nonexistent").await;
5684        assert_eq!(status, StatusCode::NOT_FOUND);
5685        assert!(
5686            !body.is_null(),
5687            "empty body means axum never matched the route, so the id was read as a literal segment"
5688        );
5689    }
5690
5691    /// An empty task list is a list, not a missing key -- the UI renders
5692    /// "no jobs" from it rather than from an error.
5693    #[tokio::test]
5694    async fn the_task_list_starts_empty_rather_than_absent() {
5695        let app = test_app();
5696        let (status, body) = get_json(&app, ferrox_api::routes::ADMIN_TASKS).await;
5697        assert_eq!(status, StatusCode::OK);
5698        assert_eq!(body["tasks"].as_array().unwrap().len(), 0);
5699    }
5700
5701    async fn post_json_uri(
5702        app: &Router,
5703        uri: &str,
5704        body: serde_json::Value,
5705    ) -> (StatusCode, serde_json::Value) {
5706        use http_body_util::BodyExt;
5707        use tower::ServiceExt;
5708
5709        let response = app
5710            .clone()
5711            .oneshot(
5712                axum::http::Request::builder()
5713                    .method("POST")
5714                    .uri(uri)
5715                    .header("content-type", "application/json")
5716                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5717                    .unwrap(),
5718            )
5719            .await
5720            .unwrap();
5721        let status = response.status();
5722        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5723        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
5724        (status, json)
5725    }
5726
5727    async fn post_json(app: &Router, body: serde_json::Value) -> serde_json::Value {
5728        post_json_uri(app, "/v1/chat/completions", body).await.1
5729    }
5730
5731    /// The engine's live footprint, beside the budget it was sized
5732    /// against. Two things are asserted rather than the number itself,
5733    /// which is a property of the host: it is never a ZERO (an engine
5734    /// using no memory is not a thing that happens, so a zero would be
5735    /// a failed read presented as a fact), and it always says WHICH
5736    /// quantity it is -- a caller comparing a PSS figure with an RSS
5737    /// one is comparing two different things and will read the
5738    /// difference as a leak.
5739    #[tokio::test]
5740    async fn stats_says_what_the_engine_is_using_and_which_quantity_that_is() {
5741        let app = test_app();
5742        let (status, body) = get_json(&app, ferrox_api::routes::V1_STATS).await;
5743        assert_eq!(status, StatusCode::OK);
5744
5745        let memory = &body["memory"];
5746        if memory.is_null() {
5747            // No `/proc`: absent is the honest answer, and the point of
5748            // this branch is that it is absent rather than zero.
5749            return;
5750        }
5751        assert!(
5752            memory["bytes"].as_u64().is_some_and(|b| b > 0),
5753            "a read that produced a zero is a broken read, not an idle \
5754             engine: {memory}"
5755        );
5756        assert!(
5757            ["pss", "rss"].contains(&memory["kind"].as_str().unwrap_or("")),
5758            "the quantity must travel with the number: {memory}"
5759        );
5760    }
5761
5762    /// A pool this deployment does not have is reported `null`, never
5763    /// as a zero row. "No window pool" and "a window pool with nothing
5764    /// in it" are different facts, and an operator shown the second for
5765    /// the first sizes against a pool that does not exist. The test
5766    /// state runs with no shared KV pool, so all three are absent here.
5767    #[tokio::test]
5768    async fn stats_reports_a_pool_it_does_not_have_as_absent_and_not_as_zero() {
5769        let app = test_app();
5770        let (status, body) = get_json(&app, ferrox_api::routes::V1_STATS).await;
5771        assert_eq!(status, StatusCode::OK);
5772        for pool in ["kv_pages", "window_slots", "state_slots"] {
5773            assert!(
5774                body["pools"][pool].is_null(),
5775                "{pool} must be null rather than a zero row: {}",
5776                body["pools"]
5777            );
5778        }
5779    }
5780
5781    /// A streamed `/v1/messages` can be cancelled only if the client
5782    /// can learn the id, and the Anthropic protocol has no field for
5783    /// it -- the `message_start` `msg_...` is a different identifier
5784    /// the cancel registry has never seen. So the header carries it,
5785    /// on the success path and on the error path alike, because a
5786    /// client that logs one id per call should not lose it exactly
5787    /// when something went wrong.
5788    #[tokio::test]
5789    async fn a_messages_response_states_the_id_that_v1_cancel_takes() {
5790        use http_body_util::BodyExt;
5791        use tower::ServiceExt;
5792
5793        let app = test_app();
5794        let send = |body: serde_json::Value| {
5795            let app = app.clone();
5796            async move {
5797                app.oneshot(
5798                    axum::http::Request::builder()
5799                        .method("POST")
5800                        .uri(ferrox_api::routes::V1_MESSAGES)
5801                        .header("content-type", "application/json")
5802                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5803                        .unwrap(),
5804                )
5805                .await
5806                .unwrap()
5807            }
5808        };
5809
5810        let ok = send(serde_json::json!({
5811            "model": "test",
5812            "max_tokens": 1,
5813            "messages": [{"role": "user", "content": "hi"}],
5814        }))
5815        .await;
5816        assert_eq!(ok.status(), StatusCode::OK);
5817        let id = ok
5818            .headers()
5819            .get("request-id")
5820            .expect("a served message names its id")
5821            .to_str()
5822            .unwrap()
5823            .to_string();
5824        assert!(!id.is_empty());
5825
5826        // A rejected body still gets one, and a different one: two calls
5827        // must never collide in the ring.
5828        let bad = send(serde_json::json!({"model": "test"})).await;
5829        assert!(bad.status().is_client_error());
5830        let other = bad.headers().get("request-id").expect("errors too");
5831        assert_ne!(other.to_str().unwrap(), id);
5832        let _ = bad.into_body().collect().await.unwrap();
5833    }
5834
5835    /// The gate is the point of the rebuild endpoint: a request that
5836    /// arrives while the KV pool is being re-split must be refused,
5837    /// because admitting it would let a decode allocate out of a pool
5838    /// whose block count is about to change under it. `503` and not
5839    /// `500` -- the caller should retry in a moment, and the body says
5840    /// which of the four closed states it hit so a client can tell
5841    /// "not yet" from "not ever".
5842    #[tokio::test]
5843    async fn a_request_that_arrives_mid_rebuild_is_refused_and_admitted_again_after() {
5844        let state = Arc::new(test_state(
5845            test_model_full_byte_vocab(),
5846            ResponseCache::new(1000, Duration::from_secs(3600)),
5847        ));
5848        let app = test_app_with_state(Arc::clone(&state));
5849        let body = serde_json::json!({
5850            "model": "test",
5851            "messages": [{"role": "user", "content": "hi"}],
5852            "max_tokens": 1,
5853        });
5854
5855        state
5856            .maintenance
5857            .lock()
5858            .unwrap()
5859            .begin_rebuild()
5860            .expect("a fresh server is serving, so the rebuild starts");
5861        let (status, refused) = post_json_uri(&app, "/v1/chat/completions", body.clone()).await;
5862        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5863        assert_eq!(refused["error"]["type"], "cache_rebuilding");
5864
5865        state.maintenance.lock().unwrap().finish_rebuild(true);
5866        let (status, _) = post_json_uri(&app, "/v1/chat/completions", body).await;
5867        assert_eq!(
5868            status,
5869            StatusCode::OK,
5870            "the gate reopens; a rebuild is not a latch"
5871        );
5872    }
5873
5874    /// Cancelling an id that is not generating must not answer `200`.
5875    /// A UI told "ok" for an already-finished request would report that
5876    /// it stopped work it did not stop, and the two outcomes are the
5877    /// only thing this endpoint exists to distinguish.
5878    #[tokio::test]
5879    async fn cancelling_an_id_that_is_not_generating_is_a_404_that_says_so() {
5880        let app = test_app();
5881        let (status, body) = post_json_uri(
5882            &app,
5883            ferrox_api::routes::V1_CANCEL,
5884            serde_json::json!({ "request_id": "chatcmpl-never-issued" }),
5885        )
5886        .await;
5887        assert_eq!(status, StatusCode::NOT_FOUND);
5888        assert_eq!(body["cancelled"], serde_json::json!(false));
5889        assert_eq!(body["request_id"], "chatcmpl-never-issued");
5890        assert!(
5891            body["detail"].as_str().is_some_and(|d| !d.is_empty()),
5892            "the verdict must carry a human reason: {body}"
5893        );
5894    }
5895
5896    /// The endpoint reaches the registry the streaming path registers
5897    /// into -- not a second, parallel one. Registered by hand here
5898    /// because a `oneshot` router cannot hold a stream open.
5899    #[tokio::test]
5900    async fn cancelling_a_live_generation_signals_its_token_and_answers_200() {
5901        let state = Arc::new(test_state(
5902            test_model_full_byte_vocab(),
5903            ResponseCache::new(1000, Duration::from_secs(3600)),
5904        ));
5905        let app = test_app_with_state(Arc::clone(&state));
5906        let (token, _guard) = state.cancels.register("chatcmpl-live");
5907
5908        let (status, before) = get_json(&app, ferrox_api::routes::ADMIN_STATS).await;
5909        assert_eq!(status, StatusCode::OK);
5910        assert_eq!(before["generating_now"], serde_json::json!(1));
5911
5912        let (status, body) = post_json_uri(
5913            &app,
5914            ferrox_api::routes::V1_CANCEL,
5915            serde_json::json!({ "request_id": "chatcmpl-live" }),
5916        )
5917        .await;
5918        assert_eq!(status, StatusCode::OK);
5919        assert_eq!(body["cancelled"], serde_json::json!(true));
5920        assert!(
5921            token.is_cancelled(),
5922            "the endpoint answered ok without setting the flag the decode loop reads"
5923        );
5924    }
5925
5926    #[tokio::test]
5927    async fn tokenize_detokenize_roundtrip_and_embeddings_mean() {
5928        let app = test_app();
5929        let (status, tok) =
5930            post_json_uri(&app, "/v1/tokenize", serde_json::json!({ "prompt": "Hi" })).await;
5931        assert_eq!(status, StatusCode::OK);
5932        let tokens = tok["tokens"].as_array().unwrap();
5933        assert_eq!(tok["count"], tokens.len());
5934        assert!(!tokens.is_empty());
5935
5936        let (status, detok) = post_json_uri(
5937            &app,
5938            "/v1/detokenize",
5939            serde_json::json!({ "tokens": tokens }),
5940        )
5941        .await;
5942        assert_eq!(status, StatusCode::OK);
5943        assert_eq!(detok["text"], "Hi");
5944
5945        let (status, emb) = post_json_uri(
5946            &app,
5947            "/v1/embeddings",
5948            serde_json::json!({
5949                "input": "Hi",
5950                "embedding_type": "mean"
5951            }),
5952        )
5953        .await;
5954        assert_eq!(status, StatusCode::OK);
5955        let vec = emb["data"][0]["embedding"].as_array().unwrap();
5956        assert!(!vec.is_empty());
5957        assert!(vec.iter().all(|v| v.as_f64().is_some()));
5958    }
5959
5960    /// The /metrics endpoint must expose the bounded expert cache's
5961    /// counters when the model streams routed experts, and the
5962    /// counters must reflect real decode activity (a forward pass
5963    /// through store-backed MoE layers produces misses/hits).
5964    #[tokio::test]
5965    async fn metrics_exposes_expert_store_counters_when_streaming_is_active() {
5966        use http_body_util::BodyExt;
5967        use tower::ServiceExt;
5968
5969        let fixture = concat!(
5970            "../ferrox-models/tests/fixtures/",
5971            "ferrox_real_moe_test.gguf"
5972        );
5973        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
5974        let decoder = Decoder::from_gguf_with_expert_cache(
5975            &fixture,
5976            ferrox_models::config::test_moe_fixture(),
5977            Some(1024 * 1024),
5978        )
5979        .expect("MoE fixture must load store-backed");
5980
5981        // Drive one real forward pass so the store sees decode
5982        // activity (the fixture's tiny vocab can't survive the HTTP
5983        // path's template text, so decode directly).
5984        let mut caches: Vec<ferrox_core::cache::KvCache> = decoder
5985            .layers
5986            .iter()
5987            .map(|_| {
5988                ferrox_core::cache::KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim)
5989            })
5990            .collect();
5991        decoder.forward_token(1, 0, &mut caches);
5992
5993        let model = Model::Gguf(GgufModel {
5994            decoder: Arc::new(decoder),
5995            tokenizer: Arc::new(ServerTokenizer::Byte),
5996            stop_tokens: StopTokens::default(),
5997            bos_id: None,
5998            is_synthetic: false,
5999            chat_template: chat_template::PromptTemplate::plain(),
6000        });
6001        let state = Arc::new(test_state(
6002            model,
6003            ResponseCache::new(16, Duration::from_secs(60)),
6004        ));
6005        let app = Router::new()
6006            .route("/metrics", axum::routing::get(metrics))
6007            .route("/v1/chat/completions", post(chat_completions))
6008            .with_state(state);
6009
6010        let fetch_metrics = |app: Router| async move {
6011            let resp = app
6012                .oneshot(
6013                    axum::http::Request::builder()
6014                        .method("GET")
6015                        .uri("/metrics")
6016                        .body(axum::body::Body::empty())
6017                        .unwrap(),
6018                )
6019                .await
6020                .unwrap();
6021            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
6022            String::from_utf8(bytes.to_vec()).unwrap()
6023        };
6024
6025        let after = fetch_metrics(app.clone()).await;
6026        assert!(
6027            after.contains("ferrox_expert_cache_misses_total"),
6028            "streaming model must expose expert-cache metrics: {after}"
6029        );
6030        let misses: u64 = after
6031            .lines()
6032            .find(|l| l.starts_with("ferrox_expert_cache_misses_total"))
6033            .and_then(|l| l.split_whitespace().nth(1))
6034            .and_then(|v| v.parse().ok())
6035            .expect("misses metric line must parse");
6036        assert!(
6037            misses > 0,
6038            "decode must have read experts through the store: {after}"
6039        );
6040    }
6041
6042    fn weather_tool() -> serde_json::Value {
6043        serde_json::json!({
6044            "type": "function",
6045            "function": {
6046                "name": "get_weather",
6047                "description": "Get the current weather for a location.",
6048                "parameters": {
6049                    "type": "object",
6050                    "properties": {"location": {"type": "string"}},
6051                    "required": ["location"]
6052                }
6053            }
6054        })
6055    }
6056
6057    fn weather_tool_def() -> ToolDef {
6058        ToolDef {
6059            kind: "function".to_string(),
6060            function: ToolFunctionDef {
6061                name: "get_weather".to_string(),
6062                description: Some("Get the current weather for a location.".to_string()),
6063                parameters: Some(serde_json::json!({
6064                    "type": "object",
6065                    "properties": {"location": {"type": "string"}},
6066                    "required": ["location"]
6067                })),
6068            },
6069        }
6070    }
6071
6072    #[test]
6073    fn tool_preamble_mentions_every_tool_name_and_description() {
6074        let preamble = tool_preamble(&[weather_tool_def()]);
6075        assert!(preamble.contains("get_weather"));
6076        assert!(preamble.contains("Get the current weather for a location."));
6077        assert!(preamble.contains("<tool_call>"));
6078        assert!(preamble.contains("</tool_call>"));
6079    }
6080
6081    #[test]
6082    fn a_real_marker_becomes_a_structured_tool_call() {
6083        let text = "sure, let me check.<tool_call>{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}</tool_call>";
6084        let (message, finish) = build_response_message(
6085            text.to_string(),
6086            &[weather_tool_def()],
6087            output::OutputPosture::for_model("test-model"),
6088            "stop",
6089        );
6090        assert_eq!(finish, "tool_calls");
6091        let calls = message.tool_calls.expect("must carry a tool call");
6092        assert_eq!(calls[0].function.name, "get_weather");
6093        let parsed: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
6094        assert_eq!(parsed["location"], "Paris");
6095    }
6096
6097    #[test]
6098    fn a_plain_answer_is_not_promoted_to_a_tool_call() {
6099        let (message, finish) = build_response_message(
6100            "just an answer".to_string(),
6101            &[weather_tool_def()],
6102            output::OutputPosture::for_model("test-model"),
6103            "stop",
6104        );
6105        assert_eq!(finish, "stop");
6106        assert!(message.tool_calls.is_none());
6107        assert_eq!(message.content.as_deref(), Some("just an answer"));
6108    }
6109
6110    /// Malformed JSON inside the marker is not a call. Returning it as
6111    /// one would hand a client arguments it cannot parse.
6112    #[test]
6113    fn a_malformed_payload_is_not_a_tool_call() {
6114        let (message, finish) = build_response_message(
6115            "<tool_call>not valid json at all</tool_call>".to_string(),
6116            &[weather_tool_def()],
6117            output::OutputPosture::for_model("test-model"),
6118            "stop",
6119        );
6120        assert_eq!(finish, "stop");
6121        assert!(message.tool_calls.is_none());
6122    }
6123
6124    /// A call to something the request never offered is refused: the
6125    /// client would be asked to execute a tool it does not have.
6126    #[test]
6127    fn a_tool_that_was_never_offered_is_not_returned() {
6128        let (message, finish) = build_response_message(
6129            "<tool_call>{\"name\": \"ping\", \"arguments\": {}}</tool_call>".to_string(),
6130            &[weather_tool_def()],
6131            output::OutputPosture::for_model("test-model"),
6132            "stop",
6133        );
6134        assert_eq!(finish, "stop");
6135        assert!(message.tool_calls.is_none());
6136    }
6137
6138    /// With no tools offered at all, marker text is just text.
6139    #[test]
6140    fn marker_text_with_no_tools_offered_stays_content() {
6141        let (message, finish) = build_response_message(
6142            "<tool_call>{\"name\": \"get_weather\", \"arguments\": {}}</tool_call>".to_string(),
6143            &[],
6144            output::OutputPosture::for_model("test-model"),
6145            "stop",
6146        );
6147        assert_eq!(finish, "stop");
6148        assert!(message.tool_calls.is_none());
6149        assert!(message.content.is_some());
6150    }
6151
6152    /// The streaming contract a coding agent depends on: the call's
6153    /// identity arrives first, then its arguments in pieces, and the
6154    /// pieces concatenate to exactly the final arguments.
6155    #[test]
6156    fn a_streamed_call_opens_then_delivers_its_arguments_in_pieces() {
6157        let opened = std::cell::Cell::new(0usize);
6158        let mut parser = crate::policy::parser::ToolCallParser::new(
6159            crate::policy::parser::ToolCallFormat::Qwen3Coder,
6160            vec![
6161                crate::policy::parser::tool_call::ToolSchema::with_parameters(
6162                    "write_file",
6163                    serde_json::json!({"type": "object", "properties": {
6164                        "path": {"type": "string"},
6165                        "contents": {"type": "string"}
6166                    }}),
6167                ),
6168            ],
6169        );
6170        let wire = "<tool_call><function=write_file>\
6171                    <parameter=path>\n/tmp/x\n</parameter>\
6172                    <parameter=contents>\nhello world\n</parameter>\
6173                    </function></tool_call>";
6174
6175        let mut deltas = Vec::new();
6176        let mut text = String::new();
6177        for piece in wire.as_bytes().chunks(7) {
6178            let chunk = String::from_utf8_lossy(piece).into_owned();
6179            let (more_text, more) = tool_call_deltas(parser.push(&chunk), &opened);
6180            text.push_str(&more_text);
6181            deltas.extend(more);
6182        }
6183        let (more_text, more) = tool_call_deltas(parser.finish(), &opened);
6184        text.push_str(&more_text);
6185        deltas.extend(more);
6186
6187        assert_eq!(opened.get(), 1, "one call opened");
6188        assert!(text.is_empty(), "the markers are not content: {text:?}");
6189
6190        let first = &deltas[0];
6191        assert_eq!(first.index, 0);
6192        assert_eq!(first.id.as_deref(), Some("call_0"));
6193        assert_eq!(first.kind, Some("function"));
6194        assert_eq!(first.function.name.as_deref(), Some("write_file"));
6195
6196        // Everything after the opening delta is argument text only,
6197        // and it parses once concatenated.
6198        let joined: String = deltas
6199            .iter()
6200            .filter_map(|d| d.function.arguments.clone())
6201            .collect();
6202        let parsed: serde_json::Value =
6203            serde_json::from_str(&joined).expect("the fragments concatenate to valid JSON");
6204        assert_eq!(parsed["path"], serde_json::json!("/tmp/x"));
6205        assert_eq!(parsed["contents"], serde_json::json!("hello world"));
6206        assert!(
6207            deltas.len() >= 3,
6208            "the arguments arrived in pieces, not whole: {}",
6209            deltas.len()
6210        );
6211        assert!(
6212            deltas[1..].iter().all(|d| d.function.name.is_none()),
6213            "only the opening delta carries identity"
6214        );
6215    }
6216
6217    /// Text either side of a call still streams as content, in order.
6218    #[test]
6219    fn text_around_a_streamed_call_is_still_content() {
6220        let opened = std::cell::Cell::new(0usize);
6221        let mut parser = crate::policy::parser::ToolCallParser::new(
6222            crate::policy::parser::ToolCallFormat::Qwen25,
6223            vec![crate::policy::parser::tool_call::ToolSchema::new(
6224                "get_weather",
6225            )],
6226        );
6227        let wire = "let me check. <tool_call>{\"name\": \"get_weather\", \
6228                    \"arguments\": {}}</tool_call> done";
6229        let mut text = String::new();
6230        for piece in wire.as_bytes().chunks(5) {
6231            let chunk = String::from_utf8_lossy(piece).into_owned();
6232            let (more, _) = tool_call_deltas(parser.push(&chunk), &opened);
6233            text.push_str(&more);
6234        }
6235        let (more, _) = tool_call_deltas(parser.finish(), &opened);
6236        text.push_str(&more);
6237
6238        assert_eq!(opened.get(), 1);
6239        assert!(text.starts_with("let me check. "), "{text:?}");
6240        assert!(text.ends_with(" done"), "{text:?}");
6241        assert!(!text.contains("<tool_call>"), "markers leaked: {text:?}");
6242    }
6243
6244    /// A reasoning model's thinking must not be returned as its
6245    /// answer.
6246    #[test]
6247    fn a_reasoning_block_is_split_out_of_the_answer() {
6248        let (message, finish) = build_response_message(
6249            "<think>weighing it up</think>The answer is 4.".to_string(),
6250            &[],
6251            output::OutputPosture::for_model("Qwen3-8B"),
6252            "stop",
6253        );
6254        assert_eq!(finish, "stop");
6255        assert_eq!(message.content.as_deref(), Some("The answer is 4."));
6256        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
6257    }
6258
6259    /// ... and a model with no reasoning format keeps its text intact,
6260    /// markers and all.
6261    #[test]
6262    fn a_non_reasoning_model_keeps_a_literal_marker_in_its_answer() {
6263        let (message, _) = build_response_message(
6264            "Use the <think> tag like this.".to_string(),
6265            &[],
6266            output::OutputPosture::for_model("llama-3.1-8b"),
6267            "stop",
6268        );
6269        assert_eq!(
6270            message.content.as_deref(),
6271            Some("Use the <think> tag like this.")
6272        );
6273        assert!(message.reasoning_content.is_none());
6274    }
6275
6276    /// Zero-regression proof: an ordinary request with no `tools`/
6277    /// `session_id` produces the plain response shape -- `content` a
6278    /// string, no `tool_calls` field -- with an honest finish reason:
6279    /// this 4-token greedy request truncates at `max_tokens`, so
6280    /// `finish_reason` must be "length" (an earlier version hardcoded
6281    /// "stop" for every non-streaming response), and `usage` counts
6282    /// exactly the generated tokens.
6283    #[tokio::test]
6284    async fn a_request_with_no_tools_or_session_behaves_exactly_as_before() {
6285        let app = test_app();
6286        let body = serde_json::json!({
6287            "model": "m",
6288            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6289            "max_tokens": 4,
6290            "temperature": 0,
6291        });
6292        let resp = post_json(&app, body).await;
6293        let message = &resp["choices"][0]["message"];
6294        assert!(message["content"].is_string());
6295        assert!(message.get("tool_calls").is_none());
6296        assert_eq!(resp["choices"][0]["finish_reason"], "length");
6297        assert_eq!(resp["usage"]["completion_tokens"], 4);
6298        assert_eq!(
6299            resp["usage"]["total_tokens"],
6300            resp["usage"]["prompt_tokens"].as_u64().unwrap() + 4
6301        );
6302    }
6303
6304    async fn get_json(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
6305        use http_body_util::BodyExt;
6306        use tower::ServiceExt;
6307
6308        let response = app
6309            .clone()
6310            .oneshot(
6311                axum::http::Request::builder()
6312                    .method("GET")
6313                    .uri(uri)
6314                    .body(axum::body::Body::empty())
6315                    .unwrap(),
6316            )
6317            .await
6318            .unwrap();
6319        let status = response.status();
6320        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6321        (status, serde_json::from_slice(&bytes).unwrap())
6322    }
6323
6324    #[tokio::test]
6325    async fn health_answers_a_capability_handshake_not_a_boolean() {
6326        let app = test_app();
6327        let (status, body) = get_json(&app, ferrox_api::routes::HEALTH).await;
6328        assert_eq!(status, StatusCode::OK);
6329
6330        let health: ferrox_api::HealthResponse = serde_json::from_value(body).unwrap();
6331        assert_eq!(health.state, ferrox_api::HealthState::Ready);
6332        assert!(health.pid > 0);
6333        assert!(health.server_time_unix_ms > 0);
6334        // Nothing has been served yet: the field is absent rather than
6335        // claiming a request happened at time zero.
6336        assert_eq!(health.last_request_age_seconds, None);
6337
6338        // Every control the UI might grey out has a code it can switch
6339        // on and a sentence it can show.
6340        for id in [
6341            ferrox_api::health::capability::CPU,
6342            ferrox_api::health::capability::METAL,
6343            ferrox_api::health::capability::CUDA,
6344            ferrox_api::health::capability::REAL_WEIGHTS,
6345            ferrox_api::health::capability::CONTINUOUS_BATCHING,
6346        ] {
6347            let cap = health
6348                .capability(id)
6349                .unwrap_or_else(|| panic!("{id} missing"));
6350            assert!(!cap.reason.is_empty(), "{cap:?}");
6351            assert!(!cap.detail.is_empty(), "{cap:?}");
6352        }
6353        // The test app serves synthetic random weights, and health must
6354        // say so: a UI that presents noise as a model invites a bug
6355        // report about "quality".
6356        let weights = health
6357            .capability(ferrox_api::health::capability::REAL_WEIGHTS)
6358            .unwrap();
6359        assert!(!weights.available);
6360        assert_eq!(weights.reason, ferrox_api::health::reason::MODEL_NOT_LOADED);
6361        assert!(health.model.as_ref().unwrap().synthetic_weights);
6362    }
6363
6364    #[tokio::test]
6365    async fn health_vouches_for_liveness_after_a_request_has_been_served() {
6366        let app = test_app();
6367        let _ = post_json(
6368            &app,
6369            serde_json::json!({
6370                "model": "m",
6371                "messages": [{"role": "user", "content": "\u{1}"}],
6372                "max_tokens": 1,
6373                "temperature": 0,
6374            }),
6375        )
6376        .await;
6377        let (_status, body) = get_json(&app, ferrox_api::routes::HEALTH).await;
6378        let health: ferrox_api::HealthResponse = serde_json::from_value(body).unwrap();
6379        let age = health
6380            .last_request_age_seconds
6381            .expect("a served request is evidence of liveness");
6382        assert!((0.0..5.0).contains(&age), "implausible age {age}");
6383    }
6384
6385    /// Every `data:` payload of an SSE response body, `[DONE]` excluded.
6386    async fn post_sse_chunks(app: &Router, body: serde_json::Value) -> Vec<serde_json::Value> {
6387        use http_body_util::BodyExt;
6388        use tower::ServiceExt;
6389
6390        let response = app
6391            .clone()
6392            .oneshot(
6393                axum::http::Request::builder()
6394                    .method("POST")
6395                    .uri("/v1/chat/completions")
6396                    .header("content-type", "application/json")
6397                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
6398                    .unwrap(),
6399            )
6400            .await
6401            .unwrap();
6402        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6403        String::from_utf8(bytes.to_vec())
6404            .unwrap()
6405            .lines()
6406            .filter_map(|line| line.strip_prefix("data: "))
6407            .filter(|payload| *payload != "[DONE]")
6408            .map(|payload| serde_json::from_str(payload).unwrap())
6409            .collect()
6410    }
6411
6412    #[tokio::test]
6413    async fn a_stream_states_its_request_id_once_in_the_first_chunk() {
6414        let app = test_app();
6415        let chunks = post_sse_chunks(
6416            &app,
6417            serde_json::json!({
6418                "model": "m",
6419                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6420                "max_tokens": 4,
6421                "temperature": 0,
6422                "stream": true,
6423            }),
6424        )
6425        .await;
6426
6427        assert!(!chunks.is_empty());
6428        let request_id = chunks[0]["request_id"]
6429            .as_str()
6430            .expect("the first chunk names the request")
6431            .to_string();
6432        assert!(request_id.starts_with("chatcmpl-"), "{request_id}");
6433        // Once, and before any content: a client that reads the id from
6434        // chunk zero never has to correlate by heuristic.
6435        for (i, chunk) in chunks.iter().enumerate().skip(1) {
6436            assert!(
6437                chunk.get("request_id").is_none(),
6438                "chunk {i} repeats request_id"
6439            );
6440        }
6441        // Every chunk of one stream carries the same `id`, and it is
6442        // that request id -- not a shared constant.
6443        for chunk in &chunks {
6444            assert_eq!(chunk["id"], serde_json::json!(request_id));
6445        }
6446
6447        let other = post_sse_chunks(
6448            &app,
6449            serde_json::json!({
6450                "model": "m",
6451                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6452                "max_tokens": 4,
6453                "temperature": 0,
6454                "stream": true,
6455            }),
6456        )
6457        .await;
6458        assert_ne!(
6459            other[0]["request_id"].as_str().unwrap(),
6460            request_id,
6461            "two concurrent chats must not share an id"
6462        );
6463    }
6464
6465    #[tokio::test]
6466    async fn a_non_streamed_response_names_the_same_request_id_as_its_completion_id() {
6467        let app = test_app();
6468        let resp = post_json(
6469            &app,
6470            serde_json::json!({
6471                "model": "m",
6472                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6473                "max_tokens": 2,
6474                "temperature": 0,
6475            }),
6476        )
6477        .await;
6478        assert_eq!(resp["id"], resp["request_id"]);
6479        assert!(resp["request_id"]
6480            .as_str()
6481            .unwrap()
6482            .starts_with("chatcmpl-"));
6483    }
6484
6485    /// The whole point of server-reported timings: a client can tell
6486    /// prefill from decode without a stopwatch (see `ferrox_api::usage`).
6487    #[tokio::test]
6488    async fn usage_carries_separate_prefill_and_decode_timings() {
6489        let app = test_app();
6490        let resp = post_json(
6491            &app,
6492            serde_json::json!({
6493                "model": "m",
6494                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6495                "max_tokens": 4,
6496                "temperature": 0,
6497            }),
6498        )
6499        .await;
6500        let usage = &resp["usage"];
6501        assert!(usage["prompt_eval_duration_ms"].is_number(), "{usage}");
6502        assert!(usage["generation_duration_ms"].is_number(), "{usage}");
6503        assert!(usage["time_to_first_token_ms"].is_number(), "{usage}");
6504        assert!(usage["predicted_per_second"].is_number(), "{usage}");
6505        // No prefix cache in this app: the field must be absent, not 0.
6506        assert!(usage.get("cached_tokens").is_none(), "{usage}");
6507    }
6508
6509    /// A real, deterministic small model with random weights will not
6510    /// spontaneously produce a `<tool_call>{...}</tool_call>` marker
6511    /// (whether a real deployed model does is a property of that
6512    /// model, not of ferrox's plumbing) -- so the real, testable
6513    /// end-to-end property here is that a `tools`-bearing request
6514    /// whose output does NOT contain the marker falls through cleanly
6515    /// to an ordinary text response instead of erroring or panicking.
6516    #[tokio::test]
6517    async fn a_tools_request_with_no_marker_in_the_output_falls_back_to_plain_content() {
6518        let app = test_app();
6519        let body = serde_json::json!({
6520            "model": "m",
6521            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6522            "max_tokens": 4,
6523            "temperature": 0,
6524            "tools": [weather_tool()],
6525        });
6526        let resp = post_json(&app, body).await;
6527        let message = &resp["choices"][0]["message"];
6528        assert!(
6529            message["content"].is_string(),
6530            "must fall back to plain content when no real tool-call marker is present: {resp:?}"
6531        );
6532        assert!(message.get("tool_calls").is_none());
6533        // Truncated at max_tokens, so the honest finish reason is
6534        // "length" -- the point here is only that it is NOT
6535        // "tool_calls".
6536        assert_eq!(resp["choices"][0]["finish_reason"], "length");
6537    }
6538
6539    /// A whole-response cache hit must be indistinguishable from
6540    /// recomputing: same content, same (honest) finish_reason, same
6541    /// usage counts -- only the `ferrox_cache` marker may differ.
6542    #[tokio::test]
6543    async fn a_cache_hit_reports_the_original_finish_reason_and_usage() {
6544        let app = test_app();
6545        let body = serde_json::json!({
6546            "model": "m",
6547            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
6548            "max_tokens": 3,
6549            "temperature": 0,
6550        });
6551        let first = post_json(&app, body.clone()).await;
6552        assert_eq!(first["ferrox_cache"], "miss");
6553        let second = post_json(&app, body).await;
6554        assert_eq!(second["ferrox_cache"], "hit");
6555        assert_eq!(
6556            first["choices"][0]["message"]["content"],
6557            second["choices"][0]["message"]["content"]
6558        );
6559        assert_eq!(
6560            first["choices"][0]["finish_reason"],
6561            second["choices"][0]["finish_reason"]
6562        );
6563        assert_eq!(first["usage"], second["usage"]);
6564        assert_eq!(second["usage"]["completion_tokens"], 3);
6565    }
6566
6567    /// The real proof for session reuse:
6568    /// a two-request session where the second request sends only its
6569    /// new message must produce exactly the same output as manually
6570    /// resending the full history (built from the *real* first reply,
6571    /// not an assumed one) with no `session_id` at all.
6572    #[tokio::test]
6573    async fn session_reuse_produces_the_same_output_as_manually_resending_full_history() {
6574        let session_app = test_app();
6575        let manual_app = test_app();
6576
6577        // Turn 1, via session.
6578        let turn1 = post_json(
6579            &session_app,
6580            serde_json::json!({
6581                "model": "m",
6582                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6583                "session_id": "s1",
6584                "max_tokens": 5,
6585                "temperature": 0,
6586            }),
6587        )
6588        .await;
6589        let reply1 = turn1["choices"][0]["message"]["content"]
6590            .as_str()
6591            .unwrap()
6592            .to_string();
6593
6594        // Turn 1, manually, for comparison -- must match exactly
6595        // (trivially, since it's the literal same single-turn
6596        // request), confirming the session path's first turn isn't
6597        // doing anything different from a plain request.
6598        let manual_turn1 = post_json(
6599            &manual_app,
6600            serde_json::json!({
6601                "model": "m",
6602                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6603                "max_tokens": 5,
6604                "temperature": 0,
6605            }),
6606        )
6607        .await;
6608        assert_eq!(
6609            manual_turn1["choices"][0]["message"]["content"]
6610                .as_str()
6611                .unwrap(),
6612            reply1
6613        );
6614
6615        // Turn 2, via session: sends ONLY the new message.
6616        let turn2 = post_json(
6617            &session_app,
6618            serde_json::json!({
6619                "model": "m",
6620                "messages": [{"role": "user", "content": "\u{4}\u{5}"}],
6621                "session_id": "s1",
6622                "max_tokens": 5,
6623                "temperature": 0,
6624            }),
6625        )
6626        .await;
6627        let reply2 = turn2["choices"][0]["message"]["content"]
6628            .as_str()
6629            .unwrap()
6630            .to_string();
6631
6632        // Turn 2, manually: the full three-message history
6633        // reconstructed using the REAL reply1 text, with no
6634        // session_id -- must produce byte-identical output.
6635        let manual_turn2 = post_json(
6636            &manual_app,
6637            serde_json::json!({
6638                "model": "m",
6639                "messages": [
6640                    {"role": "user", "content": "\u{1}\u{2}\u{3}"},
6641                    {"role": "assistant", "content": reply1},
6642                    {"role": "user", "content": "\u{4}\u{5}"},
6643                ],
6644                "max_tokens": 5,
6645                "temperature": 0,
6646            }),
6647        )
6648        .await;
6649        assert_eq!(
6650            manual_turn2["choices"][0]["message"]["content"]
6651                .as_str()
6652                .unwrap(),
6653            reply2,
6654            "resuming a session must produce identical output to manually resending the full history"
6655        );
6656    }
6657
6658    /// `lock_cache` must return a usable guard even after the mutex was
6659    /// poisoned by a panic elsewhere.
6660    #[test]
6661    fn lock_cache_recovers_from_a_poisoned_mutex() {
6662        let cache = Arc::new(Mutex::new(ResponseCache::new(10, Duration::from_secs(60))));
6663
6664        let poison_cache = Arc::clone(&cache);
6665        let _ = std::thread::spawn(move || {
6666            let _guard = poison_cache.lock().unwrap();
6667            panic!("simulated panic while holding the lock");
6668        })
6669        .join();
6670
6671        // A plain `.lock().unwrap()` would panic here; lock_cache must not.
6672        let recovered = lock_cache(&cache);
6673        assert_eq!(recovered.stats().entries, 0);
6674    }
6675
6676    #[test]
6677    fn is_cacheable_true_for_greedy_or_seeded_requests() {
6678        let mut req_body = serde_json::json!({
6679            "model": "m",
6680            "messages": [{"role": "user", "content": "hi"}],
6681        });
6682        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
6683        assert!(
6684            req.is_cacheable(),
6685            "default (temperature 0) must be cacheable"
6686        );
6687
6688        req_body["temperature"] = serde_json::json!(0.8);
6689        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
6690        assert!(
6691            !req.is_cacheable(),
6692            "unseeded sampling must never be cacheable"
6693        );
6694
6695        req_body["seed"] = serde_json::json!(42);
6696        let req: ChatCompletionRequest = serde_json::from_value(req_body).unwrap();
6697        assert!(
6698            req.is_cacheable(),
6699            "sampling with an explicit seed is deterministic and must be cacheable"
6700        );
6701    }
6702
6703    /// A template that grades only the OpenAI triple. `raise_exception`
6704    /// is how a real one rejects a value it does not know, which is what
6705    /// makes the load-time probe able to learn the vocabulary at all.
6706    const GRADED: &str = "{% if reasoning_effort %}\
6707         {% if reasoning_effort not in ['low','medium','high'] %}\
6708           {{ raise_exception('unsupported effort') }}\
6709         {% endif %}E:{{ reasoning_effort }}|{% endif %}\
6710         {% if enable_thinking %}THINK|{% endif %}{{ messages[0].content }}";
6711
6712    fn graded_template() -> chat_template::PromptTemplate {
6713        chat_template::PromptTemplate::from_gguf_metadata(
6714            Some(GRADED),
6715            Some("qwen3"),
6716            false,
6717            None,
6718            None,
6719        )
6720    }
6721
6722    fn chat_request(value: serde_json::Value) -> ChatCompletionRequest {
6723        serde_json::from_value(value).expect("request")
6724    }
6725
6726    /// A chat client that omits `max_tokens` wants an answer, not
6727    /// OpenAI's legacy 16-token completion fragment.
6728    #[test]
6729    fn an_omitted_output_budget_is_a_whole_answer_not_sixteen_tokens() {
6730        let req = chat_request(serde_json::json!({
6731            "model": "m",
6732            "messages": [{"role": "user", "content": "hi"}],
6733        }));
6734        assert_eq!(req.max_tokens, DEFAULT_CHAT_MAX_TOKENS);
6735    }
6736
6737    /// Serde already tells absent from zero -- an absent field became
6738    /// the default -- so a 0 here is one the caller wrote, and a
6739    /// zero-token budget is a request that can never become decodable.
6740    #[test]
6741    fn an_explicit_zero_output_budget_is_a_client_error() {
6742        let req = chat_request(serde_json::json!({
6743            "model": "m",
6744            "messages": [{"role": "user", "content": "hi"}],
6745            "max_tokens": 0,
6746        }));
6747        let (status, body) = req.validate_supported_fields().expect_err("rejected");
6748        assert_eq!(status, StatusCode::BAD_REQUEST);
6749        assert_eq!(body["error"]["param"], serde_json::json!("max_tokens"));
6750    }
6751
6752    /// The direction that had no wire path at all before: every request
6753    /// rendered in thinking mode because only the ON branch existed.
6754    #[test]
6755    fn a_request_can_turn_thinking_off() {
6756        let template = graded_template();
6757        for body in [
6758            serde_json::json!({
6759                "model": "m",
6760                "messages": [{"role": "user", "content": "hi"}],
6761                "reasoning_effort": "none",
6762            }),
6763            serde_json::json!({
6764                "model": "m",
6765                "messages": [{"role": "user", "content": "hi"}],
6766                "thinking": {"type": "disabled"},
6767            }),
6768        ] {
6769            let kwargs = chat_request(body).resolve_template_kwargs(&template);
6770            assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
6771            assert_eq!(kwargs["thinking_mode"], serde_json::json!("disabled"));
6772            // And `none` must not have been rounded onto a real gear on
6773            // the way: "do not think" is not "think a little".
6774            assert!(!kwargs.contains_key("reasoning_effort"));
6775        }
6776    }
6777
6778    /// The switch is what the caller reached for last; the gear is what
6779    /// they would have used had thinking been on.
6780    #[test]
6781    fn a_disabled_switch_beats_an_effort_in_the_same_request() {
6782        let template = graded_template();
6783        let kwargs = chat_request(serde_json::json!({
6784            "model": "m",
6785            "messages": [{"role": "user", "content": "hi"}],
6786            "reasoning_effort": "high",
6787            "thinking": {"type": "disabled"},
6788        }))
6789        .resolve_template_kwargs(&template);
6790        assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
6791        assert!(!kwargs.contains_key("reasoning_effort"));
6792    }
6793
6794    /// Read as "on", a misspelled switch silently serves the opposite
6795    /// of what was asked for.
6796    #[test]
6797    fn an_unrecognized_thinking_switch_is_refused_rather_than_read_as_on() {
6798        let req = chat_request(serde_json::json!({
6799            "model": "m",
6800            "messages": [{"role": "user", "content": "hi"}],
6801            "thinking": {"type": "disable"},
6802        }));
6803        let (status, _) = req.validate_supported_fields().expect_err("rejected");
6804        assert_eq!(status, StatusCode::BAD_REQUEST);
6805    }
6806
6807    /// A caller who steered the template themselves has said what they
6808    /// want; merging a protocol default in would let it contradict them.
6809    #[test]
6810    fn an_explicit_template_kwarg_stands_the_protocol_knobs_down() {
6811        let template = graded_template();
6812        let kwargs = chat_request(serde_json::json!({
6813            "model": "m",
6814            "messages": [{"role": "user", "content": "hi"}],
6815            "reasoning_effort": "none",
6816            "chat_template_kwargs": {"enable_thinking": true},
6817        }))
6818        .resolve_template_kwargs(&template);
6819        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
6820    }
6821
6822    /// The acceptance criterion for effort plumbing: an off-vocabulary
6823    /// value is quantized onto the nearest gear the checkpoint really
6824    /// grades, and the request renders instead of failing.
6825    #[test]
6826    fn an_off_vocabulary_reasoning_effort_is_quantized_rather_than_interpolated() {
6827        let template = graded_template();
6828        let req = chat_request(serde_json::json!({
6829            "model": "m",
6830            "messages": [{"role": "user", "content": "hi"}],
6831            "reasoning_effort": "minimal",
6832        }));
6833        let kwargs = req.resolve_template_kwargs(&template);
6834        assert_eq!(kwargs["reasoning_effort"], serde_json::json!("low"));
6835        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
6836        assert!(prompt.starts_with("E:low|"), "{prompt}");
6837    }
6838
6839    /// The other half of the same rule: a value no gear is close enough
6840    /// to is dropped, so the checkpoint's own default applies rather
6841    /// than an unknown string reaching the prompt.
6842    #[test]
6843    fn an_effort_with_no_near_gear_is_dropped_so_the_template_default_applies() {
6844        let template = graded_template();
6845        let req = chat_request(serde_json::json!({
6846            "model": "m",
6847            "messages": [{"role": "user", "content": "hi"}],
6848            "chat_template_kwargs": {"reasoning_effort": "none"},
6849        }));
6850        let kwargs = req.resolve_template_kwargs(&template);
6851        assert!(!kwargs.contains_key("reasoning_effort"));
6852        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
6853        assert_eq!(prompt, "hi");
6854    }
6855
6856    /// `chat_template_kwargs` is the specific spelling and wins over the
6857    /// top-level one, which is what a caller who wrote both meant.
6858    #[test]
6859    fn chat_template_kwargs_wins_over_the_top_level_reasoning_effort() {
6860        let template = graded_template();
6861        let req = chat_request(serde_json::json!({
6862            "model": "m",
6863            "messages": [{"role": "user", "content": "hi"}],
6864            "reasoning_effort": "low",
6865            "chat_template_kwargs": {"reasoning_effort": "high"},
6866        }));
6867        assert_eq!(
6868            req.resolve_template_kwargs(&template)["reasoning_effort"],
6869            serde_json::json!("high")
6870        );
6871    }
6872
6873    /// Offering tools turns thinking on even when the caller asked for
6874    /// nothing: some encoders emit well-formed calls only in thinking
6875    /// mode.
6876    #[test]
6877    fn offering_tools_turns_thinking_on_by_itself() {
6878        let template = graded_template();
6879        let quiet = chat_request(serde_json::json!({
6880            "model": "m",
6881            "messages": [{"role": "user", "content": "hi"}],
6882        }));
6883        assert!(!quiet
6884            .resolve_template_kwargs(&template)
6885            .contains_key("enable_thinking"));
6886
6887        let with_tools = chat_request(serde_json::json!({
6888            "model": "m",
6889            "messages": [{"role": "user", "content": "hi"}],
6890            "tools": [{"type": "function", "function": {"name": "get_weather"}}],
6891        }));
6892        let kwargs = with_tools.resolve_template_kwargs(&template);
6893        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
6894        let prompt =
6895            prompt_from_messages(&with_tools.messages, &template, &[], kwargs).expect("renders");
6896        assert!(prompt.starts_with("THINK|"), "{prompt}");
6897    }
6898
6899    /// The reason `force_reasoning` could only ever be `false` before:
6900    /// no template could open a block in the prompt, because no kwargs
6901    /// reached one. Now that they do, the parser has to start inside it
6902    /// -- and the evidence is the rendered prompt, not the model name.
6903    #[test]
6904    fn a_prompt_that_opens_the_reasoning_block_makes_the_first_token_reasoning() {
6905        let opener = chat_template::PromptTemplate::from_gguf_metadata(
6906            Some("{{ messages[0].content }}{% if enable_thinking %}<think>{% endif %}"),
6907            Some("qwen3"),
6908            false,
6909            None,
6910            None,
6911        );
6912        let req = chat_request(serde_json::json!({
6913            "model": "m",
6914            "messages": [{"role": "user", "content": "hi"}],
6915            "chat_template_kwargs": {"enable_thinking": true},
6916        }));
6917        let kwargs = req.resolve_template_kwargs(&opener);
6918        let prompt = prompt_from_messages(&req.messages, &opener, &[], kwargs).expect("renders");
6919        assert!(prompt.ends_with("<think>"), "{prompt}");
6920
6921        // No opening marker will ever arrive, so unparsed this whole
6922        // deliberation would have been served as the answer.
6923        let posture = output::OutputPosture::resolve("Qwen3-8B", &prompt);
6924        let (message, _) = build_response_message(
6925            "weighing it up</think>Paris.".to_string(),
6926            &[],
6927            posture,
6928            "stop",
6929        );
6930        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
6931        assert_eq!(message.content.as_deref(), Some("Paris."));
6932
6933        // Same text, a prompt that did not open the block: the model
6934        // wrote a stray closer and it stays content.
6935        let closed = output::OutputPosture::resolve("Qwen3-8B", "<|im_start|>assistant\n");
6936        let (message, _) = build_response_message(
6937            "weighing it up</think>Paris.".to_string(),
6938            &[],
6939            closed,
6940            "stop",
6941        );
6942        assert_eq!(message.reasoning_content, None);
6943    }
6944
6945    #[test]
6946    fn stop_param_accepts_both_single_string_and_array() {
6947        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
6948            "model": "m",
6949            "messages": [{"role": "user", "content": "hi"}],
6950            "stop": "END",
6951        }))
6952        .unwrap();
6953        assert_eq!(req.stop_sequences(), vec!["END".to_string()]);
6954
6955        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
6956            "model": "m",
6957            "messages": [{"role": "user", "content": "hi"}],
6958            "stop": ["A", "B"],
6959        }))
6960        .unwrap();
6961        assert_eq!(req.stop_sequences(), vec!["A".to_string(), "B".to_string()]);
6962    }
6963
6964    #[test]
6965    fn run_generation_rejects_out_of_vocab_tokens_instead_of_panicking() {
6966        let model = test_model();
6967        let result = run_generation(
6968            &model,
6969            "hello",
6970            &greedy_params(4),
6971            None,
6972            None,
6973            None,
6974            None,
6975            None,
6976        );
6977        assert!(matches!(
6978            result,
6979            Err(generate::DecodeError::TokenOutOfVocab { .. })
6980        ));
6981    }
6982
6983    /// A pool that *could* serve this request but is momentarily fully
6984    /// held is the server being behind: 503, and retrying is honest
6985    /// advice because the blocks really do come back.
6986    #[test]
6987    fn run_generation_honors_an_exhausted_kv_pool_and_maps_it_to_a_503() {
6988        let model = test_model(); // 2 layers -> 2 blocks
6989        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
6990        let pool = Arc::new(Mutex::new(ferrox_core::cache::KvBlockPool::new(64, 2)));
6991
6992        let holder_pool = Arc::clone(&pool);
6993        let holder = std::thread::spawn(move || {
6994            let mut held = ferrox_core::cache::KvCache::with_pool(1, 1, holder_pool, 0).unwrap();
6995            held.push(&[0.0], &[0.0]).unwrap(); // crosses into the second block
6996            std::thread::sleep(Duration::from_millis(200));
6997            drop(held);
6998        });
6999        std::thread::sleep(Duration::from_millis(15));
7000
7001        let config = generate::KvPoolConfig {
7002            pool,
7003            queue_wait: Duration::ZERO,
7004        };
7005        let result = run_generation(
7006            &model,
7007            &prompt,
7008            &greedy_params(4),
7009            Some(&config),
7010            None,
7011            None,
7012            None,
7013            None,
7014        );
7015        assert!(matches!(
7016            result,
7017            Err(generate::DecodeError::KvPoolExhausted)
7018        ));
7019
7020        let (status, _body) = decode_error_response(result.unwrap_err());
7021        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
7022        holder.join().unwrap();
7023    }
7024
7025    /// The same endpoint, the same pool size, a request too big for the
7026    /// *whole* pool: a 400 rather than a 503, because an idle server
7027    /// refuses it identically and `Retry-After` would be a promise
7028    /// nothing can keep.
7029    ///
7030    /// Confirmed to FAIL when `generate`'s `pool_immovable_refusal`
7031    /// check is removed: the status comes back 503.
7032    #[test]
7033    fn a_request_too_big_for_the_whole_pool_is_a_400_not_a_retryable_503() {
7034        let model = test_model(); // 2 layers
7035        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
7036        // One block, two layers: no schedule ever serves this.
7037        let pool = Arc::new(Mutex::new(ferrox_core::cache::KvBlockPool::new(64, 1)));
7038        let config = generate::KvPoolConfig {
7039            pool,
7040            queue_wait: Duration::ZERO,
7041        };
7042
7043        let result = run_generation(
7044            &model,
7045            &prompt,
7046            &greedy_params(4),
7047            Some(&config),
7048            None,
7049            None,
7050            None,
7051            None,
7052        );
7053        let err = result.expect_err("one block cannot hold two layers' caches");
7054        assert!(
7055            matches!(
7056                &err,
7057                generate::DecodeError::KvBudgetExceeded { binding, .. }
7058                    if *binding == ferrox_models::Ceiling::DeviceMemory.code()
7059            ),
7060            "expected an immovable device-memory refusal, got {err:?}"
7061        );
7062        let (status, _body) = decode_error_response(err);
7063        assert_eq!(status, StatusCode::BAD_REQUEST);
7064    }
7065
7066    /// A full admission queue is the server being behind, not the
7067    /// client being wrong: 503, with the wait hint in the body (and the
7068    /// `Retry-After` header stamped by `limits::retry_after`) and the
7069    /// depth and cap named so an operator can tell a retry storm from a
7070    /// single oversized request.
7071    #[test]
7072    fn decode_error_response_maps_a_full_queue_to_a_retryable_503() {
7073        let (status, Json(body)) = decode_error_response(generate::DecodeError::QueueFull {
7074            queued: 512,
7075            cap: 512,
7076        });
7077        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
7078        assert_eq!(body["error"]["retry_after_seconds"], 1);
7079        let message = body["error"]["message"].as_str().expect("message");
7080        assert!(message.contains("512"), "{message}");
7081    }
7082
7083    #[test]
7084    fn decode_error_response_omits_a_retry_hint_for_an_unretryable_error() {
7085        let (_status, Json(body)) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
7086            token: 99,
7087            vocab_size: 32,
7088        });
7089        assert!(
7090            body["error"]["retry_after_seconds"].is_null(),
7091            "retrying a prompt this model cannot tokenize never helps"
7092        );
7093    }
7094
7095    #[test]
7096    fn decode_error_response_maps_token_out_of_vocab_to_bad_request() {
7097        let (status, _body) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
7098            token: 99,
7099            vocab_size: 32,
7100        });
7101        assert_eq!(status, StatusCode::BAD_REQUEST);
7102    }
7103
7104    #[test]
7105    fn run_generation_succeeds_and_releases_blocks_when_the_pool_has_room() {
7106        let model = test_model(); // 2 layers
7107        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
7108        let pool = Arc::new(Mutex::new(ferrox_core::cache::KvBlockPool::new(64, 2)));
7109        let config = generate::KvPoolConfig {
7110            pool: pool.clone(),
7111            queue_wait: Duration::ZERO,
7112        };
7113
7114        let (_, finish, _usage) = run_generation(
7115            &model,
7116            &prompt,
7117            &greedy_params(4),
7118            Some(&config),
7119            None,
7120            None,
7121            None,
7122            None,
7123        )
7124        .unwrap();
7125        assert_eq!(finish, FinishReason::Length);
7126        assert_eq!(
7127            pool.lock().unwrap().free_blocks(),
7128            2,
7129            "a completed request must return its blocks to the pool"
7130        );
7131    }
7132
7133    /// The core concurrency claim: two requests using the *same* `Arc<Model>`
7134    /// must be able to run their (independent, per-call) KV caches
7135    /// concurrently without interfering with each other or needing any
7136    /// shared lock around the model itself.
7137    #[tokio::test]
7138    async fn concurrent_requests_against_the_same_model_do_not_interfere() {
7139        let model = Arc::new(test_model());
7140        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
7141
7142        let mut handles = Vec::new();
7143        for _ in 0..8 {
7144            let model = Arc::clone(&model);
7145            let prompt = prompt.clone();
7146            handles.push(tokio::task::spawn_blocking(move || {
7147                run_generation(
7148                    &model,
7149                    &prompt,
7150                    &greedy_params(6),
7151                    None,
7152                    None,
7153                    None,
7154                    None,
7155                    None,
7156                )
7157                .unwrap()
7158            }));
7159        }
7160
7161        let mut results = Vec::new();
7162        for h in handles {
7163            results.push(h.await.unwrap());
7164        }
7165        // Same prompt, same seed, same (greedy) sampling, same
7166        // immutable model -> every concurrent run must produce
7167        // identical output, proving no request's KV cache leaked into
7168        // another's.
7169        for r in &results[1..] {
7170            assert_eq!(r.0, results[0].0, "decoded chunks must match");
7171            assert_eq!(r.1, results[0].1, "finish reason must match");
7172            assert_eq!(
7173                r.2.prompt_tokens, results[0].2.prompt_tokens,
7174                "prompt token count must match"
7175            );
7176            assert_eq!(
7177                r.2.completion_tokens, results[0].2.completion_tokens,
7178                "completion token count must match"
7179            );
7180        }
7181    }
7182
7183    /// A real, minimal safetensors shard: JSON header (name -> real
7184    /// dtype/shape/`data_offsets`) followed by the concatenated raw
7185    /// F32 bytes -- exactly the format `ShardedSafetensors::open_index`
7186    /// parses, hand-built here rather than depending on
7187    /// `ferrox-models::kimi_loader`'s own private test helpers (not
7188    /// visible across the crate boundary).
7189    fn write_safetensors_shard(tensors: &[(String, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
7190        let mut header_entries = Vec::new();
7191        let mut data = Vec::new();
7192        for (name, shape, values) in tensors {
7193            let start = data.len();
7194            for v in values {
7195                data.extend_from_slice(&v.to_le_bytes());
7196            }
7197            let end = data.len();
7198            let shape_str = shape
7199                .iter()
7200                .map(|d| d.to_string())
7201                .collect::<Vec<_>>()
7202                .join(",");
7203            header_entries.push(format!(
7204                "\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{shape_str}],\"data_offsets\":[{start},{end}]}}"
7205            ));
7206        }
7207        let header = format!("{{{}}}", header_entries.join(","));
7208        let header_bytes = header.as_bytes();
7209        let mut out = Vec::with_capacity(8 + header_bytes.len() + data.len());
7210        out.extend_from_slice(&(header_bytes.len() as u64).to_le_bytes());
7211        out.extend_from_slice(header_bytes);
7212        out.extend_from_slice(&data);
7213        out
7214    }
7215
7216    /// Builds a small but completely real Kimi K3 checkpoint directory
7217    /// on disk (real `model.safetensors.index.json` + shard bytes +
7218    /// `tiktoken.model`, the exact file layout `ferrox-cli`'s
7219    /// `run-kimi` command expects) and loads it through
7220    /// `model::load_kimi_checkpoint_with_config` (the same real loading
7221    /// logic `model::load()` uses for `FERROX_MODEL_PATH` pointing at a
7222    /// directory, parametrized here only so the checkpoint can be small
7223    /// -- see that function's doc comment). Shared by every test that
7224    /// needs a real, loaded `KimiLoaded` rather than duplicating this
7225    /// setup per test.
7226    fn build_synthetic_kimi_loaded() -> model::KimiLoaded {
7227        use ferrox_models::config::{AttentionKind, KdaConfig, KimiHybridAttention, MlaConfig};
7228        use ferrox_models::kimi_loader::KimiRealHparams;
7229        use ferrox_moe::{GatingFunction, MoeLayerConfig};
7230
7231        let hidden_dim = 8;
7232        let kda_num_heads = 2;
7233        let kda_head_dim = 3;
7234        let kda_proj = kda_num_heads * kda_head_dim;
7235        let conv_kernel = 4;
7236        let dense_intermediate = 5;
7237        // One token per byte value -- enough to round-trip a simple
7238        // ASCII prompt through the real tiktoken-format vocab below,
7239        // matching `kimi_generate`'s own test convention.
7240        let vocab_size = 256;
7241        let mla_num_heads = 1;
7242        let mla_q_lora_rank = 2;
7243        let mla_kv_lora_rank = 2;
7244        let mla_qk_nope_head_dim = 2;
7245        let mla_qk_rope_head_dim = 2;
7246        let mla_v_head_dim = 2;
7247
7248        let model_cfg = ferrox_models::ModelConfig {
7249            name: "synthetic-kimi-server-test",
7250            n_layers: 1,
7251            hidden_dim,
7252            n_heads: 1,
7253            n_kv_heads: 1,
7254            head_dim: 4,
7255            vocab_size,
7256            rope_theta: 10000.0,
7257            rms_norm_eps: 1e-5,
7258            sliding_window: None,
7259            moe: MoeLayerConfig {
7260                expert_weights_scale: 1.0,
7261                n_experts: 1,
7262                n_experts_active: 1,
7263                n_shared_experts: 0,
7264                hidden_dim,
7265                expert_ffn_dim: 4,
7266                gating: GatingFunction::Sigmoid,
7267                norm_topk_prob: true,
7268                expert_group_count: None,
7269                expert_group_used_count: None,
7270            },
7271            // Layer 0 is the sole dense leading layer, using KDA
7272            // attention (real Kimi K3's own layer-0 shape) -- the
7273            // 1-indexed `kda_layers`/`full_attn_layers` convention is
7274            // `ModelConfig::layer_attention_kind`'s, not this test's.
7275            n_dense_leading_layers: 1,
7276            attention: AttentionKind::KimiHybrid(KimiHybridAttention {
7277                kda_layers: vec![1],
7278                full_attn_layers: vec![],
7279                mla: MlaConfig {
7280                    num_heads: mla_num_heads,
7281                    q_lora_rank: mla_q_lora_rank,
7282                    kv_lora_rank: mla_kv_lora_rank,
7283                    qk_nope_head_dim: mla_qk_nope_head_dim,
7284                    qk_rope_head_dim: mla_qk_rope_head_dim,
7285                    v_head_dim: mla_v_head_dim,
7286                    use_output_gate: true,
7287                    rope: None,
7288                },
7289                kda: KdaConfig {
7290                    num_heads: kda_num_heads,
7291                    head_dim: kda_head_dim,
7292                    short_conv_kernel_size: conv_kernel,
7293                    gate_lower_bound: -5.0,
7294                    use_full_rank_gate: true,
7295                },
7296            }),
7297            rope_freqs: None,
7298            rope_attn_factor: 1.0,
7299            rope_dim: None,
7300            rope_freqs_long: None,
7301            rope_freqs_short: None,
7302            rope_orig_ctx: None,
7303            rope_layout: ferrox_models::config::RopeLayout::Neox,
7304            qk_norm_style: ferrox_models::capability::QkNormStyle::WholeVector,
7305            swa_pattern: None,
7306            attn_logit_softcap: None,
7307            final_logit_softcap: None,
7308            embedding_scale: None,
7309            attention_scale: None,
7310            rope_theta_swa: None,
7311            ffn_activation: ferrox_models::config::FfnActivation::Swiglu,
7312            best_effort_fields: &["synthetic test config, not a real preset"],
7313        };
7314        let hp = KimiRealHparams {
7315            hidden_dim,
7316            kda_num_heads,
7317            kda_head_dim,
7318            mla_num_heads,
7319            mla_q_lora_rank,
7320            mla_kv_lora_rank,
7321            mla_qk_nope_head_dim,
7322            mla_qk_rope_head_dim,
7323            mla_v_head_dim,
7324            dense_intermediate_dim: dense_intermediate,
7325            moe_hidden_dim: hidden_dim,
7326            moe_intermediate_dim: 4,
7327            n_experts: 1,
7328            num_shared_experts: 0,
7329        };
7330
7331        // Every real tensor name `kimi_loader::load_kimi_layer` (dense
7332        // FFN + KDA attention + block residual) and
7333        // `load_kimi_checkpoint` (top-level) actually read.
7334        let prefix = "language_model.model.layers.0";
7335        let mut tensors: Vec<(String, Vec<usize>, Vec<f32>)> = Vec::new();
7336        let push = |tensors: &mut Vec<(String, Vec<usize>, Vec<f32>)>,
7337                    name: String,
7338                    shape: Vec<usize>,
7339                    n: usize| {
7340            tensors.push((name, shape, vec![0.01f32; n]));
7341        };
7342        push(
7343            &mut tensors,
7344            format!("{prefix}.input_layernorm.weight"),
7345            vec![hidden_dim],
7346            hidden_dim,
7347        );
7348        push(
7349            &mut tensors,
7350            format!("{prefix}.post_attention_layernorm.weight"),
7351            vec![hidden_dim],
7352            hidden_dim,
7353        );
7354        push(
7355            &mut tensors,
7356            format!("{prefix}.self_attention_res_norm.weight"),
7357            vec![hidden_dim],
7358            hidden_dim,
7359        );
7360        push(
7361            &mut tensors,
7362            format!("{prefix}.self_attention_res_proj.weight"),
7363            vec![1, hidden_dim],
7364            hidden_dim,
7365        );
7366        push(
7367            &mut tensors,
7368            format!("{prefix}.mlp_res_norm.weight"),
7369            vec![hidden_dim],
7370            hidden_dim,
7371        );
7372        push(
7373            &mut tensors,
7374            format!("{prefix}.mlp_res_proj.weight"),
7375            vec![1, hidden_dim],
7376            hidden_dim,
7377        );
7378        push(
7379            &mut tensors,
7380            format!("{prefix}.self_attn.q_proj.weight"),
7381            vec![kda_proj, hidden_dim],
7382            kda_proj * hidden_dim,
7383        );
7384        push(
7385            &mut tensors,
7386            format!("{prefix}.self_attn.k_proj.weight"),
7387            vec![kda_proj, hidden_dim],
7388            kda_proj * hidden_dim,
7389        );
7390        push(
7391            &mut tensors,
7392            format!("{prefix}.self_attn.v_proj.weight"),
7393            vec![kda_proj, hidden_dim],
7394            kda_proj * hidden_dim,
7395        );
7396        push(
7397            &mut tensors,
7398            format!("{prefix}.self_attn.q_conv1d.weight"),
7399            vec![kda_proj, 1, conv_kernel],
7400            kda_proj * conv_kernel,
7401        );
7402        push(
7403            &mut tensors,
7404            format!("{prefix}.self_attn.k_conv1d.weight"),
7405            vec![kda_proj, 1, conv_kernel],
7406            kda_proj * conv_kernel,
7407        );
7408        push(
7409            &mut tensors,
7410            format!("{prefix}.self_attn.v_conv1d.weight"),
7411            vec![kda_proj, 1, conv_kernel],
7412            kda_proj * conv_kernel,
7413        );
7414        push(
7415            &mut tensors,
7416            format!("{prefix}.self_attn.A_log"),
7417            vec![kda_num_heads],
7418            kda_num_heads,
7419        );
7420        push(
7421            &mut tensors,
7422            format!("{prefix}.self_attn.f_a_proj.weight"),
7423            vec![kda_head_dim, hidden_dim],
7424            kda_head_dim * hidden_dim,
7425        );
7426        push(
7427            &mut tensors,
7428            format!("{prefix}.self_attn.f_b_proj.weight"),
7429            vec![kda_proj, kda_head_dim],
7430            kda_proj * kda_head_dim,
7431        );
7432        push(
7433            &mut tensors,
7434            format!("{prefix}.self_attn.dt_bias"),
7435            vec![kda_proj],
7436            kda_proj,
7437        );
7438        push(
7439            &mut tensors,
7440            format!("{prefix}.self_attn.b_proj.weight"),
7441            vec![kda_num_heads, hidden_dim],
7442            kda_num_heads * hidden_dim,
7443        );
7444        push(
7445            &mut tensors,
7446            format!("{prefix}.self_attn.g_proj.weight"),
7447            vec![kda_proj, hidden_dim],
7448            kda_proj * hidden_dim,
7449        );
7450        push(
7451            &mut tensors,
7452            format!("{prefix}.self_attn.o_norm.weight"),
7453            vec![kda_head_dim],
7454            kda_head_dim,
7455        );
7456        push(
7457            &mut tensors,
7458            format!("{prefix}.self_attn.o_proj.weight"),
7459            vec![hidden_dim, kda_proj],
7460            hidden_dim * kda_proj,
7461        );
7462        push(
7463            &mut tensors,
7464            format!("{prefix}.mlp.gate_proj.weight"),
7465            vec![dense_intermediate, hidden_dim],
7466            dense_intermediate * hidden_dim,
7467        );
7468        push(
7469            &mut tensors,
7470            format!("{prefix}.mlp.up_proj.weight"),
7471            vec![dense_intermediate, hidden_dim],
7472            dense_intermediate * hidden_dim,
7473        );
7474        push(
7475            &mut tensors,
7476            format!("{prefix}.mlp.down_proj.weight"),
7477            vec![hidden_dim, dense_intermediate],
7478            hidden_dim * dense_intermediate,
7479        );
7480        push(
7481            &mut tensors,
7482            "language_model.model.embed_tokens.weight".to_string(),
7483            vec![vocab_size, hidden_dim],
7484            vocab_size * hidden_dim,
7485        );
7486        push(
7487            &mut tensors,
7488            "language_model.lm_head.weight".to_string(),
7489            vec![vocab_size, hidden_dim],
7490            vocab_size * hidden_dim,
7491        );
7492        push(
7493            &mut tensors,
7494            "language_model.model.norm.weight".to_string(),
7495            vec![hidden_dim],
7496            hidden_dim,
7497        );
7498        push(
7499            &mut tensors,
7500            "language_model.model.output_attn_res_norm.weight".to_string(),
7501            vec![hidden_dim],
7502            hidden_dim,
7503        );
7504        push(
7505            &mut tensors,
7506            "language_model.model.output_attn_res_proj.weight".to_string(),
7507            vec![1, hidden_dim],
7508            hidden_dim,
7509        );
7510
7511        // Unique per CALL, not per (pid, vocab_size). Both callers of
7512        // this helper use the same `vocab_size`, so keying on it gave
7513        // the two tests one directory -- and `fs::write` opens with
7514        // `O_TRUNC`, so one test rewriting the shard truncated it to
7515        // zero while the other's `ferrox-safetensors` MMAP of that
7516        // exact file was live. Touching a mapping past the end of its
7517        // file is SIGBUS, which kills the whole test binary rather than
7518        // failing one test, and only when the two happen to overlap --
7519        // so it showed up as an occasional unexplained CI crash.
7520        //
7521        // A counter and not a thread id: the harness reuses threads
7522        // across tests, so two sequential tests can share one.
7523        static FIXTURE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7524        let dir = std::env::temp_dir().join(format!(
7525            "ferrox_server_kimi_e2e_test_{}_{}",
7526            std::process::id(),
7527            FIXTURE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7528        ));
7529        std::fs::create_dir_all(&dir).unwrap();
7530        let shard_bytes = write_safetensors_shard(&tensors);
7531        std::fs::write(dir.join("shard0.safetensors"), &shard_bytes).unwrap();
7532        let map_entries: Vec<String> = tensors
7533            .iter()
7534            .map(|(name, ..)| format!("\"{name}\":\"shard0.safetensors\""))
7535            .collect();
7536        let index = format!("{{\"weight_map\":{{{}}}}}", map_entries.join(","));
7537        std::fs::write(dir.join("model.safetensors.index.json"), &index).unwrap();
7538
7539        // A real tiktoken-format vocab file: one base64-encoded byte
7540        // plus its rank per line -- enough to round-trip an ASCII
7541        // prompt without needing the real 163584-entry Kimi K3 vocab.
7542        use base64::Engine;
7543        let vocab_lines: Vec<String> = (0..vocab_size as u32)
7544            .map(|b| {
7545                let b64 = base64::engine::general_purpose::STANDARD.encode([b as u8]);
7546                format!("{b64} {b}")
7547            })
7548            .collect();
7549        std::fs::write(dir.join("tiktoken.model"), vocab_lines.join("\n")).unwrap();
7550
7551        let loaded = model::load_kimi_checkpoint_with_config(dir.to_str().unwrap(), model_cfg, hp)
7552            .expect("must load the synthetic Kimi checkpoint end to end");
7553        std::fs::remove_dir_all(&dir).ok();
7554        loaded
7555    }
7556
7557    /// The real end-to-end proof for Kimi-through-the-server: a real
7558    /// synthetic Kimi K3 checkpoint served through the exact same
7559    /// `run_generation` entry point the HTTP handlers call for the
7560    /// GGUF path. Proves the whole new plumbing end to end: directory-
7561    /// shaped checkpoint loading, `KimiEngine`/`KimiTokenizer` wired
7562    /// through the `Model` enum, and `generate::generate_engine`
7563    /// producing real, bounded generated text.
7564    #[test]
7565    fn kimi_model_serves_real_text_end_to_end_via_run_generation() {
7566        let loaded = build_synthetic_kimi_loaded();
7567        let state = build_app_state(
7568            model::LoadedModel::Kimi(loaded),
7569            None,
7570            None,
7571            None,
7572            false,
7573            None,
7574            Arc::new(health::Detection::ready(health::probe_backends())),
7575        );
7576        let active = state.active().expect("a freshly built state has a model");
7577        assert_eq!(active.model.tokenizer_kind(), "kimi-tiktoken-bpe");
7578        assert!(!active.model.is_synthetic());
7579
7580        let (_chunks, finish, _usage) = run_generation(
7581            &active.model,
7582            "hi",
7583            &greedy_params(5),
7584            None,
7585            None,
7586            None,
7587            None,
7588            None,
7589        )
7590        .expect("a real Kimi checkpoint must generate without error");
7591        assert!(matches!(finish, FinishReason::Length | FinishReason::Stop));
7592    }
7593
7594    /// Explicit proof of the "gate, don't paper over" design decision
7595    /// (see `ferrox_models::engine`'s module docs): even when an operator configures
7596    /// a KV block pool and/or prefix cache, a Kimi request must never
7597    /// consult either -- `generate_engine`'s signature has no
7598    /// parameter for them at all, so this isn't just an unexercised
7599    /// code path, it's structurally impossible for a Kimi request to
7600    /// touch them. Confirmed here by observing both are completely
7601    /// untouched (pool blocks unchanged, cache stats unchanged) after a
7602    /// real Kimi generation runs alongside both.
7603    #[test]
7604    fn kv_pool_and_prefix_cache_are_never_consulted_for_a_kimi_model() {
7605        let loaded = build_synthetic_kimi_loaded();
7606        let state = build_app_state(
7607            model::LoadedModel::Kimi(loaded),
7608            None,
7609            None,
7610            None,
7611            false,
7612            None,
7613            Arc::new(health::Detection::ready(health::probe_backends())),
7614        );
7615
7616        let pool = Arc::new(Mutex::new(ferrox_core::cache::KvBlockPool::new(64, 4)));
7617        let kv_pool_config = generate::KvPoolConfig {
7618            pool: pool.clone(),
7619            queue_wait: Duration::ZERO,
7620        };
7621        let pc = Mutex::new(PrefixCache::new(4));
7622
7623        run_generation(
7624            &state
7625                .active()
7626                .expect("a freshly built state has a model")
7627                .model,
7628            "hi",
7629            &greedy_params(5),
7630            Some(&kv_pool_config),
7631            None,
7632            Some(&pc),
7633            None,
7634            None,
7635        )
7636        .expect("a real Kimi checkpoint must generate without error");
7637
7638        assert_eq!(
7639            pool.lock().unwrap().free_blocks(),
7640            4,
7641            "the KV pool must be completely untouched by a Kimi request"
7642        );
7643        let stats = pc.lock().unwrap().stats();
7644        assert_eq!(
7645            stats.hits + stats.misses,
7646            0,
7647            "the prefix cache must never be consulted for a Kimi request"
7648        );
7649    }
7650}