Skip to main content

frink_server/
lib.rs

1//! frink-server: OpenAI-compatible HTTP surface (`/health`,
2//! `/v1/models`, `/v1/chat/completions`, `/v1/completions`,
3//! `/v1/tokenize`, `/v1/detokenize`, `/v1/embeddings`) over the
4//! frink-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 `FRINK_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. Under continuous batching the batch
33//! worker emits the same incremental chunks as the private decode loop.
34
35mod admin;
36mod anthropic;
37mod attribution;
38mod budget;
39mod cache_admin;
40mod cancel;
41mod chat_params;
42mod chat_template;
43mod cli;
44mod completion;
45mod continuation;
46mod conversations;
47mod decode_task;
48mod embeddings;
49mod generate;
50mod grammar_request;
51mod health;
52mod journal;
53mod json_mode;
54mod limits;
55mod loaded;
56mod logprobs;
57mod lora;
58mod mcp;
59mod model;
60mod openai_extra;
61mod output;
62mod policy;
63mod prefill_batch;
64mod reasoning_budget;
65mod reasoning_tokens;
66mod request_tail;
67mod rerank;
68mod response_cache;
69pub(crate) mod responses;
70mod resume;
71mod sample_step;
72mod sampling_knobs;
73mod sampling_loop;
74mod security;
75mod serving;
76mod session;
77mod slots;
78mod sse;
79mod stats;
80mod stop;
81mod stream_events;
82mod tasks;
83mod tool_grammar;
84mod unimplemented_fields;
85mod unsupported_sampling;
86mod utf8_stream;
87
88use std::cell::RefCell;
89use std::convert::Infallible;
90use std::net::SocketAddr;
91use std::path::PathBuf;
92use std::rc::Rc;
93use std::sync::{Arc, Mutex, MutexGuard};
94use std::time::Duration;
95
96use axum::{
97    extract::State,
98    http::StatusCode,
99    response::sse::{Event, Sse},
100    response::{IntoResponse, Response},
101    routing::{get, post},
102    Json, Router,
103};
104use serde::{Deserialize, Serialize};
105
106use cli::apply_cli_overrides;
107pub use cli::{ServerArgs, BUILT_WITH_CUDA, BUILT_WITH_METAL};
108
109use frink_core::cache::KvBlockPool;
110use frink_models::kimi_tokenizer::KimiTokenizer;
111use frink_models::sampling::SamplingParams;
112use frink_models::tokenizer::{SpecialTokens, StopTokens};
113use frink_models::{Decoder, Gemma4Engine, KimiEngine, MlaEngine, PrefixCache};
114#[cfg(test)]
115use generate::FinishReason;
116use generate::GenerationParams;
117pub(crate) use loaded::{ActiveModel, Loaded};
118use model::ServerTokenizer;
119use rerank::encoder_endpoints;
120use response_cache::ResponseCache;
121use sampling_knobs::SamplingKnobs;
122
123/// The loaded model: immutable once built, so it needs no lock at all --
124/// just cheap `Arc` sharing across concurrent request tasks. Two real
125/// checkpoint shapes exist (see `model::LoadedModel`'s doc comment for
126/// why `FRINK_MODEL_PATH` picks between them); everything that isn't
127/// engine-specific (chat template, tokenizer kind reporting, whether
128/// this is the synthetic demo) goes through the small inherent methods
129/// below rather than being matched on ad hoc at every call site.
130#[allow(clippy::large_enum_variant)] // KimiEngine/MlaEngine dwarf Arc<Decoder>; boxing would churn call sites
131pub(crate) enum Model {
132    Gguf(GgufModel),
133    Kimi(KimiModel),
134    Mla(MlaModel),
135    Gemma4(Gemma4Model),
136    Glm52(Glm52Model),
137}
138
139pub(crate) struct GgufModel {
140    decoder: Arc<Decoder>,
141    tokenizer: Arc<ServerTokenizer>,
142    stop_tokens: StopTokens,
143    bos_id: Option<usize>,
144    is_synthetic: bool,
145    chat_template: chat_template::PromptTemplate,
146}
147
148pub(crate) struct KimiModel {
149    engine: KimiEngine,
150    tokenizer: KimiTokenizer,
151    stop_tokens: StopTokens,
152    chat_template: chat_template::PromptTemplate,
153}
154
155pub(crate) struct MlaModel {
156    engine: MlaEngine,
157    tokenizer: ServerTokenizer,
158    stop_tokens: StopTokens,
159    bos_id: Option<usize>,
160    name: String,
161    chat_template: chat_template::PromptTemplate,
162}
163
164pub(crate) struct Gemma4Model {
165    engine: Gemma4Engine,
166    tokenizer: ServerTokenizer,
167    stop_tokens: StopTokens,
168    bos_id: Option<usize>,
169    name: String,
170    chat_template: chat_template::PromptTemplate,
171}
172
173pub(crate) struct Glm52Model {
174    engine: frink_models::Glm52Engine,
175    tokenizer: ServerTokenizer,
176    stop_tokens: StopTokens,
177    bos_id: Option<usize>,
178    name: String,
179    chat_template: chat_template::PromptTemplate,
180}
181
182impl Model {
183    pub(crate) fn chat_template(&self) -> chat_template::PromptTemplate {
184        match self {
185            Model::Gguf(m) => m.chat_template.clone(),
186            Model::Kimi(m) => m.chat_template.clone(),
187            Model::Mla(m) => m.chat_template.clone(),
188            Model::Gemma4(m) => m.chat_template.clone(),
189            Model::Glm52(m) => m.chat_template.clone(),
190        }
191    }
192
193    /// Kimi K3 / MLA / GLM-5.2 have no synthetic-weight demo path through this
194    /// server (unlike GGUF, which falls back to one when
195    /// `FRINK_MODEL_PATH` is unset) -- a loaded `Model::Kimi` /
196    /// `Model::Mla` / `Model::Glm52` is always a real checkpoint.
197    fn is_synthetic(&self) -> bool {
198        match self {
199            Model::Gguf(m) => m.is_synthetic,
200            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => false,
201        }
202    }
203
204    fn tokenizer_kind(&self) -> &'static str {
205        match self {
206            Model::Gguf(m) => m.tokenizer.kind(),
207            Model::Kimi(_) => "kimi-tiktoken-bpe",
208            Model::Mla(m) => m.tokenizer.kind(),
209            Model::Gemma4(m) => m.tokenizer.kind(),
210            Model::Glm52(m) => m.tokenizer.kind(),
211        }
212    }
213
214    /// Live counters of the bounded expert cache, when the model
215    /// streams routed experts (`FRINK_EXPERT_CACHE_BYTES`); `None`
216    /// for fully resident models.
217    fn expert_store_stats(&self) -> Option<frink_core::expert_store::ExpertStoreStats> {
218        match self {
219            Model::Gguf(m) => m.decoder.expert_store_stats(),
220            Model::Kimi(m) => m.engine.weights.expert_store_stats(),
221            Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
222        }
223    }
224
225    pub(crate) fn name(&self) -> &str {
226        match self {
227            Model::Gguf(m) => m.decoder.config.name,
228            Model::Kimi(_) => "kimi-k3",
229            Model::Mla(m) => m.name.as_str(),
230            Model::Gemma4(m) => m.name.as_str(),
231            Model::Glm52(m) => m.name.as_str(),
232        }
233    }
234
235    /// `specials` is llama.cpp's `parse_special`, and each caller is
236    /// matched to the llama.cpp server site it mirrors
237    /// (`tools/server/server-context.cpp` unless said otherwise):
238    ///
239    /// * a prompt, rendered from a chat template or given raw --
240    ///   `/v1/chat/completions`, `/v1/completions`, `/v1/messages`,
241    ///   `count_tokens`, slot save: `Parse`, as
242    ///   `tokenize_input_prompts(..., true, true)` does for both
243    ///   completion routes. llama.cpp's server does NOT tokenize a
244    ///   message's content separately from the template around it, so
245    ///   neither does this one; a document that mentions `<|im_end|>`
246    ///   inside a chat message is parsed on both engines. Doing better
247    ///   would need the template renderer to hand back which spans are
248    ///   content, and is deliberately not done here so the two engines
249    ///   agree about the prompt.
250    /// * pooled decoder embeddings: `Parse` (`handle_embeddings_impl`).
251    /// * `/v1/tokenize`: the request's own `parse_special`, default
252    ///   `true` (`json_value(body, "parse_special", true)`).
253    /// * DRY sequence breakers: `AsText`
254    ///   (`llama-sampler.cpp`: `vocab.tokenize(str, false, false)`).
255    /// * a stop string that is one token: `Parse`. This is frink's own
256    ///   mechanism (llama.cpp matches stop strings on decoded text and
257    ///   tokenizes them only to trim `n_probs`), and a caller who names
258    ///   `<|eot_id|>` as a stop means the token.
259    /// * a tool-call opener that anchors the paged KV window: `Parse`,
260    ///   because the opener is a special token where the family has one.
261    pub(crate) fn encode(&self, text: &str, specials: SpecialTokens) -> Vec<usize> {
262        match self {
263            Model::Gguf(m) => m.tokenizer.encode(text, specials),
264            Model::Kimi(m) => m
265                .tokenizer
266                .encode(text, specials)
267                .into_iter()
268                .map(|id| id as usize)
269                .collect(),
270            Model::Mla(m) => m.tokenizer.encode(text, specials),
271            Model::Gemma4(m) => m.tokenizer.encode(text, specials),
272            Model::Glm52(m) => m.tokenizer.encode(text, specials),
273        }
274    }
275
276    /// The BOS id the generation path would prepend, or `None` when
277    /// this checkpoint's own metadata says not to prepend one.
278    ///
279    /// Read by `/tokenize`'s `add_special`, so that endpoint reports
280    /// the prompt the model would actually be given rather than a
281    /// second opinion about it. Kimi has no BOS id plumbed through the
282    /// server -- `run_generation` passes `None` for it -- and this
283    /// agrees with that rather than inventing one.
284    pub(crate) fn bos_id(&self) -> Option<usize> {
285        match self {
286            Model::Gguf(m) => m.bos_id,
287            Model::Kimi(_) => None,
288            Model::Mla(m) => m.bos_id,
289            Model::Gemma4(m) => m.bos_id,
290            Model::Glm52(m) => m.bos_id,
291        }
292    }
293
294    pub(crate) fn decode(&self, ids: &[usize]) -> String {
295        match self {
296            Model::Gguf(m) => m.tokenizer.decode(ids),
297            Model::Kimi(m) => {
298                let ids32: Vec<u32> = ids.iter().map(|&id| id as u32).collect();
299                m.tokenizer.decode(&ids32)
300            }
301            Model::Mla(m) => m.tokenizer.decode(ids),
302            Model::Gemma4(m) => m.tokenizer.decode(ids),
303            Model::Glm52(m) => m.tokenizer.decode(ids),
304        }
305    }
306
307    /// Final-normed last-layer hidden states for GGUF Decoder only.
308    /// Returns `None` for engines without a hidden-state hook (e.g. Kimi/MLA/GLM).
309    pub(crate) fn embed_tokens(&self, tokens: &[usize]) -> Option<Vec<Vec<f32>>> {
310        match self {
311            Model::Gguf(m) => {
312                let mut caches: Vec<_> = m.decoder.config.new_kv_caches();
313                Some(m.decoder.forward_hidden_batch(tokens, 0, &mut caches))
314            }
315            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
316        }
317    }
318
319    /// The generic GGUF decoder, when that is what is loaded.
320    ///
321    /// `None` for the dedicated engines (Kimi, MLA, Gemma-4, GLM-5.2):
322    /// they hold their own KV in their own shape, and
323    /// [`crate::slots`]'s file format describes the generic one.
324    pub(crate) fn gguf_decoder(&self) -> Option<&Arc<Decoder>> {
325        match self {
326            Model::Gguf(m) => Some(&m.decoder),
327            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
328        }
329    }
330
331    pub(crate) fn vocab_size(&self) -> Option<usize> {
332        match self {
333            Model::Gguf(m) => Some(m.decoder.config.vocab_size),
334            Model::Kimi(m) => Some(m.tokenizer.vocab_size()),
335            Model::Mla(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
336            Model::Gemma4(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
337            Model::Glm52(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
338        }
339    }
340
341    /// True when this checkpoint carries a real vocabulary rather than
342    /// the byte-level fallback the synthetic-weight demo model uses.
343    ///
344    /// Read by the DRY sampler, whose sequence breakers are strings that
345    /// only mean something against a real tokenizer; see
346    /// [`frink_models::dry::DryVocabMissing`].
347    fn has_real_vocabulary(&self) -> bool {
348        match self {
349            Model::Gguf(m) => !matches!(*m.tokenizer, model::ServerTokenizer::Byte),
350            Model::Kimi(_) => true,
351            Model::Mla(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
352            Model::Gemma4(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
353            Model::Glm52(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
354        }
355    }
356}
357
358/// What the DRY sampler needs to tokenise its sequence breakers.
359///
360/// One trait, two implementations (`frink_cli`'s `CliTokenizer` has the
361/// other), so `--dry-sequence-breaker` and the `dry_sequence_breakers`
362/// request field cannot come to mean different things.
363impl frink_models::dry::DryVocab for Model {
364    fn n_tokens(&self) -> usize {
365        self.vocab_size().unwrap_or(0)
366    }
367
368    fn detokenize(&self, token: usize) -> String {
369        self.decode(&[token])
370    }
371
372    fn tokenize(&self, text: &str) -> Vec<usize> {
373        self.encode(text, SpecialTokens::AsText)
374    }
375}
376
377pub(crate) struct AppState {
378    /// A **side-car** embedding model (`FRINK_EMBEDDING_MODEL_PATH`),
379    /// served by `/v1/embeddings` in preference to pooling a decoder's
380    /// hidden states.
381    ///
382    /// This is now the *second* way an encoder gets here. The first is
383    /// [`AppState::active`]: an encoder-only checkpoint at
384    /// `FRINK_MODEL_PATH` (or swapped in through
385    /// `/admin/models/load`) is the loaded model, as
386    /// [`crate::loaded::Loaded::Encoder`]. This field is what a
387    /// deployment uses when it wants a generative model active *and*
388    /// embeddings from a real encoder at the same time -- one process,
389    /// two checkpoints, which the active-model slot alone cannot
390    /// express. See [`AppState::embedding_model`] for which wins.
391    pub(crate) embedding: Option<Arc<frink_models::EmbeddingModel>>,
392    /// The swappable active model.
393    ///
394    /// **A reader clones the `Arc` under the read lock and then runs;
395    /// the lock is never held across a decode.** That is the whole
396    /// design: `RwLock` guards the *pointer*, not the model, so
397    /// `/admin/models/load` swapping in a new `Arc` cannot stall a
398    /// request that is already generating, and a request that started
399    /// against the old model keeps decoding against the exact weights
400    /// it began with until it finishes -- the old `ActiveModel` (and
401    /// its batcher thread) is dropped only when the last in-flight
402    /// holder releases it, not when the swap happens. Requests that
403    /// arrive after the swap see the new model. There is deliberately
404    /// no attempt to migrate an in-flight request: half a completion
405    /// from one checkpoint and half from another is worse than either.
406    ///
407    /// `None` means nothing is loaded (after `/admin/models/unload`, or
408    /// a failed startup load): generation endpoints answer 503 rather
409    /// than pretending, and `/health` reports `unavailable`.
410    active: std::sync::RwLock<Option<Arc<ActiveModel>>>,
411    /// Set while a load task is in flight, so a second load request is
412    /// rejected instead of racing the first. A load is not cheap and
413    /// two concurrent ones would fight for the same memory.
414    pub(crate) load_in_progress: std::sync::atomic::AtomicBool,
415    /// Long-running jobs (download, load) -- see the `tasks` module.
416    pub(crate) tasks: Arc<tasks::TaskRegistry>,
417    /// Generations that can currently be stopped by `POST /v1/cancel`
418    /// -- see the `cancel` module for why a dropped socket alone is not
419    /// enough.
420    pub(crate) cancels: Arc<cancel::CancelRegistry>,
421    /// Recent-request ring buffer and the counters behind
422    /// `/admin/stats` -- see the `stats` module.
423    pub(crate) stats: stats::Stats,
424    /// Replay buffers for streams started with `stream_resumable`.
425    /// See the `resume` module.
426    pub(crate) streams: resume::StreamRegistry,
427    /// The directory `/admin/models` scans, when one is configured.
428    pub(crate) model_dir: Option<PathBuf>,
429    /// The only shared *mutable* state in the server. Locked only for
430    /// the brief get/put around a cache lookup, never held across a
431    /// decode -- see the module doc comment.
432    response_cache: Mutex<ResponseCache>,
433    /// `Some` when `FRINK_KV_POOL_BLOCKS`/`FRINK_KV_POOL_BLOCK_SIZE`
434    /// are set: every request's per-layer KV caches then draw from
435    /// this one shared, bounded pool instead of each growing
436    /// unboundedly. A request whose caches can't get their first block
437    /// retries for up to `FRINK_KV_POOL_QUEUE_TIMEOUT_MS` (zero by
438    /// default -- reject immediately) before being rejected with 503,
439    /// rather than being admitted regardless of how many other
440    /// requests are already decoding -- see
441    /// `frink_core::cache::KvBlockPool` and `generate::KvPoolConfig`.
442    /// `None` (the default) preserves the
443    /// original unbounded-per-request behavior exactly.
444    pub(crate) kv_pool: Option<generate::KvPoolConfig>,
445    /// `Some` when `FRINK_PAGED_KV_BLOCKS` is set: per-layer paged KV
446    /// storage every request draws pages from, rather than each request
447    /// owning a private contiguous buffer.
448    ///
449    /// Mutually exclusive with BOTH `kv_pool` and `prefix_cache`, and
450    /// refused at startup rather than silently preferred. Against
451    /// `kv_pool` because they are two answers to the same question.
452    /// Against `prefix_cache` because `PrefixCache` stores
453    /// `Vec<KvCache>` snapshots, which a paged request has none of, so
454    /// enabling both would give a cache that can never hit -- see
455    /// `wire-radix-prefix-cache` in the plan, which is what removes
456    /// that restriction.
457    pub(crate) paged_kv: Option<generate::PagedKvConfig>,
458    /// `Some` when `FRINK_PREFIX_CACHE_ENTRIES` is set: a shared,
459    /// LRU-bounded store of previously processed prompt+KV-state
460    /// snapshots (see `frink_models::PrefixCache`), consulted so a
461    /// request that *extends* an earlier one -- the common multi-turn-
462    /// chat case -- can skip recomputing the shared part. Mutually
463    /// exclusive with `kv_pool` (see `generate::generate`'s doc
464    /// comment for why); `None` (the default) means every request
465    /// processes its full prompt from scratch, exactly as before this
466    /// existed.
467    pub(crate) prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
468    /// Server-side per-session conversation history -- see
469    /// `session::SessionStore`'s doc comment.
470    /// Always present (unlike `kv_pool`/`prefix_cache`, it's not
471    /// opt-in): a request that never sends `session_id` simply never
472    /// touches it, at negligible cost (one empty `HashMap`).
473    sessions: session::SessionStore,
474    requests_total: std::sync::atomic::AtomicU64,
475    request_errors_total: std::sync::atomic::AtomicU64,
476    started_at: std::time::Instant,
477    /// Milliseconds after `started_at` at which the last request
478    /// finished; 0 means none has. Reported by `/health` as an age, so a
479    /// client that sees a slow health poll from a GPU-saturated server
480    /// has positive evidence of liveness instead of declaring it dead.
481    last_request_ms: std::sync::atomic::AtomicU64,
482    /// Backend capability probe behind `/health` (see `health` module).
483    detection: Arc<health::Detection>,
484    /// Loaded MCP config (`--mcp-config`); tool invocation not wired yet.
485    mcp: Option<mcp::LoadedMcpConfig>,
486    /// Whether a swapped-in GGUF model should get a continuous-batching
487    /// worker, decided once at startup from the same env var and
488    /// exclusions as the initial load.
489    pub(crate) continuous_batching_enabled: bool,
490    /// Serializes private-loop Metal decodes when continuous batching is
491    /// off. Shared `metal_attn_kv` is not safe across concurrent
492    /// `forward_token` calls yet; see `docs/plans/metal-parallel-concurrency.md`.
493    pub(crate) metal_private_decode_gate: Option<Arc<std::sync::Mutex<()>>>,
494    /// The model id a load task is currently working on, so
495    /// `/admin/models` can report `loading` for it. Separate from
496    /// `load_in_progress` because that is a gate and this is a label.
497    loading_model: Mutex<Option<String>>,
498    /// The last failed load, as `(model id, message)`. Sticky until the
499    /// next successful load so `/admin/models` can say *why* an entry
500    /// is in `error` without the user retrying to find out.
501    last_load_error: Mutex<Option<(String, String)>>,
502    /// Live serving counters and the two sliding-window rates behind
503    /// `/v1/stats` -- see `crate::stats::ServingStats`. Distinct from
504    /// `stats`, which is the historical ring: this is what is happening
505    /// *now*, and it decays to zero when nothing is.
506    pub(crate) serving: Mutex<crate::stats::ServingStats>,
507    /// The gate every request, cache rebuild and shutdown passes
508    /// through -- see `crate::policy::maintenance::MaintenanceGate`. Held across none
509    /// of them: each operation takes it, reads or moves the state, and
510    /// releases before doing any work.
511    pub(crate) maintenance: Mutex<crate::policy::maintenance::MaintenanceGate>,
512    /// The live memory reading behind `/v1/stats`, re-probed at most
513    /// once per [`FOOTPRINT_TTL_MS`] -- see
514    /// `cache_admin::footprint_json`. A `Mutex` and not an atomic
515    /// because holding it across the probe is what collapses concurrent
516    /// pollers onto ONE VMA walk.
517    pub(crate) footprint:
518        Mutex<crate::policy::footprint::ProbeCache<crate::policy::footprint::Footprint>>,
519    /// Wall-clock second this process started serving.
520    ///
521    /// Distinct from `started_at`, which is an `Instant` and has no
522    /// wall clock at all. This exists so an accounting receipt's id can
523    /// be derived from something stable for the life of THIS process
524    /// and different in the next one: a pid alone is reused across
525    /// restarts, and a restarted engine reusing a previous
526    /// generation's receipt id would have its own receipt silently
527    /// skipped as already written.
528    pub(crate) started_unix: u64,
529}
530
531/// How long a memory reading is served before it is taken again.
532///
533/// Two seconds: long enough that a dashboard polling once a second
534/// costs one probe rather than one per poll, short enough that an
535/// operator watching a load ramp sees it move.
536pub(crate) const FOOTPRINT_TTL_MS: u64 = 2_000;
537
538impl AppState {
539    /// Clones the active model's `Arc` and releases the lock before
540    /// returning. Every caller then runs against its own handle, so no
541    /// decode ever holds this lock -- see [`AppState::active`].
542    pub(crate) fn active(&self) -> Option<Arc<ActiveModel>> {
543        self.active
544            .read()
545            .unwrap_or_else(|p| p.into_inner())
546            .clone()
547    }
548
549    /// [`AppState::active`] for a request that cannot proceed without a
550    /// model. 503 with a `Retry-After`-shaped explanation is the honest
551    /// answer while nothing is loaded; the alternative -- keeping a
552    /// stale model around so the endpoint never fails -- would serve
553    /// tokens from a checkpoint the operator explicitly unloaded.
554    pub(crate) fn require_active(&self) -> Result<Arc<ActiveModel>, ApiError> {
555        self.active().ok_or_else(|| {
556            (
557                StatusCode::SERVICE_UNAVAILABLE,
558                Json(serde_json::json!({"error": {
559                    "message": "no model is loaded; POST /admin/models/load with an id from \
560                                GET /admin/models",
561                    "type": "model_not_loaded"
562                }})),
563            )
564        })
565    }
566
567    /// [`AppState::active`]'s *generation* model only, for the many
568    /// call sites that do not care about the batcher.
569    ///
570    /// Two refusals live behind this one `?`: nothing loaded (503, from
571    /// [`AppState::require_active`]) and an encoder loaded (501, from
572    /// [`ActiveModel::generative`]). They are different answers to
573    /// different questions and neither may be given for the other.
574    pub(crate) fn require_model(&self) -> Result<Arc<Model>, ApiError> {
575        Ok(Arc::clone(self.require_active()?.generative()?))
576    }
577
578    /// Publishes a new active model (or `None` to unload) and returns
579    /// the previous one.
580    ///
581    /// The write lock is held only for the pointer swap. The returned
582    /// value is the caller's to drop *outside* the lock: dropping a
583    /// multi-gigabyte model can take a moment, and doing it under the
584    /// lock would block every reader for exactly as long.
585    pub(crate) fn swap_active(&self, next: Option<Arc<ActiveModel>>) -> Option<Arc<ActiveModel>> {
586        let mut guard = self.active.write().unwrap_or_else(|p| p.into_inner());
587        std::mem::replace(&mut *guard, next)
588    }
589
590    /// Stamps "a request just finished" for `/health`'s liveness
591    /// vouching. Relaxed: this is a freshness hint, not a
592    /// synchronization point.
593    fn mark_request_finished(&self) {
594        let ms = self.started_at.elapsed().as_millis().min(u64::MAX as u128) as u64;
595        self.last_request_ms
596            .store(ms, std::sync::atomic::Ordering::Relaxed);
597    }
598
599    pub(crate) fn uptime(&self) -> Duration {
600        self.started_at.elapsed()
601    }
602
603    pub(crate) fn requests_total(&self) -> u64 {
604        self.requests_total
605            .load(std::sync::atomic::Ordering::Relaxed)
606    }
607
608    pub(crate) fn errors_total(&self) -> u64 {
609        self.request_errors_total
610            .load(std::sync::atomic::Ordering::Relaxed)
611    }
612
613    pub(crate) fn cache_stats(&self) -> response_cache::CacheStats {
614        lock_cache(&self.response_cache).stats()
615    }
616
617    /// Seconds since the last request finished, or `None` when none
618    /// has. Same derivation `/health` uses, so the two agree.
619    pub(crate) fn last_request_age_seconds(&self) -> Option<f64> {
620        let last = self
621            .last_request_ms
622            .load(std::sync::atomic::Ordering::Relaxed);
623        (last > 0)
624            .then(|| self.uptime().as_secs_f64() - (last as f64 / 1000.0))
625            .map(|age| age.max(0.0))
626    }
627
628    pub(crate) fn loading_model_id(&self) -> Option<String> {
629        self.loading_model
630            .lock()
631            .unwrap_or_else(|p| p.into_inner())
632            .clone()
633    }
634
635    pub(crate) fn set_loading_model(&self, id: Option<String>) {
636        *self.loading_model.lock().unwrap_or_else(|p| p.into_inner()) = id;
637    }
638
639    pub(crate) fn last_load_error(&self) -> Option<(String, String)> {
640        self.last_load_error
641            .lock()
642            .unwrap_or_else(|p| p.into_inner())
643            .clone()
644    }
645
646    pub(crate) fn set_last_load_error(&self, error: Option<(String, String)>) {
647        *self
648            .last_load_error
649            .lock()
650            .unwrap_or_else(|p| p.into_inner()) = error;
651    }
652
653    /// Records one finished request in the `/admin/stats` ring buffer.
654    ///
655    /// `attribution` is threaded from the request's own headers rather
656    /// than looked up here: by the time a generation task finishes, the
657    /// request parts are long gone, and reconstructing "who was that"
658    /// afterwards is exactly the guessing the monitor exists to avoid.
659    /// The model that would serve a request right now, as `/v1/models`
660    /// names it. `None` when nothing is loaded.
661    pub(crate) fn active_model_name(&self) -> Option<String> {
662        self.active().map(|a| a.name().to_string())
663    }
664
665    /// The encoder `/v1/embeddings` should use, from either of the two
666    /// ways one gets here.
667    ///
668    /// `FRINK_EMBEDDING_MODEL_PATH` wins over an encoder loaded as the
669    /// active model, and it has to: a deployment that names both has
670    /// asked for the side-car explicitly, while the active model may
671    /// have been swapped in by `/admin/models/load` since. Only one of
672    /// the two is ever set in practice -- the side-car exists so a
673    /// *generative* model can be active at the same time.
674    pub(crate) fn embedding_model(&self) -> Option<Arc<frink_models::EmbeddingModel>> {
675        self.embedding
676            .clone()
677            .or_else(|| self.active().and_then(|a| a.encoder().map(Arc::clone)))
678    }
679
680    /// What `/v1/embeddings` is actually charging against, for the
681    /// `/admin/stats` ring: the embedding model when one is serving,
682    /// otherwise whichever decoder is active.
683    pub(crate) fn embedding_model_name(&self) -> Option<String> {
684        match self.embedding_model() {
685            Some(e) => Some(e.name().to_string()),
686            None => self.active_model_name(),
687        }
688    }
689
690    pub(crate) fn record_request(&self, record: stats::Record<'_>) {
691        self.stats.record(stats::entry(record));
692    }
693}
694
695/// Defense in depth: if a panic ever happened while this lock was held
696/// (none of the CPU-bound decode work runs under it, so this should be
697/// very unlikely), recovering the inner state on poison rather than
698/// `.unwrap()`ing keeps the cache from permanently bricking the server.
699fn lock_cache(cache: &Mutex<ResponseCache>) -> MutexGuard<'_, ResponseCache> {
700    cache
701        .lock()
702        .unwrap_or_else(|poisoned| poisoned.into_inner())
703}
704
705#[derive(Debug, Clone, Deserialize)]
706#[serde(untagged)]
707pub(crate) enum MessageContent {
708    Text(String),
709    Parts(Vec<ContentPart>),
710}
711
712#[derive(Debug, Clone, Deserialize)]
713struct ContentPart {
714    #[serde(rename = "type")]
715    kind: String,
716    #[serde(default)]
717    text: Option<String>,
718    #[serde(default)]
719    image_url: Option<serde_json::Value>,
720}
721
722impl MessageContent {
723    fn as_text(&self) -> String {
724        match self {
725            Self::Text(s) => s.clone(),
726            Self::Parts(parts) => parts
727                .iter()
728                .filter_map(|p| p.text.as_deref())
729                .collect::<Vec<_>>()
730                .join(""),
731        }
732    }
733
734    fn has_image(&self) -> bool {
735        match self {
736            Self::Text(_) => false,
737            Self::Parts(parts) => parts
738                .iter()
739                .any(|p| p.kind == "image_url" || p.image_url.is_some()),
740        }
741    }
742}
743
744#[derive(Debug, Clone, Deserialize)]
745pub(crate) struct ChatMessage {
746    pub(crate) role: String,
747    /// `None` for an assistant message that made tool calls instead of
748    /// replying with text (the real OpenAI convention: `content` and
749    /// `tool_calls` are mutually exclusive on an assistant message).
750    #[serde(default)]
751    pub(crate) content: Option<MessageContent>,
752    /// Present on a replayed assistant message that previously made
753    /// one or more tool calls (conversation history a client sends
754    /// back on a follow-up request).
755    #[serde(default)]
756    pub(crate) tool_calls: Option<Vec<ToolCallIn>>,
757    /// Present on a `"tool"`-role message carrying a call's result
758    /// (unused by rendering today -- `role` alone already
759    /// distinguishes it -- but accepted so real OpenAI-shaped tool-
760    /// result messages deserialize without error).
761    #[serde(default)]
762    #[allow(dead_code)]
763    pub(crate) tool_call_id: Option<String>,
764    /// A replayed assistant turn's chain of thought, kept out of
765    /// `content` on the way in and handed back to the template on the
766    /// way out.
767    ///
768    /// It has to be a field of its own rather than prose folded into
769    /// `content`, because a template that knows about reasoning wraps
770    /// it in the family's own markers -- and a template that does not
771    /// must be able to drop it. Concatenating it into `content` would
772    /// show a model its own scratchpad as if it had said it out loud,
773    /// which is exactly what the markers exist to prevent.
774    ///
775    /// Accepted under both spellings clients use: `reasoning_content`
776    /// (the DeepSeek convention frink emits) and `reasoning`
777    /// (what the OpenAI Responses and Anthropic surfaces call it), so a
778    /// client can replay a turn shaped the way it received it.
779    #[serde(default, alias = "reasoning")]
780    pub(crate) reasoning_content: Option<String>,
781}
782
783impl ChatMessage {
784    /// The text this message actually contributes to a rendered
785    /// prompt: `content` verbatim for an ordinary message, or (for a
786    /// replayed assistant message carrying `tool_calls`) each call
787    /// re-rendered as the same `<tool_call>{...}</tool_call>` marker
788    /// text a model is asked to produce for a *new* call -- see
789    /// `chat_template`'s module doc comment for why.
790    fn rendered_content(&self) -> String {
791        let mut out = self
792            .content
793            .as_ref()
794            .map(MessageContent::as_text)
795            .unwrap_or_default();
796        if let Some(calls) = &self.tool_calls {
797            for call in calls {
798                out.push_str(&format!(
799                    "<tool_call>{{\"name\": \"{}\", \"arguments\": {}}}</tool_call>",
800                    call.function.name, call.function.arguments
801                ));
802            }
803        }
804        out
805    }
806}
807
808#[derive(Debug, Clone, Deserialize)]
809pub(crate) struct ToolCallIn {
810    #[serde(default)]
811    #[allow(dead_code)]
812    id: String,
813    #[serde(rename = "type", default)]
814    #[allow(dead_code)]
815    kind: String,
816    function: ToolCallFunctionIn,
817}
818
819#[derive(Debug, Clone, Deserialize)]
820struct ToolCallFunctionIn {
821    name: String,
822    /// A JSON-encoded string (the real OpenAI convention for
823    /// `tool_calls[].function.arguments`), not a nested object --
824    /// spliced directly into the re-rendered `<tool_call>{...}` marker
825    /// text since it's already valid JSON.
826    arguments: String,
827}
828
829/// A tool definition in the real OpenAI request shape:
830/// `{"type": "function", "function": {"name", "description", "parameters"}}`.
831#[derive(Debug, Clone, Deserialize)]
832struct ToolDef {
833    #[serde(rename = "type", default)]
834    #[allow(dead_code)]
835    kind: String,
836    function: ToolFunctionDef,
837}
838
839#[derive(Debug, Clone, Deserialize)]
840struct ToolFunctionDef {
841    name: String,
842    #[serde(default)]
843    description: Option<String>,
844    #[serde(default)]
845    parameters: Option<serde_json::Value>,
846}
847
848/// OpenAI's `tool_choice`: `"auto"`/`"none"`/`"required"`, or an object
849/// pinning one specific function.
850///
851/// All four are honoured now. `"none"` hides the tools from the prompt;
852/// `"auto"` offers them; `"required"` and a named function FORCE a call,
853/// by compiling the offered tools into a grammar the decode loop must
854/// keep parseable (`crate::tool_grammar`). Before that grammar existed
855/// the last two were a 501, because a server that is asked to force a
856/// call and can only ask for one in the prompt has not done what it was
857/// told.
858#[derive(Debug, Clone, Deserialize)]
859#[serde(untagged)]
860enum ToolChoice {
861    Mode(String),
862    Specific(serde_json::Value),
863}
864
865/// OpenAI's `stop` field accepts either a single string or an array of
866/// strings.
867#[derive(Deserialize)]
868#[serde(untagged)]
869enum StopParam {
870    One(String),
871    Many(Vec<String>),
872}
873
874#[derive(Deserialize)]
875struct ChatCompletionRequest {
876    model: String,
877    messages: Vec<ChatMessage>,
878    #[serde(default = "default_max_tokens")]
879    max_tokens: usize,
880    #[serde(default)]
881    temperature: Option<f32>,
882    #[serde(default)]
883    top_p: Option<f32>,
884    /// llama.cpp's `--min-p`. Not an OpenAI field; accepted under the
885    /// same spelling llama.cpp's server uses, because a client
886    /// that sends it and is silently served an unfiltered distribution
887    /// cannot tell that apart from having had it honoured.
888    #[serde(default)]
889    min_p: Option<f32>,
890    #[serde(default)]
891    top_k: Option<usize>,
892    #[serde(default)]
893    repetition_penalty: Option<f32>,
894    /// llama.cpp's `typ_p`, `top_n_sigma`, `xtc_*` and `dry_*`, in ONE
895    /// struct shared with the other two routes that take them. See
896    /// `sampling_knobs::ExtraSamplerFields`.
897    #[serde(flatten)]
898    extra_samplers: crate::sampling_knobs::ExtraSamplerFields,
899    /// Fields that change what comes back and that this server does not
900    /// implement, in ONE struct shared with the other two generation
901    /// routes. See `crate::unimplemented_fields`.
902    #[serde(flatten)]
903    unimplemented: crate::unimplemented_fields::UnimplementedFields,
904    #[serde(default)]
905    seed: Option<u64>,
906    #[serde(default)]
907    stop: Option<StopParam>,
908    #[serde(default)]
909    stream: Option<bool>,
910    /// Frink extension. `true` asks the server to keep a replay buffer
911    /// for this stream so a dropped connection can be resumed from the
912    /// last `id:` seen, or drained over the JSON polling fallback.
913    ///
914    /// It also changes what a dropped socket *means*. Without it, the
915    /// connection closing cancels the generation (see the `cancel`
916    /// module). With it, the generation keeps running into the replay
917    /// buffer -- which is the entire point, and the reason this is the
918    /// caller's decision rather than the server's: a tab that navigated
919    /// away wants the CPU back, and a tab whose proxy dropped a
920    /// 90-second answer wants the answer. `POST /v1/cancel` stops a
921    /// resumable stream either way.
922    #[serde(default)]
923    stream_resumable: Option<bool>,
924    /// Run past the model's own end-of-generation tokens, so this
925    /// request produces exactly `max_tokens`.
926    ///
927    /// A serving-benchmark knob, under the spelling the other
928    /// OpenAI-compatible servers use. It
929    /// exists because a benchmark whose requests stop at their own EOS
930    /// finishes them at different lengths, and the slowest percentile
931    /// is then whichever request happened to be asked for the most
932    /// tokens -- a fact about the prompts, reported as a fact about the
933    /// server. It does NOT withdraw the caller's own `stop` strings.
934    #[serde(default)]
935    ignore_eos: Option<bool>,
936    #[serde(default)]
937    tools: Vec<ToolDef>,
938    #[serde(default)]
939    tool_choice: Option<ToolChoice>,
940    /// The OpenAI extension every reasoning-model deployment actually
941    /// uses: whatever is in here becomes a top-level variable in the
942    /// checkpoint's own chat template, which is how `enable_thinking`
943    /// (Qwen3, gemma-4), `thinking` (DeepSeek) and `reasoning_effort`
944    /// are really driven. Values here can never shadow the structural
945    /// variables (`messages`, `tools`, `add_generation_prompt`) -- see
946    /// `frink_models::chat_template::RenderOptions`.
947    #[serde(default)]
948    chat_template_kwargs: Option<serde_json::Map<String, serde_json::Value>>,
949    /// OpenAI's own spelling of the same knob. It is folded into
950    /// `chat_template_kwargs` before rendering, and loses to an explicit
951    /// entry there: a caller who wrote both meant the specific one.
952    ///
953    /// `"none"` and `"off"` are not gears -- they mean *do not think*,
954    /// and are handled by [`ChatCompletionRequest::thinking_direction`]
955    /// before any quantization can round them onto a real one.
956    #[serde(default)]
957    reasoning_effort: Option<String>,
958    /// The DeepSeek wire's thinking switch: `{"type": "enabled"}` or
959    /// `{"type": "disabled"}`. It decides the direction outright, and
960    /// `disabled` beats any effort the same request also carries.
961    #[serde(default)]
962    thinking: Option<ThinkingSwitch>,
963    /// Server-side conversation history key (see the `session`
964    /// module): when set, `messages` is treated as
965    /// *only the new turn(s)* to append to this session's stored
966    /// history, not the whole conversation.
967    #[serde(default)]
968    session_id: Option<String>,
969    /// llama.cpp's `continue_final_message`: render the LAST message,
970    /// which must be an assistant turn, as a turn still being written
971    /// rather than a closed one, so the model carries on from where
972    /// it stopped. `true`, `"reasoning_content"`, `"content"`, or
973    /// `false`; unset, a trailing assistant message is continued by
974    /// default, as llama.cpp's server does. The whole rule, its
975    /// refusals included, is [`continuation`].
976    #[serde(default, deserialize_with = "continuation::deserialize")]
977    continue_final_message: continuation::ContinueFinalMessage,
978    /// llama.cpp's `reasoning_budget_tokens` (alias
979    /// `thinking_budget_tokens`): a token budget for the chain of
980    /// thought, enforced in the sampler. `-1` or absent takes the
981    /// server's `--reasoning-budget`; `0` closes the block the moment it
982    /// opens; `N` allows N tokens of thought and then forces the closer.
983    /// The range is checked at deserialization, so an out-of-range
984    /// value is a 400 naming the field. See [`crate::reasoning_budget`].
985    #[serde(default, alias = "thinking_budget_tokens")]
986    reasoning_budget_tokens: Option<reasoning_budget::BudgetTokens>,
987    /// OpenAI fields we explicitly reject rather than silently ignore.
988    #[serde(default)]
989    logprobs: Option<bool>,
990    #[serde(default)]
991    top_logprobs: Option<u32>,
992    #[serde(default)]
993    presence_penalty: Option<f32>,
994    #[serde(default)]
995    frequency_penalty: Option<f32>,
996    #[serde(default)]
997    response_format: Option<serde_json::Value>,
998    /// Declared ONLY so it can be refused by name -- see
999    /// [`crate::unsupported_sampling::refuse_logit_bias`], which
1000    /// `/v1/completions` calls with the same rules. Undeclared, serde
1001    /// dropped it and the caller got a 200 whose answer was sampled
1002    /// from unbiased logits, which is indistinguishable from having had
1003    /// the bias honoured.
1004    #[serde(default)]
1005    logit_bias: Option<serde_json::Value>,
1006    /// llama.cpp's per-request `lora: [{id, scale}]`: the scale of every
1007    /// loaded adapter for THIS request, unnamed adapters at 0. Resolved
1008    /// against the loaded adapters by `crate::lora::resolve_request`.
1009    #[serde(default)]
1010    lora: Option<Vec<frink_api::LoraScaleRequest>>,
1011    /// llama.cpp's `samplers`: the ORDER the sampler chain runs in,
1012    /// either a list of names or the one `;`-separated string
1013    /// `--samplers` takes.
1014    ///
1015    /// Read as `Value` and decided by
1016    /// [`crate::unsupported_sampling::parse_sampler_order`], shared with
1017    /// `/v1/completions` and `/completion`, so the three routes cannot
1018    /// disagree about which samplers exist. A sampler frink does not
1019    /// implement is refused BY NAME rather than dropped from the chain.
1020    #[serde(default)]
1021    samplers: Option<serde_json::Value>,
1022    /// A GBNF grammar every sampled token must keep parseable.
1023    ///
1024    /// llama.cpp's field, spelled the same way, because a client that
1025    /// already builds a grammar for `llama-server` should not have to
1026    /// build a second one. Not an OpenAI field: OpenAI states the same
1027    /// constraint as `response_format: {"type": "json_schema"}`, which
1028    /// is now compiled through the same grammar engine. Sending BOTH is
1029    /// two constraints on one generation and is refused -- see
1030    /// [`crate::grammar_request`], where every spelling is resolved.
1031    #[serde(default)]
1032    grammar: Option<String>,
1033}
1034
1035/// The output budget a chat request gets when it names none.
1036///
1037/// Not OpenAI's legacy 16 -- that floor belongs to `/v1/completions`,
1038/// where a caller asking for a completion of a fragment usually wants a
1039/// fragment back. A chat client that omits `max_tokens` wants an
1040/// answer, and 16 tokens of one reads as a truncated server.
1041///
1042/// It is safe to be this large only because the context ceiling CLAMPS
1043/// rather than refuses (see `generate`): a request whose prompt leaves
1044/// less than this much room is served with what remains, not rejected
1045/// over a number the caller never set.
1046const DEFAULT_CHAT_MAX_TOKENS: usize = 32_768;
1047
1048/// The DeepSeek-wire thinking switch.
1049#[derive(Debug, Clone, Deserialize)]
1050pub(crate) struct ThinkingSwitch {
1051    #[serde(rename = "type")]
1052    pub(crate) kind: String,
1053}
1054
1055/// Every spelling a caller can use to steer the template's thinking
1056/// themselves. If any of these is already present in
1057/// `chat_template_kwargs`, the protocol-level knobs stand down.
1058const THINKING_KWARG_KEYS: [&str; 4] = [
1059    "enable_thinking",
1060    "thinking",
1061    "thinking_mode",
1062    "reasoning_effort",
1063];
1064
1065/// The efforts that mean "do not think" rather than naming a gear.
1066/// Compared after trimming and lowercasing, because a client that sends
1067/// `"None"` means the same thing.
1068const DISABLE_EFFORTS: [&str; 2] = ["none", "off"];
1069
1070fn default_max_tokens() -> usize {
1071    DEFAULT_CHAT_MAX_TOKENS
1072}
1073
1074impl ChatCompletionRequest {
1075    /// This request's sampler knobs. Resolved to `SamplingParams` by
1076    /// `sampling_knobs`, shared with `/v1/completions`, so the two
1077    /// routes cannot disagree about what a knob means or which ones
1078    /// exist.
1079    ///
1080    /// Fallible because `samplers` is parsed here: a chain naming a
1081    /// sampler this engine does not have is a refusal, never a chain
1082    /// built without it.
1083    fn sampling_knobs(&self) -> Result<SamplingKnobs, ApiError> {
1084        let mut knobs = SamplingKnobs {
1085            temperature: self.temperature,
1086            top_p: self.top_p,
1087            min_p: self.min_p,
1088            top_k: self.top_k,
1089            repetition_penalty: self.repetition_penalty,
1090            presence_penalty: self.presence_penalty,
1091            frequency_penalty: self.frequency_penalty,
1092            // The OpenAI wire has no field for the penalty window; only
1093            // llama.cpp's native `/completion` does. See
1094            // `SamplingKnobs::penalty_last_n`.
1095            penalty_last_n: None,
1096            sampler_order: unsupported_sampling::parse_sampler_order(
1097                self.samplers.as_ref(),
1098                "/v1/chat/completions",
1099            )?,
1100            ..SamplingKnobs::default()
1101        };
1102        self.extra_samplers.apply(&mut knobs);
1103        Ok(knobs)
1104    }
1105
1106    fn sampling_params(
1107        &self,
1108        model: crate::sampling_knobs::SamplerModel<'_>,
1109    ) -> Result<SamplingParams, ApiError> {
1110        self.sampling_knobs()?.resolve(model).map_err(|e| {
1111            unsupported_feature(&format!("`dry_multiplier` on /v1/chat/completions: {e}"))
1112        })
1113    }
1114
1115    fn stop_sequences(&self) -> Vec<String> {
1116        self.stop
1117            .as_ref()
1118            .map(|s| match s {
1119                StopParam::One(v) => vec![v.clone()],
1120                StopParam::Many(v) => v.clone(),
1121            })
1122            .unwrap_or_default()
1123    }
1124
1125    /// Real tool-calling is only offered when `tools` is non-empty AND
1126    /// the client hasn't explicitly disabled it via `tool_choice:
1127    /// "none"` -- see `ToolChoice`'s doc comment for what the other
1128    /// values do (nothing different from `"auto"`).
1129    /// How many alternatives to report per position, or `None` when
1130    /// this request did not ask for logprobs at all.
1131    ///
1132    /// OpenAI's chat wire splits the question in two: `logprobs: true`
1133    /// turns the object on, and `top_logprobs: N` says how many
1134    /// alternatives to list. `top_logprobs` without `logprobs` is not
1135    /// a valid request upstream and is refused here rather than read
1136    /// as an implied `true`, because guessing which of two fields the
1137    /// caller meant is how a server answers a question nobody asked.
1138    fn n_logprobs(&self) -> Result<Option<usize>, ApiError> {
1139        const MAX: u32 = 20;
1140        match (self.logprobs, self.top_logprobs) {
1141            (Some(true), Some(n)) if n > MAX => Err(invalid_request(
1142                &format!(
1143                    "`top_logprobs` is {n}; this server reports at most {MAX} alternatives per \
1144                     position, as upstream does"
1145                ),
1146                "top_logprobs",
1147            )),
1148            (Some(true), Some(n)) => Ok(Some(n as usize)),
1149            // `logprobs: true` alone is the chosen token's logprob and
1150            // no alternatives, which is what upstream's default `0`
1151            // means.
1152            (Some(true), None) => Ok(Some(0)),
1153            (_, Some(_)) => Err(invalid_request(
1154                "`top_logprobs` requires `logprobs: true`",
1155                "top_logprobs",
1156            )),
1157            _ => Ok(None),
1158        }
1159    }
1160
1161    /// True when the caller asked for more than one completion.
1162    ///
1163    /// Read off the shared table's own field, so the route and the
1164    /// refusal cannot disagree about what `n` said.
1165    fn several_choices(&self) -> bool {
1166        self.unimplemented.n.is_some_and(|n| n > 1)
1167    }
1168
1169    fn tools_active(&self) -> bool {
1170        !self.tools.is_empty()
1171            && !matches!(&self.tool_choice, Some(ToolChoice::Mode(m)) if m == "none")
1172    }
1173
1174    /// Whether this request FORCES a tool call, and which tools it may
1175    /// choose between.
1176    ///
1177    /// `"required"` and a named function are the same question with a
1178    /// different answer set, so they are one function here and one
1179    /// grammar builder downstream. Everything else -- absent, `"auto"`,
1180    /// `"none"` -- forces nothing and returns `None`.
1181    ///
1182    /// An object `tool_choice` that names nothing is a 400 rather than a
1183    /// silent `None`: a client that sent `{"type": "function"}` and got
1184    /// an unforced answer cannot tell that apart from a served one.
1185    fn forced_tool_choice(&self) -> Result<Option<tool_grammar::Forced<'_>>, ApiError> {
1186        match &self.tool_choice {
1187            Some(ToolChoice::Mode(m)) if m == "required" => Ok(Some(tool_grammar::Forced::Any)),
1188            Some(ToolChoice::Specific(value)) => {
1189                // OpenAI's shape is `{"type":"function","function":{"name":…}}`;
1190                // several clients send `{"name":…}` flat, and both name
1191                // the same thing.
1192                let name = value
1193                    .get("function")
1194                    .and_then(|f| f.get("name"))
1195                    .or_else(|| value.get("name"))
1196                    .and_then(|n| n.as_str());
1197                match name {
1198                    Some(name) => Ok(Some(tool_grammar::Forced::Named(name))),
1199                    None => Err(invalid_request(
1200                        "tool_choice must be \"auto\", \"none\", \"required\", or an object with \
1201                         function.name",
1202                        "tool_choice",
1203                    )),
1204                }
1205            }
1206            _ => Ok(None),
1207        }
1208    }
1209
1210    /// The offered tools, reduced to what [`tool_grammar`] needs.
1211    fn tool_specs(&self) -> Vec<tool_grammar::ToolSpec<'_>> {
1212        self.tools
1213            .iter()
1214            .map(|t| tool_grammar::ToolSpec {
1215                name: &t.function.name,
1216                parameters: t.function.parameters.as_ref(),
1217            })
1218            .collect()
1219    }
1220
1221    /// The `chat_template_kwargs` this request actually renders with.
1222    ///
1223    /// Five rules, all of them from `frink-edge`:
1224    ///
1225    /// * **An explicit knob wins wholesale.** A caller who already set
1226    ///   any of `enable_thinking` / `thinking` / `thinking_mode` /
1227    ///   `reasoning_effort` inside `chat_template_kwargs` has said what
1228    ///   they want; the protocol-level knobs are then ignored entirely
1229    ///   rather than merged, because a merge would let a default
1230    ///   contradict an explicit request.
1231    /// * **`none` and `off` are not gears.** `reasoning_effort: "none"`
1232    ///   means *turn thinking off* and broadcasts the off pair; it must
1233    ///   not be quantized onto the nearest gear, which would turn "do
1234    ///   not think" into "think a little". Same for the DeepSeek-wire
1235    ///   `thinking: {"type": "disabled"}`, which beats any effort.
1236    ///
1237    /// * **Thinking follows the tools.** Offering tools turns thinking
1238    ///   on even when the caller said nothing, because some encoders
1239    ///   emit well-formed tool calls only in thinking mode
1240    ///   ([`crate::policy::effort::resolve_thinking_mode`]).
1241    /// * **Effort is quantized onto what this checkpoint grades.** A
1242    ///   template that accepts only the OpenAI triple must not be sent
1243    ///   `minimal`; it is mapped to the nearest gear, or dropped when no
1244    ///   gear is close enough, rather than interpolated verbatim into
1245    ///   the prompt ([`crate::policy::effort::sanitize_effort`], against the
1246    ///   profile probed at load).
1247    /// * **One value, every spelling.** The graded-strength dialect
1248    ///   reads `reasoning_strength`; a Jinja template ignores variables
1249    ///   it does not declare, so broadcasting costs nothing and removes
1250    ///   a per-family routing table
1251    ///   ([`crate::policy::effort::broadcast_effort_spellings`]).
1252    ///
1253    /// Every render path has to do this identically -- a request that
1254    /// validates against one prompt and generates from another is the
1255    /// failure this returns a single value to prevent.
1256    /// Which way this request steers thinking, before any template is
1257    /// consulted: `Some(false)` off, `Some(true)` on, `None` unstated.
1258    ///
1259    /// `thinking: {"type": …}` decides outright and `disabled` wins over
1260    /// any effort, because a client that sent both a switch and a gear
1261    /// meant the switch -- the gear is what it would use *if* thinking
1262    /// were on.
1263    fn thinking_direction(&self) -> Option<bool> {
1264        if let Some(switch) = &self.thinking {
1265            return match switch.kind.trim().to_ascii_lowercase().as_str() {
1266                "disabled" => Some(false),
1267                "enabled" => Some(true),
1268                // An unrecognized type is not a silent default -- see
1269                // `validate_supported_fields`, which rejects it.
1270                _ => None,
1271            };
1272        }
1273        let effort = self.reasoning_effort.as_ref()?;
1274        DISABLE_EFFORTS
1275            .contains(&effort.trim().to_ascii_lowercase().as_str())
1276            .then_some(false)
1277    }
1278
1279    fn resolve_template_kwargs(
1280        &self,
1281        template: &chat_template::PromptTemplate,
1282    ) -> serde_json::Map<String, serde_json::Value> {
1283        let mut kwargs = self.chat_template_kwargs.clone().unwrap_or_default();
1284        // Whether the caller steered the template themselves. Read
1285        // BEFORE anything is added, or every request looks explicit
1286        // from the second statement on.
1287        let caller_steered = THINKING_KWARG_KEYS.iter().any(|k| kwargs.contains_key(*k));
1288
1289        if !caller_steered {
1290            match self.thinking_direction() {
1291                Some(false) => {
1292                    for (k, v) in crate::policy::effort::thinking_off_kwargs() {
1293                        kwargs.insert(k, v);
1294                    }
1295                    // Nothing below applies: an effort would re-enter a
1296                    // block this request just closed.
1297                    return kwargs;
1298                }
1299                Some(true) => {
1300                    for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1301                        kwargs.insert(k, v);
1302                    }
1303                }
1304                None => {}
1305            }
1306            if let Some(effort) = &self.reasoning_effort {
1307                kwargs
1308                    .entry("reasoning_effort".to_string())
1309                    .or_insert_with(|| serde_json::json!(effort));
1310            }
1311        }
1312
1313        let offered: Vec<serde_json::Value> = if self.tools_active() {
1314            self.tools.iter().map(chat_template::tool_json).collect()
1315        } else {
1316            Vec::new()
1317        };
1318        let thinking = crate::policy::effort::resolve_thinking_mode(Some(&kwargs), Some(&offered));
1319        if thinking == crate::policy::effort::ThinkingMode::Thinking {
1320            for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1321                kwargs.entry(k).or_insert(v);
1322            }
1323        }
1324        match crate::policy::effort::sanitize_effort(&mut kwargs, template.efforts()) {
1325            crate::policy::effort::EffortMapping::Mapped(to) => {
1326                tracing::debug!("reasoning_effort quantized to {}", to.as_str());
1327            }
1328            crate::policy::effort::EffortMapping::Dropped => {
1329                tracing::debug!(
1330                    "reasoning_effort dropped: this checkpoint's template grades no gear close \
1331                     enough, so its own default applies"
1332                );
1333            }
1334            crate::policy::effort::EffortMapping::Unchanged => {}
1335        }
1336        crate::policy::effort::broadcast_effort_spellings(&mut kwargs);
1337        kwargs
1338    }
1339
1340    /// Reject OpenAI fields we do not implement, and `tool_choice`
1341    /// values that would silently lie (required / named function).
1342    fn validate_supported_fields(&self) -> Result<(), ApiError> {
1343        // An explicit zero is a client error, not "unset". Serde already
1344        // told them apart -- an absent field became
1345        // `DEFAULT_CHAT_MAX_TOKENS` -- so a 0 here is one the caller
1346        // wrote, and the engine cannot serve a zero-token budget: the
1347        // request would never become decodable and the client would wait
1348        // for an answer that cannot arrive.
1349        if self.max_tokens == 0 {
1350            return Err(invalid_request(
1351                "max_tokens must be at least 1",
1352                "max_tokens",
1353            ));
1354        }
1355        // An unrecognized switch is refused rather than read as "on":
1356        // a client that misspells `disabled` and is served a thinking
1357        // model anyway has been silently given the opposite of what it
1358        // asked for.
1359        if let Some(switch) = &self.thinking {
1360            let kind = switch.kind.trim().to_ascii_lowercase();
1361            if kind != "enabled" && kind != "disabled" {
1362                return Err(invalid_request(
1363                    "thinking.type must be \"enabled\" or \"disabled\"",
1364                    "thinking.type",
1365                ));
1366            }
1367        }
1368        for msg in &self.messages {
1369            if msg.content.as_ref().is_some_and(MessageContent::has_image) {
1370                return Err(unsupported_feature(
1371                    "image_url content parts are not implemented (multimodal/VL deferred, see docs/API.md)",
1372                ));
1373            }
1374        }
1375        // Served (`crate::logprobs::render_chat`); what is refused is
1376        // a `top_logprobs` above upstream's cap, which is a 400 on the
1377        // value rather than a 501 on the field.
1378        self.n_logprobs()?;
1379        // `n` moved into `crate::unimplemented_fields` with the rest of
1380        // the surface: it was refused HERE and dropped on
1381        // `/v1/completions`, which is the split that module exists for.
1382        self.unimplemented.refuse("/v1/chat/completions")?;
1383        unsupported_sampling::refuse_logit_bias(self.logit_bias.as_ref(), "/v1/chat/completions")?;
1384        // Parsed here as well as in `sampling_knobs` so a bad chain is
1385        // a 400/501 before any prompt is rendered. The same function
1386        // both times, so there is no second opinion to drift from.
1387        unsupported_sampling::parse_sampler_order(self.samplers.as_ref(), "/v1/chat/completions")?;
1388        // Every spelling of "constrain the output", resolved by the one
1389        // function that knows the rule: `grammar` is compiled and a
1390        // `response_format` is decided in full -- its schema converted,
1391        // its unhonoured members refused by name, its unknown types
1392        // refused by the type they named. Done here so all of that is a
1393        // 400 before any prompt is rendered. The result is recompiled in
1394        // `generation_params`, which is the only other caller: a grammar
1395        // is a small parse, and one rule in two places would be two
1396        // rules soon enough.
1397        //
1398        // Kept as ONE call rather than a second `match` on
1399        // `response_format` beside it. The one that used to be here
1400        // answered `json_schema` with "only json_object is supported"
1401        // and had to be kept in step with the module by hand.
1402        let stated_grammar =
1403            grammar_request::for_request(self.grammar.as_deref(), self.response_format.as_ref())?;
1404        // A forced `tool_choice` is served by compiling the offered tools
1405        // into a grammar (`tool_grammar`). What can be checked without
1406        // knowing which checkpoint is loaded is checked here, so the
1407        // caller's own mistakes are refused before a prompt is rendered;
1408        // the rest -- whether the served family's wire format has a
1409        // grammar at all -- needs the model and is refused in
1410        // `generation_params_for_template`.
1411        if let Some(forced) = self.forced_tool_choice()? {
1412            if self.tools.is_empty() {
1413                return Err(invalid_request(
1414                    "tool_choice forces a tool call, but no tools were offered",
1415                    "tool_choice",
1416                ));
1417            }
1418            if let tool_grammar::Forced::Named(name) = forced {
1419                if !self.tools.iter().any(|t| t.function.name == name) {
1420                    return Err(invalid_request(
1421                        &format!(
1422                            "tool_choice names {name:?}, which is not one of the tools offered"
1423                        ),
1424                        "tool_choice",
1425                    ));
1426                }
1427            }
1428            // Two different constraints on one generation. Serving the
1429            // one we happen to compile last is not answering either.
1430            //
1431            // Asked of the RESOLVED grammar rather than of
1432            // `self.grammar`: a `response_format` json_schema states one
1433            // too, and a check spelled against one field would have let
1434            // the other through -- `generation_params_for_template`
1435            // overwrites `params.grammar` with the tool-call grammar on
1436            // the strength of this refusal having happened.
1437            if stated_grammar.is_some() {
1438                return Err(invalid_request(
1439                    "a forced tool_choice and a \"grammar\" or response_format \"json_schema\" \
1440                     are two different constraints on the same generation; send one",
1441                    "tool_choice",
1442                ));
1443            }
1444            if self.json_object_mode() {
1445                return Err(invalid_request(
1446                    "a forced tool_choice cannot be combined with response_format json_object: \
1447                     the tool-call markers are not JSON",
1448                    "tool_choice",
1449                ));
1450            }
1451        }
1452        Ok(())
1453    }
1454
1455    /// `stop_sequences()` plus `</tool_call>` when tool-calling is
1456    /// active -- reusing the existing stop-sequence machinery
1457    /// (`generate::generate`'s `earliest_stop_match`) to end generation
1458    /// right after a tool call's JSON body, rather than adding any new
1459    /// decode-time logic. See `tool_preamble`'s doc comment for the
1460    /// full real, disclosed approach.
1461    fn effective_stop_sequences(&self) -> Vec<String> {
1462        let mut stop = self.stop_sequences();
1463        if self.tools_active() {
1464            stop.push("</tool_call>".to_string());
1465        }
1466        stop
1467    }
1468
1469    fn json_object_mode(&self) -> bool {
1470        self.response_format
1471            .as_ref()
1472            .and_then(|v| v.get("type"))
1473            .and_then(|v| v.as_str())
1474            == Some("json_object")
1475    }
1476}
1477
1478#[derive(Serialize)]
1479struct ChatCompletionChoice {
1480    index: usize,
1481    message: ChatCompletionResponseMessage,
1482    finish_reason: &'static str,
1483    /// OpenAI's chat `logprobs` object, absent unless the request
1484    /// asked (`crate::logprobs::render_chat`). `null` and absent mean
1485    /// the same thing to a client here, and absent is the smaller
1486    /// answer.
1487    #[serde(skip_serializing_if = "Option::is_none")]
1488    logprobs: Option<serde_json::Value>,
1489}
1490
1491#[derive(Serialize)]
1492struct ChatCompletionResponseMessage {
1493    role: &'static str,
1494    #[serde(skip_serializing_if = "Option::is_none")]
1495    content: Option<String>,
1496    /// A reasoning model's chain of thought, split out of `content`.
1497    /// Absent for a model that emitted none, which is also what a
1498    /// client that does not know the field sees.
1499    #[serde(skip_serializing_if = "Option::is_none")]
1500    reasoning_content: Option<String>,
1501    #[serde(skip_serializing_if = "Option::is_none")]
1502    tool_calls: Option<Vec<ToolCallOut>>,
1503}
1504
1505#[derive(Serialize, Clone)]
1506struct ToolCallOut {
1507    id: String,
1508    #[serde(rename = "type")]
1509    kind: &'static str,
1510    function: ToolCallFunctionOut,
1511}
1512
1513/// One tool call as a **streamed delta**.
1514///
1515/// OpenAI's incremental shape: `index` correlates the pieces, and every
1516/// other field is optional because the first delta of a call carries
1517/// its identity and the ones after it carry only more argument text. A
1518/// buffered path expresses a whole call as a delta with every field
1519/// set, so there is one type on the wire rather than two.
1520#[derive(Serialize, Clone)]
1521struct ToolCallDelta {
1522    index: usize,
1523    #[serde(skip_serializing_if = "Option::is_none")]
1524    id: Option<String>,
1525    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1526    kind: Option<&'static str>,
1527    function: ToolCallFunctionDelta,
1528}
1529
1530#[derive(Serialize, Clone, Default)]
1531struct ToolCallFunctionDelta {
1532    #[serde(skip_serializing_if = "Option::is_none")]
1533    name: Option<String>,
1534    /// A literal continuation of this call's arguments JSON. A client
1535    /// concatenates them in `index` order and parses the result.
1536    #[serde(skip_serializing_if = "Option::is_none")]
1537    arguments: Option<String>,
1538}
1539
1540impl ToolCallDelta {
1541    /// The whole call in one delta, for a path that had it all along.
1542    fn whole(index: usize, name: String, arguments: String) -> Self {
1543        ToolCallDelta {
1544            index,
1545            id: Some(format!("call_{index}")),
1546            kind: Some("function"),
1547            function: ToolCallFunctionDelta {
1548                name: Some(name),
1549                arguments: Some(arguments),
1550            },
1551        }
1552    }
1553
1554    /// The opening delta: identity, and no arguments yet.
1555    fn opening(index: usize, name: String) -> Self {
1556        ToolCallDelta {
1557            index,
1558            id: Some(format!("call_{index}")),
1559            kind: Some("function"),
1560            function: ToolCallFunctionDelta {
1561                name: Some(name),
1562                arguments: Some(String::new()),
1563            },
1564        }
1565    }
1566
1567    /// A continuation: more argument text for a call already opened.
1568    fn arguments(index: usize, fragment: String) -> Self {
1569        ToolCallDelta {
1570            index,
1571            id: None,
1572            kind: None,
1573            function: ToolCallFunctionDelta {
1574                name: None,
1575                arguments: Some(fragment),
1576            },
1577        }
1578    }
1579}
1580
1581#[derive(Serialize, Clone)]
1582struct ToolCallFunctionOut {
1583    name: String,
1584    /// A JSON-encoded string, matching the real OpenAI
1585    /// `tool_calls[].function.arguments` convention (see
1586    /// `ToolCallFunctionIn::arguments`'s doc comment).
1587    arguments: String,
1588}
1589
1590#[derive(Serialize)]
1591struct ChatCompletionResponse {
1592    id: String,
1593    /// Non-standard extension: the same value as `id`, stated under the
1594    /// name the rest of frink keys by (metrics, logs, `POST /cancel`
1595    /// once it exists). `id` is OpenAI's completion id and a client has
1596    /// no way to know frink also uses it as the request key -- saying
1597    /// so costs one field and removes the guess.
1598    request_id: String,
1599    object: &'static str,
1600    model: String,
1601    choices: Vec<ChatCompletionChoice>,
1602    /// OpenAI-convention token accounting (prompt/completion/total),
1603    /// counted from the exact ids the generation loop processed. On a
1604    /// whole-response cache hit, this is the original computation's
1605    /// accounting (same prompt, same deterministic outcome).
1606    usage: generate::Usage,
1607    /// Non-standard extension field (not part of the OpenAI API
1608    /// contract, but additive and harmless to OpenAI-compatible
1609    /// clients that ignore unknown fields): "hit" if this exact
1610    /// cacheable request was already computed, "miss" if this request
1611    /// just computed and cached a fresh completion, or "skip" if
1612    /// nothing was stored -- either the request wasn't cacheable at all
1613    /// (sampling without a seed -- see
1614    /// `ChatCompletionRequest::is_cacheable`) or the answer was not a
1615    /// complete one and may not be replayed to anybody (a cancelled
1616    /// generation -- see `response_cache::CachedCompletion::cacheable`).
1617    frink_cache: &'static str,
1618}
1619
1620#[derive(Serialize)]
1621struct ChatCompletionChunkDelta {
1622    #[serde(skip_serializing_if = "Option::is_none")]
1623    role: Option<&'static str>,
1624    #[serde(skip_serializing_if = "Option::is_none")]
1625    content: Option<String>,
1626    /// See `ChatCompletionResponseMessage::reasoning_content`.
1627    #[serde(skip_serializing_if = "Option::is_none")]
1628    reasoning_content: Option<String>,
1629    #[serde(skip_serializing_if = "Option::is_none")]
1630    tool_calls: Option<Vec<ToolCallDelta>>,
1631}
1632
1633#[derive(Serialize)]
1634struct ChatCompletionChunkChoice {
1635    index: usize,
1636    delta: ChatCompletionChunkDelta,
1637    finish_reason: Option<&'static str>,
1638}
1639
1640#[derive(Serialize)]
1641struct ChatCompletionChunk {
1642    id: String,
1643    /// Present on the **first** chunk of a stream (see
1644    /// `ChatCompletionResponse::request_id`). A client learns the key
1645    /// for this generation before any content arrives, so a live view
1646    /// can correlate metrics with the stream it is rendering instead of
1647    /// guessing which in-flight request is "probably mine" -- a guess
1648    /// that mis-attributes the moment two chats run at once.
1649    #[serde(skip_serializing_if = "Option::is_none")]
1650    request_id: Option<String>,
1651    object: &'static str,
1652    model: String,
1653    choices: Vec<ChatCompletionChunkChoice>,
1654    /// Present only on the final chunk (the one carrying
1655    /// `finish_reason`), mirroring OpenAI's stream `usage` shape.
1656    #[serde(skip_serializing_if = "Option::is_none")]
1657    usage: Option<generate::Usage>,
1658}
1659
1660/// Liveness, readiness and capabilities in one cheap answer (see the
1661/// `health` module for why detection is a visible state rather than a
1662/// gap). Never behind auth or rate limiting, and never blocking: this is
1663/// the endpoint a supervisor asks when it is deciding whether to kill
1664/// the process.
1665async fn health(State(state): State<Arc<AppState>>) -> Response {
1666    let snapshot = state.detection.snapshot();
1667    let mut capabilities = snapshot.capabilities;
1668    let active = state.active();
1669
1670    // Model-derived capabilities need no probing, so they are answered
1671    // even while backend detection is still running.
1672    capabilities.push(match active.as_deref() {
1673        // `unavailable` was defined in Phase 1 but unreachable, because
1674        // the server only bound the port after a successful load. With
1675        // `/admin/models/unload` it is a state a client can actually
1676        // observe, and it must not read as "loaded but synthetic".
1677        None => frink_api::Capability::unavailable(
1678            frink_api::health::capability::REAL_WEIGHTS,
1679            frink_api::health::reason::MODEL_NOT_LOADED,
1680            "No model is loaded. POST /admin/models/load with an id from GET /admin/models.",
1681        ),
1682        Some(active) if active.is_synthetic() => frink_api::Capability::unavailable(
1683            frink_api::health::capability::REAL_WEIGHTS,
1684            frink_api::health::reason::MODEL_NOT_LOADED,
1685            "Serving synthetic random weights: set FRINK_MODEL_PATH (or -m) to a real \
1686             checkpoint. Output from this model is noise.",
1687        ),
1688        // An encoder is real weights and is genuinely serving, so this
1689        // is `available` -- but a supervisor reading "serving X" and
1690        // then getting 501 from /v1/chat/completions learned nothing.
1691        // The detail says which endpoint this checkpoint is for.
1692        // NOT a hard-coded /v1/embeddings any more: a reranker is an
1693        // encoder too, and its pooling_type is RANK, which
1694        // /v1/embeddings refuses and /v1/rerank is for. See
1695        // `rerank::encoder_endpoints`, which `/v1/models` reads as well
1696        // so the two cannot disagree.
1697        Some(active) if active.encoder().is_some() => {
1698            let endpoints = active
1699                .encoder()
1700                .map(|e| encoder_endpoints(e))
1701                .unwrap_or_default();
1702            let served_by = match endpoints.is_empty() {
1703                true => "no endpoint in this build serves it".to_string(),
1704                false => format!("served by {}", endpoints.join(" and ")),
1705            };
1706            frink_api::Capability::available(
1707                frink_api::health::capability::REAL_WEIGHTS,
1708                format!(
1709                    "Serving the real embedding checkpoint '{}'. This is an ENCODER, \
1710                     {served_by}; generation endpoints refuse it.",
1711                    active.name(),
1712                ),
1713            )
1714        }
1715        Some(active) => frink_api::Capability::available(
1716            frink_api::health::capability::REAL_WEIGHTS,
1717            format!("Serving the real checkpoint '{}'.", active.name()),
1718        ),
1719    });
1720    capabilities.push(if active.as_ref().is_some_and(|a| a.batcher.is_some()) {
1721        frink_api::Capability::available(
1722            frink_api::health::capability::CONTINUOUS_BATCHING,
1723            if state.continuous_batching_enabled && continuous_batching_env().is_none() {
1724                "On by default on Metal. Concurrent requests share one batched decode worker."
1725            } else {
1726                "Concurrent requests share one batched decode step."
1727            },
1728        )
1729    } else if state.metal_private_decode_gate.is_some() {
1730        frink_api::Capability::unavailable(
1731            frink_api::health::capability::CONTINUOUS_BATCHING,
1732            frink_api::health::reason::DISABLED,
1733            "Off; private Metal decodes serialize (one at a time). Set FRINK_CONTINUOUS_BATCHING=1 or --cont-batching for parallel serving.",
1734        )
1735    } else {
1736        frink_api::Capability::unavailable(
1737            frink_api::health::capability::CONTINUOUS_BATCHING,
1738            frink_api::health::reason::DISABLED,
1739            "Off; set FRINK_CONTINUOUS_BATCHING=1 (incompatible with a KV pool or prefix cache).",
1740        )
1741    });
1742
1743    let last_request_ms = state
1744        .last_request_ms
1745        .load(std::sync::atomic::Ordering::Relaxed);
1746    let uptime = state.started_at.elapsed();
1747    // Readiness is "can this server generate", and with nothing loaded
1748    // it cannot -- so `unavailable` (503) wins over whatever the backend
1749    // probe concluded. Phase 1 defined this state but nothing could
1750    // reach it, because the process only bound the port after a
1751    // successful load; `/admin/models/unload` makes it reachable, and a
1752    // 200 `ready` here would tell a supervisor to send traffic that is
1753    // guaranteed to 503.
1754    let health_state = if active.is_none() {
1755        frink_api::HealthState::Unavailable
1756    } else {
1757        snapshot.state
1758    };
1759    let body = frink_api::HealthResponse {
1760        state: health_state,
1761        reason: match health_state {
1762            frink_api::HealthState::Ready => None,
1763            frink_api::HealthState::Unavailable => {
1764                Some(frink_api::health::reason::MODEL_NOT_LOADED.to_string())
1765            }
1766            frink_api::HealthState::Detecting => {
1767                Some(frink_api::health::reason::DETECTING.to_string())
1768            }
1769        },
1770        detail: match health_state {
1771            frink_api::HealthState::Ready => None,
1772            frink_api::HealthState::Unavailable => Some(
1773                "No model is loaded. POST /admin/models/load with an id from GET /admin/models."
1774                    .to_string(),
1775            ),
1776            frink_api::HealthState::Detecting => {
1777                Some("Probing available compute backends.".to_string())
1778            }
1779        },
1780        model: active
1781            .as_deref()
1782            .map(|active| frink_api::health::ModelSummary {
1783                id: active.name().to_string(),
1784                tokenizer: active.tokenizer_kind().to_string(),
1785                synthetic_weights: active.is_synthetic(),
1786            }),
1787        capabilities,
1788        version: env!("CARGO_PKG_VERSION").to_string(),
1789        pid: std::process::id(),
1790        uptime_seconds: uptime.as_secs_f64(),
1791        server_time_unix_ms: std::time::SystemTime::now()
1792            .duration_since(std::time::UNIX_EPOCH)
1793            .map(|d| d.as_millis().min(u64::MAX as u128) as u64)
1794            .unwrap_or(0),
1795        last_request_age_seconds: (last_request_ms > 0)
1796            .then(|| uptime.as_secs_f64() - (last_request_ms as f64 / 1000.0))
1797            .map(|age| age.max(0.0)),
1798    };
1799
1800    let status =
1801        StatusCode::from_u16(body.state.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1802    (status, Json(body)).into_response()
1803}
1804
1805async fn list_models(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1806    // OpenAI's `/v1/models` lists what can be *used* right now, which
1807    // after an unload is nothing. The inventory of what is on disk is a
1808    // different question and lives at `/admin/models`.
1809    let Some(active) = state.active() else {
1810        return Json(serde_json::json!({ "object": "list", "data": [] }));
1811    };
1812    let mut model_entry = serde_json::json!({
1813        "id": active.name(),
1814        "object": "model",
1815        "frink_synthetic_weights": active.is_synthetic(),
1816        "frink_tokenizer": active.tokenizer_kind(),
1817    });
1818    // An encoder is listed -- it IS what is loaded, and a client asking
1819    // "what can I use" must be told about it -- but it is listed as
1820    // what it is. `frink_endpoints` is the machine-readable half of
1821    // the 501 a generation route would answer with: a client that reads
1822    // it never has to send the request to find out.
1823    if let Some(encoder) = active.encoder() {
1824        model_entry["frink_model_kind"] = serde_json::json!("embedding");
1825        model_entry["frink_endpoints"] = serde_json::json!(encoder_endpoints(encoder));
1826        model_entry["frink_n_embd"] = serde_json::json!(encoder.n_embd());
1827        model_entry["frink_pooling"] = serde_json::json!(encoder.pooling_type().name());
1828        model_entry["frink_context_length"] = serde_json::json!(encoder.n_ctx_train());
1829    }
1830    // Which reasoning gears this checkpoint really has, learned by
1831    // probing its own template at load. A checkpoint that says nothing
1832    // about thinking carries NEITHER field rather than an empty list:
1833    // an empty list reads as "asked, and it has no gears", which is a
1834    // different claim from "this is not a reasoning model". An encoder
1835    // is not asked at all, for the same reason -- it has no template to
1836    // probe, and `ThinkGears::default()` would be an invented answer.
1837    if let Some(model) = active.generative_opt() {
1838        let parser_configured = active.reasoning_format().is_some();
1839        let gears = model.chat_template().think_gears(parser_configured);
1840        if !gears.is_empty() {
1841            model_entry["supported_reasoning_efforts"] = serde_json::json!(gears.supported);
1842            if let Some(default) = &gears.default {
1843                model_entry["default_reasoning_effort"] = serde_json::json!(default);
1844            }
1845            // What to SEND for each gear, so a client selects one without
1846            // knowing that "off" is two booleans and "high" is a string.
1847            model_entry["reasoning_effort_kwargs"] = serde_json::json!(gears.kwargs);
1848        }
1849    }
1850    if let Some(mcp) = &state.mcp {
1851        model_entry["frink_mcp"] = mcp.models_metadata();
1852    }
1853    Json(serde_json::json!({
1854        "object": "list",
1855        "data": [model_entry]
1856    }))
1857}
1858
1859/// `GET /v1/stats`: what is happening *now*.
1860///
1861/// Distinct from `/admin/stats`, which is the historical ring. The two
1862/// throughput figures come from sliding windows, so an idle server
1863/// reports 0 rather than the rate it managed while it was busy -- a
1864/// cumulative average never comes back down, and a status bar showing
1865/// one is reporting the past as the present.
1866///
1867/// Latency is the ring's p95, nearest-rank, so it names a request that
1868/// really took that long. Both it and the mean time-to-first-token are
1869/// `null` rather than `0` when nothing can be said: a non-streamed
1870/// request has no TTFT, and averaging those in as zero would make the
1871/// server look faster the fewer clients stream.
1872async fn serving_stats(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1873    let now_ms = state.uptime().as_millis().min(u64::MAX as u128) as u64;
1874    let mut serving = state.serving.lock().unwrap_or_else(|p| p.into_inner());
1875    let active = state.active();
1876    Json(serde_json::json!({
1877        "model": active.as_ref().map(|a| a.name()),
1878        "state": state
1879            .maintenance
1880            .lock()
1881            .unwrap_or_else(|p| p.into_inner())
1882            .state()
1883            .as_str(),
1884        "uptime_s": state.uptime().as_secs(),
1885        "throughput": {
1886            "decode_tps": (serving.decode_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1887            "prefill_tps": (serving.prefill_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1888        },
1889        "requests": {
1890            "active": state.cancels.live_count(),
1891            "completed": state.stats.recorded_total(),
1892            "p95_ms": state.stats.p95_duration_ms(),
1893            "ttft_mean_ms": state.stats.ttft_mean_ms(),
1894            "prompt_tokens_total": state.stats.tokens_prompt_total(),
1895            "completion_tokens_total": state.stats.tokens_generated_total(),
1896        },
1897        // Served here so a status bar tracking throughput and pressure
1898        // makes ONE request rather than two. Upstream stamps the same
1899        // gauges on every reply of the batch; frink does not, because
1900        // the reply shapes here are OpenAI's and Anthropic's and a pool
1901        // gauge on a `chat.completion` is a field no client asked for.
1902        "pools": cache_admin::pool_gauges(&state),
1903        // What the engine is REALLY using, beside the budget it was
1904        // sized against. `null` when no live figure can be read.
1905        "memory": cache_admin::footprint_json(&state),
1906    }))
1907}
1908
1909#[derive(Deserialize)]
1910struct RequestsQuery {
1911    #[serde(default)]
1912    since: u64,
1913    #[serde(default = "default_requests_limit")]
1914    limit: usize,
1915}
1916
1917fn default_requests_limit() -> usize {
1918    stats::MAX_PAGE
1919}
1920
1921/// `GET /v1/requests?since=&limit=`: an incremental page of the ring.
1922///
1923/// The cursor is all-time, so a poller that keeps up reads each row
1924/// exactly once and never re-reads. `missed` is the honest half: rows
1925/// that existed and were evicted before this poll could see them. A
1926/// client polling slower than the server finishes requests needs to
1927/// know that, rather than have it hidden by a shorter page.
1928async fn recent_requests(
1929    State(state): State<Arc<AppState>>,
1930    axum::extract::Query(q): axum::extract::Query<RequestsQuery>,
1931) -> Json<serde_json::Value> {
1932    let (rows, cursor, missed) = state.stats.page(q.since, q.limit);
1933    Json(serde_json::json!({
1934        "requests": rows,
1935        "next_cursor": cursor,
1936        "missed": missed,
1937        "total": state.stats.recorded_total(),
1938    }))
1939}
1940
1941#[derive(Serialize)]
1942struct CombinedCacheStats {
1943    response_cache: response_cache::CacheStats,
1944    /// `None` when `FRINK_PREFIX_CACHE_ENTRIES` isn't set.
1945    prefix_cache: Option<frink_models::PrefixCacheStats>,
1946}
1947
1948async fn cache_stats(State(state): State<Arc<AppState>>) -> Json<CombinedCacheStats> {
1949    Json(CombinedCacheStats {
1950        response_cache: lock_cache(&state.response_cache).stats(),
1951        prefix_cache: state
1952            .prefix_cache
1953            .as_ref()
1954            .map(|pc| pc.lock().unwrap_or_else(|p| p.into_inner()).stats()),
1955    })
1956}
1957
1958/// Prometheus text-exposition format (`# HELP`/`# TYPE` plus
1959/// `name value` lines), so this endpoint can be scraped directly by a
1960/// Prometheus server or anything compatible with that format without
1961/// frink needing to speak any particular metrics client library.
1962async fn metrics(State(state): State<Arc<AppState>>) -> Response {
1963    use std::sync::atomic::Ordering;
1964
1965    let cache_stats = lock_cache(&state.response_cache).stats();
1966    let active = state.active();
1967    let requests_total = state.requests_total.load(Ordering::Relaxed);
1968    let errors_total = state.request_errors_total.load(Ordering::Relaxed);
1969    let uptime = state.started_at.elapsed().as_secs_f64();
1970
1971    let body = format!(
1972        "# HELP frink_requests_total Total chat completion requests received.\n\
1973         # TYPE frink_requests_total counter\n\
1974         frink_requests_total {requests_total}\n\
1975         # HELP frink_request_errors_total Total chat completion requests that returned an error.\n\
1976         # TYPE frink_request_errors_total counter\n\
1977         frink_request_errors_total {errors_total}\n\
1978         # HELP frink_cache_hits_total Whole-response cache hits.\n\
1979         # TYPE frink_cache_hits_total counter\n\
1980         frink_cache_hits_total {}\n\
1981         # HELP frink_cache_misses_total Whole-response cache misses.\n\
1982         # TYPE frink_cache_misses_total counter\n\
1983         frink_cache_misses_total {}\n\
1984         # HELP frink_cache_entries Current whole-response cache entry count.\n\
1985         # TYPE frink_cache_entries gauge\n\
1986         frink_cache_entries {}\n\
1987         # HELP frink_synthetic_weights 1 if serving synthetic random weights instead of a real checkpoint.\n\
1988         # TYPE frink_synthetic_weights gauge\n\
1989         frink_synthetic_weights {}\n\
1990         # HELP frink_uptime_seconds Seconds since this server process started.\n\
1991         # TYPE frink_uptime_seconds gauge\n\
1992         frink_uptime_seconds {uptime}\n",
1993        cache_stats.hits,
1994        cache_stats.misses,
1995        cache_stats.entries,
1996        // With nothing loaded there are no weights at all, synthetic or
1997        // otherwise; 0 is the reading that keeps the gauge meaning
1998        // "serving noise" rather than "serving nothing".
1999        active
2000            .as_ref()
2001            .map(|a| a.is_synthetic() as u8)
2002            .unwrap_or(0),
2003    );
2004
2005    // Expert-store counters, present only when the model streams
2006    // routed experts through the bounded cache
2007    // (FRINK_EXPERT_CACHE_BYTES).
2008    let body = match active
2009        .as_ref()
2010        .and_then(|a| a.expert_store_stats())
2011    {
2012        Some(es) => format!(
2013            "{body}\
2014             # HELP frink_expert_cache_hits_total Expert-store cache hits.\n\
2015             # TYPE frink_expert_cache_hits_total counter\n\
2016             frink_expert_cache_hits_total {}\n\
2017             # HELP frink_expert_cache_misses_total Expert-store cache misses (source reads).\n\
2018             # TYPE frink_expert_cache_misses_total counter\n\
2019             frink_expert_cache_misses_total {}\n\
2020             # HELP frink_expert_cache_evictions_total Expert-store LRU evictions.\n\
2021             # TYPE frink_expert_cache_evictions_total counter\n\
2022             frink_expert_cache_evictions_total {}\n\
2023             # HELP frink_expert_cache_pass_throughs_total Acquires served uncached (entry could not fit the budget).\n\
2024             # TYPE frink_expert_cache_pass_throughs_total counter\n\
2025             frink_expert_cache_pass_throughs_total {}\n\
2026             # HELP frink_expert_cache_bytes_read_total Bytes read from the checkpoint for expert misses.\n\
2027             # TYPE frink_expert_cache_bytes_read_total counter\n\
2028             frink_expert_cache_bytes_read_total {}\n\
2029             # HELP frink_expert_cache_resident_bytes Current expert-cache footprint in bytes.\n\
2030             # TYPE frink_expert_cache_resident_bytes gauge\n\
2031             frink_expert_cache_resident_bytes {}\n",
2032            es.hits, es.misses, es.evictions, es.pass_throughs, es.bytes_read, es.resident_bytes,
2033        ),
2034        None => body,
2035    };
2036
2037    // Scheduler counters, present only under continuous batching
2038    // (FRINK_CONTINUOUS_BATCHING=1). `prefill_chunks` next to
2039    // `prefill_tokens` is what makes chunked prefill observable: their
2040    // ratio is the effective chunk size the worker actually ran.
2041    let body = match active.as_ref().and_then(|a| a.batcher.as_ref()) {
2042        Some(batcher) => {
2043            let sched = batcher.stats();
2044            format!(
2045                "{body}\
2046                 # HELP frink_prefill_chunks_total Bounded prefill chunks the batch scheduler has run.\n\
2047                 # TYPE frink_prefill_chunks_total counter\n\
2048                 frink_prefill_chunks_total {}\n\
2049                 # HELP frink_prefill_tokens_total Prompt tokens run through chunked prefill.\n\
2050                 # TYPE frink_prefill_tokens_total counter\n\
2051                 frink_prefill_tokens_total {}\n\
2052                 # HELP frink_decode_steps_total Batched decode steps the batch scheduler has run.\n\
2053                 # TYPE frink_decode_steps_total counter\n\
2054                 frink_decode_steps_total {}\n\
2055                 # HELP frink_scheduler_queue_depth Requests waiting for admission to the batch scheduler.\n\
2056                 # TYPE frink_scheduler_queue_depth gauge\n\
2057                 frink_scheduler_queue_depth {}\n\
2058                 # HELP frink_scheduler_queue_rejected_total Requests refused with 503 because the admission queue was full.\n\
2059                 # TYPE frink_scheduler_queue_rejected_total counter\n\
2060                 frink_scheduler_queue_rejected_total {}\n\
2061                 # HELP frink_kv_blocks_total KV blocks in the scheduler's admission budget (0 when unconfigured).\n\
2062                 # TYPE frink_kv_blocks_total gauge\n\
2063                 frink_kv_blocks_total {}\n\
2064                 # HELP frink_kv_blocks_free KV blocks not reserved by an in-flight request.\n\
2065                 # TYPE frink_kv_blocks_free gauge\n\
2066                 frink_kv_blocks_free {}\n\
2067                 # HELP frink_kv_block_size Token positions per KV block.\n\
2068                 # TYPE frink_kv_block_size gauge\n\
2069                 frink_kv_block_size {}\n\
2070                 # HELP frink_kv_rejected_too_large_total Requests refused with 400 because they exceed the whole KV block budget.\n\
2071                 # TYPE frink_kv_rejected_too_large_total counter\n\
2072                 frink_kv_rejected_too_large_total {}\n\
2073                 # HELP frink_kv_rejected_context_length_total Requests refused with 400 for exceeding the per-request context ceiling.\n\
2074                 # TYPE frink_kv_rejected_context_length_total counter\n\
2075                 frink_kv_rejected_context_length_total {}\n\
2076                 # HELP frink_scheduler_aborted_total Requests the batch scheduler stopped because they were cancelled.\n\
2077                 # TYPE frink_scheduler_aborted_total counter\n\
2078                 frink_scheduler_aborted_total {}\n\
2079                 # HELP frink_scheduler_max_seqs Cap on in-flight sequences (-np / FRINK_CB_MAX_SEQS); 0 when unlimited.\n\
2080                 # TYPE frink_scheduler_max_seqs gauge\n\
2081                 frink_scheduler_max_seqs {}\n\
2082                 # HELP frink_scheduler_prefill_chunk Prompt tokens per prefill chunk (-b / -ub / FRINK_CB_PREFILL_CHUNK).\n\
2083                 # TYPE frink_scheduler_prefill_chunk gauge\n\
2084                 frink_scheduler_prefill_chunk {}\n",
2085                sched.prefill_chunks,
2086                sched.prefill_tokens,
2087                sched.decode_steps,
2088                sched.queue_depth,
2089                sched.queue_rejected,
2090                sched.kv_blocks_total,
2091                sched.kv_blocks_free,
2092                sched.kv_block_size,
2093                sched.kv_rejected_too_large,
2094                sched.kv_rejected_context_length,
2095                sched.aborted,
2096                sched.max_seqs,
2097                sched.prefill_chunk,
2098            )
2099        }
2100        None => body,
2101    };
2102
2103    (
2104        [(
2105            axum::http::header::CONTENT_TYPE,
2106            "text/plain; version=0.0.4",
2107        )],
2108        body,
2109    )
2110        .into_response()
2111}
2112
2113pub(crate) type ApiError = (StatusCode, Json<serde_json::Value>);
2114
2115/// A field the server understands but this value of which it cannot
2116/// serve. Distinct from [`unsupported_feature`] (501, "frink does not
2117/// implement this") -- a 400 says the request itself is wrong, which is
2118/// the difference between a client retrying elsewhere and a client
2119/// fixing its own body.
2120pub(crate) fn invalid_request(message: &str, param: &str) -> ApiError {
2121    (
2122        StatusCode::BAD_REQUEST,
2123        Json(serde_json::json!({"error": {
2124            "message": message,
2125            "type": "invalid_request_error",
2126            "param": param,
2127            "code": null,
2128        }})),
2129    )
2130}
2131
2132pub(crate) fn unsupported_feature(message: &str) -> ApiError {
2133    (
2134        StatusCode::NOT_IMPLEMENTED,
2135        Json(serde_json::json!({"error": {"message": message, "type": "unsupported"}})),
2136    )
2137}
2138
2139pub(crate) fn decode_error_response(e: generate::DecodeError) -> ApiError {
2140    let status = match e {
2141        generate::DecodeError::TokenOutOfVocab { .. } => StatusCode::BAD_REQUEST,
2142        // Well-formed, and this deployment cannot serve it: 501, the
2143        // same answer `crate::unimplemented_fields` gives a field this
2144        // server does not implement.
2145        generate::DecodeError::Unsupported(_) => StatusCode::NOT_IMPLEMENTED,
2146        // The request is bigger than the server can ever serve. That
2147        // is a property of the request, so it is the client's 400 --
2148        // answering 503 would send it into a retry loop that cannot
2149        // succeed.
2150        generate::DecodeError::KvBudgetExceeded { .. } => StatusCode::BAD_REQUEST,
2151        // Not the client's fault, and true of the exact same request a
2152        // moment later once capacity frees up -- 503, not 400. The
2153        // `Retry-After` header these need is stamped centrally by
2154        // `limits::retry_after`; see that function for why it lives in a
2155        // layer rather than here.
2156        generate::DecodeError::KvPoolExhausted | generate::DecodeError::QueueFull { .. } => {
2157            StatusCode::SERVICE_UNAVAILABLE
2158        }
2159        // The caller's grammar against this model's vocabulary, and
2160        // nothing about the server's load: the same body fails the same
2161        // way on an idle box, so 400 rather than 503.
2162        generate::DecodeError::GrammarConstraint { .. } => StatusCode::BAD_REQUEST,
2163        // Meant to be unreachable -- the route refuses the family with
2164        // a 501 before rendering -- and a 500 when it is not, because
2165        // then it is this server's decode path that skipped a seam.
2166        generate::DecodeError::ReasoningBudget { .. } => StatusCode::INTERNAL_SERVER_ERROR,
2167    };
2168    tracing::warn!("decode error: {e}");
2169    let mut body = serde_json::json!({"error": {"message": e.to_string()}});
2170    // A refusal against a ceiling names the ceiling and both sides of
2171    // the arithmetic. "Out of memory" (or a bare 400) tells a caller
2172    // that something did not fit; it does not tell them whether to
2173    // shorten the prompt or to run a bigger box, and those are the only
2174    // two actions available.
2175    if let generate::DecodeError::KvBudgetExceeded {
2176        binding,
2177        estimated_bytes,
2178        limit_bytes,
2179        positions,
2180        positions_limit,
2181        ..
2182    } = &e
2183    {
2184        body["error"]["type"] = serde_json::json!("invalid_request_error");
2185        body["error"]["code"] = serde_json::json!(binding);
2186        body["error"]["binding"] = serde_json::json!(binding);
2187        body["error"]["estimated_bytes"] = serde_json::json!(estimated_bytes);
2188        body["error"]["limit_bytes"] = serde_json::json!(limit_bytes);
2189        body["error"]["positions"] = serde_json::json!(positions);
2190        body["error"]["positions_limit"] = serde_json::json!(positions_limit);
2191    }
2192    // The header carries the same hint (stamped by `limits::retry_after`);
2193    // repeating it in the body is for clients that read JSON and never
2194    // look at headers, which is most of them.
2195    if let Some(secs) = e.retry_after_secs() {
2196        body["error"]["retry_after_seconds"] = serde_json::json!(secs);
2197    }
2198    (status, Json(body))
2199}
2200
2201pub(crate) fn join_error_response(e: tokio::task::JoinError) -> ApiError {
2202    tracing::error!("generation task panicked: {e}");
2203    (
2204        StatusCode::INTERNAL_SERVER_ERROR,
2205        Json(serde_json::json!({"error": {"message": "internal error during generation"}})),
2206    )
2207}
2208
2209/// Runs generation for `params` against `model`, calling `emit` for each
2210/// decoded text chunk. Returns finish reason, usage, and the concatenated
2211/// text (for sessions / tool-call detection). Pure CPU-bound work with
2212/// no I/O and no shared lock: safe to run on `spawn_blocking`.
2213#[allow(clippy::too_many_arguments)] // one clear parameter per concern:
2214                                     // model + prompt + params, then the three optional shared
2215                                     // facilities (KV pool, prefix cache, batcher), the context
2216                                     // ceiling, and the sink. Bundling them would only move the
2217                                     // same list behind a struct at two call sites.
2218fn run_generation_emit(
2219    model: &Model,
2220    prompt: &str,
2221    params: &GenerationParams,
2222    kv_pool: Option<&generate::KvPoolConfig>,
2223    paged_kv: Option<&generate::PagedKvConfig>,
2224    prefix_cache: Option<&Mutex<PrefixCache>>,
2225    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2226    ceiling: Option<&budget::ContextCeiling>,
2227    metal_private_decode_gate: Option<&std::sync::Mutex<()>>,
2228    mut emit: impl FnMut(&str),
2229    // One entry per choice. `n` is 1 for every streaming request --
2230    // `n` > 1 with `stream` is refused at the route, because emitting
2231    // choice 0 entirely and then choice 1 is not what a client reading
2232    // `choices[].index` expects, and round-robin needs a steppable
2233    // sampler (`docs/plans/several-completions-per-request.md`).
2234) -> Result<(Vec<generate::GeneratedChoice>, generate::Usage), generate::DecodeError> {
2235    let synthetic = model.is_synthetic();
2236    // Held for the whole generation: a `POST /lora-adapters`, or a
2237    // request whose `lora` field overrides the scales, waits for this
2238    // one to finish rather than changing the weights under it. See
2239    // `crate::lora`.
2240    let _lora_lease = lora::lease(model, params.lora.as_deref());
2241    let mut chunks: Vec<Vec<String>> = vec![Vec::new(); params.n.max(1)];
2242    // Layer 1 of the stop machinery is resolved exactly here, because
2243    // this is the one place that has both the request's stop strings
2244    // and the model's tokenizer. Both the batched and the private
2245    // decode paths below read the result off the params, so there is
2246    // one answer rather than two that can drift.
2247    let params = &{
2248        let mut resolved = params.clone();
2249        resolved.stop_token_ids = crate::stop::resolve_stop_tokens(&resolved.stop, |text| {
2250            model.encode(text, SpecialTokens::Parse)
2251        });
2252        // The reasoning budget's markers, for the same reason and at
2253        // the same seam: `<think>` is a token id only to this model,
2254        // and whether the prompt already opened the block is a fact
2255        // about the rendered prompt, which this is the last place to
2256        // hold beside the tokenizer.
2257        resolved.reasoning_budget = resolved
2258            .reasoning_budget
2259            .armed(resolved.reasoning, prompt, |text| {
2260                model.encode(text, SpecialTokens::Parse)
2261            })
2262            .map_err(|detail| generate::DecodeError::ReasoningBudget { detail })?;
2263        resolved
2264    };
2265    let used_batcher = matches!((model, continuous_batcher), (Model::Gguf(_), Some(_)));
2266    let _metal_private_guard =
2267        acquire_metal_private_decode_gate(metal_private_decode_gate, used_batcher);
2268    let (finishes, usage) = match model {
2269        Model::Gguf(m) => {
2270            if let Some(batcher) = continuous_batcher {
2271                let mut tokens = m.tokenizer.encode(prompt, SpecialTokens::Parse);
2272                frink_models::tokenizer::prepend_bos(&mut tokens, m.bos_id);
2273                let (finish, _generated_ids, text, usage) = if synthetic {
2274                    batcher.generate(tokens, params.clone(), m.stop_tokens.clone())?
2275                } else {
2276                    batcher.generate_streaming(
2277                        tokens,
2278                        params.clone(),
2279                        m.stop_tokens.clone(),
2280                        Some(|chunk: &str| {
2281                            if !chunk.is_empty() {
2282                                chunks[0].push(chunk.to_string());
2283                                emit(chunk);
2284                            }
2285                        }),
2286                    )?
2287                };
2288                if !text.is_empty() && chunks[0].is_empty() {
2289                    chunks[0].push(text);
2290                }
2291                // One choice: the batch scheduler serves `n = 1` only,
2292                // and `crate::unimplemented_fields` refuses the rest on
2293                // the wire.
2294                // The batch scheduler serves one choice and publishes
2295                // no distributions; `wants_logprobs` is refused for a
2296                // batched request at the route.
2297                (vec![(finish, Vec::new())], usage)
2298            } else {
2299                generate::generate(
2300                    &m.decoder,
2301                    m.tokenizer.as_ref(),
2302                    &m.stop_tokens,
2303                    m.bos_id,
2304                    prompt,
2305                    params,
2306                    kv_pool,
2307                    paged_kv,
2308                    prefix_cache,
2309                    ceiling,
2310                    |choice, chunk| {
2311                        chunks[choice].push(chunk.to_string());
2312                        // Only choice 0 streams, and only a request
2313                        // with one choice streams at all: `n` > 1 with
2314                        // `stream` is refused at the route.
2315                        if !synthetic && choice == 0 {
2316                            emit(chunk);
2317                        }
2318                    },
2319                )?
2320            }
2321        }
2322        Model::Kimi(m) => generate::generate_engine(
2323            &m.engine,
2324            &m.tokenizer,
2325            &m.stop_tokens,
2326            None,
2327            prompt,
2328            params,
2329            |chunk| {
2330                chunks[0].push(chunk.to_string());
2331                if !synthetic {
2332                    emit(chunk);
2333                }
2334            },
2335        )?,
2336        Model::Mla(m) => generate::generate_engine(
2337            &m.engine,
2338            &m.tokenizer,
2339            &m.stop_tokens,
2340            m.bos_id,
2341            prompt,
2342            params,
2343            |chunk| {
2344                chunks[0].push(chunk.to_string());
2345                if !synthetic {
2346                    emit(chunk);
2347                }
2348            },
2349        )?,
2350        Model::Gemma4(m) => generate::generate_engine(
2351            &m.engine,
2352            &m.tokenizer,
2353            &m.stop_tokens,
2354            m.bos_id,
2355            prompt,
2356            params,
2357            |chunk| {
2358                chunks[0].push(chunk.to_string());
2359                if !synthetic {
2360                    emit(chunk);
2361                }
2362            },
2363        )?,
2364        Model::Glm52(m) => generate::generate_engine(
2365            &m.engine,
2366            &m.tokenizer,
2367            &m.stop_tokens,
2368            m.bos_id,
2369            prompt,
2370            params,
2371            |chunk| {
2372                chunks[0].push(chunk.to_string());
2373                if !synthetic {
2374                    emit(chunk);
2375                }
2376            },
2377        )?,
2378    };
2379
2380    let mut full = chunks[0].concat();
2381    if synthetic {
2382        full = format!(
2383            "[frink synthetic-weight demo: no real checkpoint loaded -- set FRINK_MODEL_PATH \
2384             to serve a real model. Decoded ids -> {full:?}]"
2385        );
2386        emit(&full);
2387    } else if used_batcher && !full.is_empty() && chunks[0].is_empty() {
2388        emit(&full);
2389    }
2390
2391    // One `(finish_reason, text)` per choice, choice 0 first. Zipped
2392    // rather than indexed so a mismatch between the two lists is a
2393    // short result rather than a panic -- and the assert says the two
2394    // must agree, because a choice with no finish reason is a bug and
2395    // not a shape.
2396    debug_assert_eq!(finishes.len(), chunks.len(), "one finish reason per choice");
2397    let mut out: Vec<generate::GeneratedChoice> = finishes
2398        .into_iter()
2399        .zip(chunks.into_iter().map(|c| c.concat()))
2400        .map(|((finish, logprobs), text)| generate::GeneratedChoice {
2401            finish,
2402            text,
2403            logprobs,
2404        })
2405        .collect();
2406    if let Some(first) = out.first_mut() {
2407        // The synthetic demo REPLACES the text with a banner, so the
2408        // token pieces the distributions were collected for no longer
2409        // concatenate to what is returned, and `text_offset` would
2410        // index a string that does not contain them. Dropped together
2411        // with the substitution, at the one site that makes it: an
2412        // offset into text the caller did not get is worse than no
2413        // offset.
2414        if synthetic {
2415            first.logprobs.clear();
2416        }
2417        first.text = full;
2418    }
2419    Ok((out, usage))
2420}
2421
2422/// Collecting wrapper around [`run_generation_emit`] for non-streaming
2423/// paths and tests.
2424#[allow(clippy::too_many_arguments)] // mirrors `run_generation_emit`
2425                                     // exactly, minus the sink; see its note.
2426pub(crate) fn run_generation(
2427    model: &Model,
2428    prompt: &str,
2429    params: &GenerationParams,
2430    kv_pool: Option<&generate::KvPoolConfig>,
2431    paged_kv: Option<&generate::PagedKvConfig>,
2432    prefix_cache: Option<&Mutex<PrefixCache>>,
2433    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2434    ceiling: Option<&budget::ContextCeiling>,
2435    metal_private_decode_gate: Option<&std::sync::Mutex<()>>,
2436    // One `(finish_reason, text)` per choice, choice 0 first. See
2437    // `run_generation_emit`.
2438) -> Result<(Vec<generate::GeneratedChoice>, generate::Usage), generate::DecodeError> {
2439    run_generation_emit(
2440        model,
2441        prompt,
2442        params,
2443        kv_pool,
2444        paged_kv,
2445        prefix_cache,
2446        continuous_batcher,
2447        ceiling,
2448        metal_private_decode_gate,
2449        |_| {},
2450    )
2451}
2452
2453/// Render a conversation into the prompt the served checkpoint expects.
2454///
2455/// Who describes the tools depends on the template: one that reads
2456/// `tools` is handed them structurally and owns the whole grammar, and
2457/// one that does not gets [`tool_preamble`] as an extra leading system
2458/// turn -- this server's original answer, and still the only one
2459/// available for a checkpoint whose template never mentions tools.
2460///
2461/// `extra` is the request's already-sanitized `chat_template_kwargs`
2462/// (see [`resolve_template_kwargs`]).
2463pub(crate) fn prompt_from_messages(
2464    messages: &[ChatMessage],
2465    template: &chat_template::PromptTemplate,
2466    tools: &[ToolDef],
2467    extra: serde_json::Map<String, serde_json::Value>,
2468) -> Result<String, ApiError> {
2469    let rendered = if tools.is_empty() || template.handles_tools() {
2470        template.render(messages, tools, extra)
2471    } else {
2472        let mut with_preamble = Vec::with_capacity(messages.len() + 1);
2473        with_preamble.push(ChatMessage {
2474            role: "system".to_string(),
2475            content: Some(MessageContent::Text(tool_preamble(tools))),
2476            tool_calls: None,
2477            tool_call_id: None,
2478            reasoning_content: None,
2479        });
2480        with_preamble.extend_from_slice(messages);
2481        template.render(&with_preamble, &[], extra)
2482    };
2483    rendered.map_err(template_error_response)
2484}
2485
2486/// A template that will not render is a request failure, never a
2487/// fallback to a guessed one: serving a checkpoint framing it has never
2488/// seen is the exact bug `chat_template` exists to delete, so the
2489/// compiler's own message goes back to the caller instead.
2490fn template_error_response(err: frink_models::chat_template::TemplateError) -> ApiError {
2491    (
2492        StatusCode::BAD_REQUEST,
2493        Json(serde_json::json!({
2494            "error": {
2495                "message": format!("chat template failed to render: {err}"),
2496                "type": "invalid_request_error",
2497                "param": "messages",
2498                "code": null,
2499            }
2500        })),
2501    )
2502}
2503
2504/// Real, disclosed approach for tool-calling without grammar-
2505/// constrained decoding (which doesn't exist in this server):
2506/// describe each tool in plain text and ask the
2507/// model to wrap a call in a literal `<tool_call>{...}</tool_call>`
2508/// marker, then reuse the existing stop-sequence machinery (see
2509/// `ChatCompletionRequest::effective_stop_sequences`) to end
2510/// generation right after it, and parse the captured text for that
2511/// marker afterward (`output::parse_output`, which also accepts the
2512/// format the served checkpoint's own family emits). This is
2513/// stop-bounded,
2514/// prompt-engineered JSON extraction, not enforced-valid-JSON output --
2515/// a real limitation, not overclaimed.
2516fn tool_preamble(tools: &[ToolDef]) -> String {
2517    let mut out = String::from(
2518        "You can call tools to help answer the user. To call a tool, respond with \
2519         EXACTLY one line in this format and nothing else:\n\
2520         <tool_call>{\"name\": \"<tool name>\", \"arguments\": {<arguments as a JSON \
2521         object matching that tool's parameters>}}</tool_call>\n\n\
2522         Available tools:\n",
2523    );
2524    for t in tools {
2525        out.push_str(&format!(
2526            "- {}: {}\n  parameters (JSON schema): {}\n",
2527            t.function.name,
2528            t.function.description.as_deref().unwrap_or(""),
2529            t.function
2530                .parameters
2531                .as_ref()
2532                .map(|v| v.to_string())
2533                .unwrap_or_else(|| "{}".to_string()),
2534        ));
2535    }
2536    out
2537}
2538
2539/// Fold one batch of parser events into the text to stream and the
2540/// tool-call deltas to stream beside it.
2541///
2542/// `opened` counts calls that have gone out, which is both the wire
2543/// `index` and how the terminal chunk knows whether this generation
2544/// ended in a tool call. `CallEnd` deliberately emits nothing: every
2545/// byte of the arguments has already gone out as a fragment, and
2546/// repeating them would make a client that concatenates deltas produce
2547/// the arguments twice.
2548fn tool_call_deltas(
2549    events: Vec<crate::policy::parser::ToolCallEvent>,
2550    opened: &std::cell::Cell<usize>,
2551) -> (String, Vec<ToolCallDelta>) {
2552    let mut text = String::new();
2553    let mut deltas = Vec::new();
2554    for event in events {
2555        match event {
2556            crate::policy::parser::ToolCallEvent::Text(chunk) => text.push_str(&chunk),
2557            crate::policy::parser::ToolCallEvent::CallStart { index, name } => {
2558                opened.set(opened.get().max(index + 1));
2559                deltas.push(ToolCallDelta::opening(index, name));
2560            }
2561            crate::policy::parser::ToolCallEvent::CallArguments { index, fragment } => {
2562                if !fragment.is_empty() {
2563                    deltas.push(ToolCallDelta::arguments(index, fragment));
2564                }
2565            }
2566            crate::policy::parser::ToolCallEvent::CallEnd { .. } => {}
2567        }
2568    }
2569    (text, deltas)
2570}
2571
2572/// Builds the final response message + finish reason from raw
2573/// generated text.
2574///
2575/// Three things come out of the text: a reasoning block, when the
2576/// served checkpoint's family emits one; every tool call it made, in
2577/// whichever format it used; and whatever prose is left. `base_finish`
2578/// is promoted to `"tool_calls"` only when a call was actually found --
2579/// a model can answer in plain text despite tools being offered, and
2580/// that must fall through to an ordinary text response rather than an
2581/// error.
2582fn build_response_message(
2583    text: String,
2584    tools: &[ToolDef],
2585    posture: output::OutputPosture,
2586    base_finish: &'static str,
2587) -> (ChatCompletionResponseMessage, &'static str) {
2588    let parsed = output::parse_output(&text, tools, posture);
2589    let calls: Vec<ToolCallOut> = parsed
2590        .calls
2591        .into_iter()
2592        .enumerate()
2593        .map(|(index, call)| ToolCallOut {
2594            id: format!("call_{index}"),
2595            kind: "function",
2596            function: ToolCallFunctionOut {
2597                name: call.name,
2598                arguments: call.arguments,
2599            },
2600        })
2601        .collect();
2602    if !calls.is_empty() {
2603        return (
2604            ChatCompletionResponseMessage {
2605                role: "assistant",
2606                content: None,
2607                reasoning_content: parsed.reasoning,
2608                tool_calls: Some(calls),
2609            },
2610            "tool_calls",
2611        );
2612    }
2613    (
2614        ChatCompletionResponseMessage {
2615            role: "assistant",
2616            content: Some(parsed.content),
2617            reasoning_content: parsed.reasoning,
2618            tool_calls: None,
2619        },
2620        base_finish,
2621    )
2622}
2623
2624/// Resolves the full message history a prompt should be rendered
2625/// from: `req.messages` verbatim when no session is in play, or (see
2626/// `session` module) `req.messages` appended to `session_id`'s stored
2627/// history, returning the accumulated whole.
2628fn resolve_history(state: &AppState, req: &ChatCompletionRequest) -> Vec<ChatMessage> {
2629    let mut history = match &req.session_id {
2630        Some(id) => state.sessions.extend_and_get(id, &req.messages),
2631        None => req.messages.clone(),
2632    };
2633    if req.json_object_mode() {
2634        inject_json_object_system_hint(&mut history);
2635    }
2636    history
2637}
2638
2639fn inject_json_object_system_hint(messages: &mut Vec<ChatMessage>) {
2640    const HINT: &str =
2641        "You must respond with valid JSON only (a single JSON object, no markdown fences).";
2642    if let Some(sys) = messages.iter_mut().find(|m| m.role == "system") {
2643        match &mut sys.content {
2644            Some(MessageContent::Text(s)) if !s.contains("JSON") => {
2645                s.push_str("\n\n");
2646                s.push_str(HINT);
2647            }
2648            None => {
2649                sys.content = Some(MessageContent::Text(HINT.to_string()));
2650            }
2651            _ => {}
2652        }
2653    } else {
2654        messages.insert(
2655            0,
2656            ChatMessage {
2657                role: "system".to_string(),
2658                content: Some(MessageContent::Text(HINT.to_string())),
2659                tool_calls: None,
2660                tool_call_id: None,
2661                reasoning_content: None,
2662            },
2663        );
2664    }
2665}
2666
2667async fn chat_completions(
2668    State(state): State<Arc<AppState>>,
2669    headers: axum::http::HeaderMap,
2670    Json(req): Json<ChatCompletionRequest>,
2671) -> Response {
2672    let attribution = attribution::Attribution::from_headers(&headers);
2673    state
2674        .requests_total
2675        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2676    let started = std::time::Instant::now();
2677
2678    // One id per request, assigned before any work starts -- including
2679    // before validation -- so the streaming and non-streaming paths
2680    // agree and a rejected request is still nameable in the monitor.
2681    let request_id = frink_api::next_request_id();
2682    let stream = req.stream.unwrap_or(false);
2683
2684    // The maintenance gate comes before validation: while the cache is
2685    // being resized or the server is draining, the honest answer is
2686    // "not now" whichever fields the body carries, and admitting a
2687    // request into a pool that is being rebuilt under it is worse than
2688    // refusing one that would have 400'd anyway.
2689    let refusal = cache_admin::check_admission(&state)
2690        .err()
2691        .or_else(|| req.validate_supported_fields().err());
2692    if let Some(err) = refusal {
2693        state
2694            .request_errors_total
2695            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2696        let response = err.into_response();
2697        state.record_request(stats::Record {
2698            request_id: &request_id,
2699            route: frink_api::routes::V1_CHAT_COMPLETIONS,
2700            model: state.active_model_name(),
2701            status: response.status().as_u16(),
2702            stream,
2703            duration_ms: started.elapsed().as_millis() as u64,
2704            usage: None,
2705            attribution: &attribution,
2706        });
2707        return response;
2708    }
2709
2710    let response = if stream {
2711        chat_completions_stream(
2712            Arc::clone(&state),
2713            req,
2714            request_id.clone(),
2715            started,
2716            attribution.clone(),
2717        )
2718        .await
2719        .into_response()
2720    } else {
2721        chat_completions_full(
2722            Arc::clone(&state),
2723            req,
2724            request_id.clone(),
2725            started,
2726            attribution.clone(),
2727        )
2728        .await
2729        .into_response()
2730    };
2731
2732    if response.status().is_client_error() || response.status().is_server_error() {
2733        state
2734            .request_errors_total
2735            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2736        // Only failures are recorded here. A success has already
2737        // recorded itself from the path that knows the token counts --
2738        // and, for a stream, that has not even happened yet.
2739        state.record_request(stats::Record {
2740            request_id: &request_id,
2741            route: frink_api::routes::V1_CHAT_COMPLETIONS,
2742            // `None` here is the 503 case and says so: nothing was
2743            // loaded, so nothing served it.
2744            model: state.active_model_name(),
2745            status: response.status().as_u16(),
2746            stream,
2747            duration_ms: started.elapsed().as_millis() as u64,
2748            usage: None,
2749            attribution: &attribution,
2750        });
2751    }
2752    state.mark_request_finished();
2753
2754    response
2755}
2756
2757async fn chat_completions_full(
2758    state: Arc<AppState>,
2759    req: ChatCompletionRequest,
2760    request_id: String,
2761    started: std::time::Instant,
2762    attribution: attribution::Attribution,
2763) -> Result<Json<ChatCompletionResponse>, ApiError> {
2764    let tools_active = req.tools_active();
2765    // Cloned once, up front: this request decodes against exactly this
2766    // model even if `/admin/models/load` swaps a different one in
2767    // halfway through (see `AppState::active`).
2768    let active = state.require_active()?;
2769    let history = resolve_history(&state, &req);
2770    let template = active.generative()?.chat_template();
2771    let kwargs = req.resolve_template_kwargs(&template);
2772    let prompt = req.render_prompt(&history, &template, &req.tools, kwargs, active.name())?;
2773    // Resolved BEFORE the lookup, because the constraint is part of the
2774    // key: a grammar, JSON mode and `ignore_eos` all change the answer
2775    // and none of them changes the prompt, so a cache consulted first
2776    // would answer a constrained request with an unconstrained
2777    // completion (#35). It also means an unparseable grammar is a 400
2778    // for the second caller too, rather than a 200 carrying prose
2779    // generated under no grammar at all.
2780    let mut params =
2781        req.generation_params_for_template(&template, active.name(), active.sampler_model())?;
2782    params.lora = lora::resolve_request(active.generative()?, req.lora.as_deref())?;
2783    let key = req.is_cacheable().then(|| req.cache_key(&prompt, &params));
2784
2785    // Per choice, alongside `completion`: a cache HIT carries none,
2786    // and cannot -- which is safe only because a request that asked
2787    // for logprobs is uncacheable (`is_cacheable`).
2788    let mut generated_logprobs: Vec<crate::sampling_loop::PerTokenProbs> = Vec::new();
2789    // Parsed before the generation so a bad `top_logprobs` is a 400
2790    // rather than a wasted decode.
2791    let n_logprobs = req.n_logprobs()?;
2792    // The same detokenizer `/v1/detokenize` answers with.
2793    let decode_piece = |id: usize| active.decode_any(&[id]);
2794    let (completion, cache_status) = if let Some(cached) = key
2795        .as_ref()
2796        .and_then(|key| lock_cache(&state.response_cache).get(key))
2797    {
2798        tracing::debug!("cache hit for key {}", key.as_ref().unwrap().digest());
2799        (cached, "hit")
2800    } else {
2801        let (choices, usage) = decode_task::buffered(
2802            decode_task::DecodeHandles::take(&state, &active)?,
2803            prompt.clone(),
2804            params,
2805        )
2806        .await?;
2807
2808        // The distributions do not go into the cache (see
2809        // `CachedCompletion`) and do not need to: a request that asked
2810        // for them is uncacheable, so this branch only ever stores
2811        // entries nobody will ask logprobs of.
2812        generated_logprobs = choices.iter().map(|c| c.logprobs.clone()).collect();
2813        let completion = response_cache::CachedCompletion {
2814            choices: choices.into_iter().map(|c| (c.finish, c.text)).collect(),
2815            usage,
2816        };
2817        // A cacheable KEY is not on its own permission to store an
2818        // answer: `cacheable` refuses a generation that did not run to
2819        // its own end, and is the only way to build the value `put`
2820        // takes, so a cancelled partial cannot become the cached answer
2821        // for the next caller (#57).
2822        let cache_status = match key {
2823            // Nothing is cloned unless there is a key to store it
2824            // under: the common path here is a sampled request, which
2825            // has none.
2826            Some(key) => match completion.clone().cacheable() {
2827                Some(cacheable) => {
2828                    tracing::debug!("cache miss for key {}", key.digest());
2829                    lock_cache(&state.response_cache).put(key, cacheable);
2830                    "miss"
2831                }
2832                None => "skip",
2833            },
2834            None => "skip",
2835        };
2836        (completion, cache_status)
2837    };
2838    // Choice 0's text is what a session stores and what JSON mode
2839    // validates: both describe one reply.
2840    let content = completion.first_text().to_string();
2841
2842    if req.json_object_mode() {
2843        json_mode::validate_json_object_output(&content)?;
2844    }
2845
2846    // Stored regardless of cache hit/miss, so a session's history is
2847    // always consistent with what a client would see, whether or not
2848    // this exact prompt happened to be served from cache.
2849    if let Some(id) = &req.session_id {
2850        state.sessions.store_reply(
2851            id,
2852            ChatMessage {
2853                role: "assistant".to_string(),
2854                content: Some(MessageContent::Text(content.clone())),
2855                tool_calls: None,
2856                tool_call_id: None,
2857                reasoning_content: None,
2858            },
2859        );
2860    }
2861
2862    // One `choices[]` entry per generated choice, each parsed for tool
2863    // calls and reasoning in its own right: a tool call in choice 2 is
2864    // a tool call, and reading only choice 0 would return the others
2865    // as raw marker text.
2866    let posture = output::OutputPosture::resolve_full(
2867        active.reasoning_format(),
2868        active.tool_call_format(),
2869        &prompt,
2870    );
2871    let tools: &[_] = if tools_active { &req.tools } else { &[] };
2872    let rendered: Vec<ChatCompletionChoice> = completion
2873        .choices
2874        .into_iter()
2875        .enumerate()
2876        .map(|(index, (finish, text))| {
2877            let (message, finish_reason) =
2878                build_response_message(text, tools, posture, finish.as_str());
2879            ChatCompletionChoice {
2880                index,
2881                message,
2882                finish_reason,
2883                logprobs: n_logprobs.map(|k| {
2884                    crate::logprobs::render_chat(
2885                        generated_logprobs.get(index).unwrap_or(&Vec::new()),
2886                        Some(k),
2887                        &decode_piece,
2888                    )
2889                }),
2890            }
2891        })
2892        .collect();
2893
2894    state.record_request(stats::Record {
2895        request_id: &request_id,
2896        route: frink_api::routes::V1_CHAT_COMPLETIONS,
2897        // The handle this request decoded against, not `req.model`: a
2898        // swap mid-flight does not change which weights answered.
2899        model: Some(active.name().to_string()),
2900        status: 200,
2901        stream: false,
2902        duration_ms: started.elapsed().as_millis() as u64,
2903        usage: Some(&completion.usage),
2904        attribution: &attribution,
2905    });
2906
2907    Ok(Json(ChatCompletionResponse {
2908        id: request_id.clone(),
2909        request_id,
2910        object: "chat.completion",
2911        model: req.model,
2912        choices: rendered,
2913        usage: completion.usage,
2914        frink_cache: cache_status,
2915    }))
2916}
2917
2918async fn chat_completions_stream(
2919    state: Arc<AppState>,
2920    req: ChatCompletionRequest,
2921    request_id: String,
2922    started: std::time::Instant,
2923    attribution: attribution::Attribution,
2924) -> Result<Response, ApiError> {
2925    // Streaming requests are never served from or written to the response cache.
2926    //
2927    // And they serve one choice. Emitting choice 0 to its end and then
2928    // choice 1 is not what a client reading `choices[].index` expects,
2929    // and interleaving them round-robin needs a sampler that can be
2930    // stepped one token at a time per choice
2931    // (`docs/plans/several-completions-per-request.md`). Refused by
2932    // name rather than silently collapsed to one, which is the whole
2933    // argument of `crate::unimplemented_fields`.
2934    if req.several_choices() {
2935        return Err(unsupported_feature(
2936            "`n` > 1 with `stream` is not implemented: the choices would arrive one after \
2937             another rather than interleaved by `choices[].index`. Send the request without \
2938             `stream`, which serves `n` on this route.",
2939        ));
2940    }
2941    let tools_active = req.tools_active();
2942    // See `chat_completions_full`: the handle is taken once and the
2943    // whole stream runs against it, so a mid-stream model swap cannot
2944    // splice two checkpoints into one completion.
2945    let active = state.require_active()?;
2946    let history = resolve_history(&state, &req);
2947    let template = active.generative()?.chat_template();
2948    let kwargs = req.resolve_template_kwargs(&template);
2949    let prompt = req.render_prompt(&history, &template, &req.tools, kwargs, active.name())?;
2950    let model_name = req.model.clone();
2951    let session_id = req.session_id.clone();
2952    let sessions = state.sessions.clone();
2953
2954    let model = Arc::clone(active.generative()?);
2955    let kv_pool = state.kv_pool.clone();
2956    let paged_kv = state.paged_kv.clone();
2957    let prefix_cache = state.prefix_cache.clone();
2958    let batcher = active.batcher.clone();
2959    let ceiling = active.ceiling.clone();
2960    let metal_private_decode_gate = state.metal_private_decode_gate.clone();
2961    let mut params =
2962        req.generation_params_for_template(&template, active.name(), active.sampler_model())?;
2963    params.lora = lora::resolve_request(active.generative()?, req.lora.as_deref())?;
2964    let stats_state = Arc::clone(&state);
2965    // Read now, off the handle this stream will decode against. Read
2966    // later it would name whatever a swap had made current by then.
2967    let served_model = active.name().to_string();
2968    // How to read this stream, fixed before the first token: the family
2969    // from the served checkpoint, and whether the prompt that was
2970    // actually rendered left the model inside a reasoning block.
2971    let posture = output::OutputPosture::resolve_full(
2972        active.reasoning_format(),
2973        active.tool_call_format(),
2974        &prompt,
2975    );
2976    // The offered tools, captured for the terminal parse: the request
2977    // itself does not outlive the closure that consumes it.
2978    let offered_tools: Vec<ToolDef> = if tools_active {
2979        req.tools.clone()
2980    } else {
2981        Vec::new()
2982    };
2983
2984    // Tier two of cancellation: the id is already on the wire, so the
2985    // client can name it. The guard rides with the generation task and
2986    // deregisters however that task ends, panic included -- see the
2987    // `cancel` module.
2988    let (cancel_token, cancel_guard) = state.cancels.register(&request_id);
2989    params.cancel = Some(cancel_token.clone());
2990
2991    // Tool-call detection needs the full stop-bounded text; continuous
2992    // batching returns one string. Both stay buffered. Otherwise each
2993    // decoded chunk is pushed on a channel for overlapped SSE delivery.
2994    // Incremental streaming, including when tools are offered. It used
2995    // to be `!tools_active && ...`: finding a tool call needed the
2996    // whole text. `crate::policy::parser::ToolCallParser` streams prefix-stable
2997    // argument fragments, so that reason is gone, and a coding agent
2998    // now watches an argument arrive instead of waiting for it.
2999    let overlap = true;
3000
3001    // Opt-in replay. Registering a buffer is also what decides whether a
3002    // dropped socket cancels this generation -- see `resume`'s module
3003    // doc for why that is the caller's call and not the server's.
3004    let slot = req
3005        .stream_resumable
3006        .unwrap_or(false)
3007        .then(|| state.streams.register(&request_id));
3008    let emitter = resume::Emitter::new(slot);
3009
3010    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);
3011    // Built here, where the id and model name are still owned by this
3012    // frame: the generation task takes both. Serialized once, because
3013    // it is byte-identical every time it goes out.
3014    let keepalive = sse::keepalive_event(&ChatCompletionChunk {
3015        id: request_id.clone(),
3016        request_id: None,
3017        object: "chat.completion.chunk",
3018        model: model_name.clone(),
3019        choices: vec![ChatCompletionChunkChoice {
3020            index: 0,
3021            delta: ChatCompletionChunkDelta {
3022                role: None,
3023                content: None,
3024                reasoning_content: None,
3025                tool_calls: None,
3026            },
3027            finish_reason: None,
3028        }],
3029        usage: None,
3030    });
3031
3032    tokio::task::spawn_blocking(move || {
3033        // Held for the whole generation; dropping it is what takes the
3034        // id back out of the cancel registry.
3035        let _cancel_guard = cancel_guard;
3036        let tx_chunks = tx.clone();
3037        // The orphan deadline (see `crate::sse`): a client that is
3038        // neither reading nor disconnected must not park this blocking
3039        // thread -- and the model handle and cancel guard it holds --
3040        // for the life of the process.
3041        let orphan_timeout = sse::orphan_timeout_from_env();
3042        let mut first = true;
3043        let head_request_id = request_id.clone();
3044        // The chain-of-thought split, applied as the tokens arrive
3045        // rather than at the end. Without this an overlapped stream --
3046        // which is the default for a reasoning model with no tools --
3047        // would deliver the whole thinking block as `content` and then
3048        // the buffered path would deliver the same request's thinking
3049        // as `reasoning_content`, so the same question would answer
3050        // differently depending on a transport detail. Shared with the
3051        // terminal flush below, which releases whatever the parser is
3052        // still withholding against a marker that never arrived.
3053        let stream_reasoning: Rc<RefCell<Option<crate::policy::parser::ReasoningParser>>> =
3054            Rc::new(RefCell::new(posture.reasoning_parser()));
3055        let emit_reasoning = Rc::clone(&stream_reasoning);
3056        // The tool-call parser, fed whatever the reasoning parser
3057        // classified as content. Absent when the request offered no
3058        // tools, in which case marker-looking text is just text.
3059        let stream_tools: Rc<RefCell<Option<crate::policy::parser::ToolCallParser>>> = Rc::new(
3060            RefCell::new(tools_active.then(|| posture.tool_call_parser(&offered_tools))),
3061        );
3062        let emit_tools = Rc::clone(&stream_tools);
3063        // How many calls have been opened on the wire, so the terminal
3064        // chunk knows whether to say `tool_calls` and does not repeat
3065        // what already went out.
3066        let streamed_calls = Rc::new(std::cell::Cell::new(0usize));
3067        let emit_streamed_calls = Rc::clone(&streamed_calls);
3068        let result = run_generation_emit(
3069            &model,
3070            &prompt,
3071            &params,
3072            kv_pool.as_ref(),
3073            paged_kv.as_ref(),
3074            prefix_cache.as_deref(),
3075            batcher.as_ref(),
3076            ceiling.as_deref(),
3077            metal_private_decode_gate.as_deref(),
3078            |chunk| {
3079                if !overlap || chunk.is_empty() {
3080                    return;
3081                }
3082                let (reasoning, content) = match emit_reasoning.borrow_mut().as_mut() {
3083                    Some(parser) => {
3084                        let delta = parser.push(chunk);
3085                        (delta.reasoning, delta.content)
3086                    }
3087                    None => (String::new(), chunk.to_string()),
3088                };
3089                // Content goes through the tool parser, which holds
3090                // back anything that could still become a marker and
3091                // turns a recognized call into wire deltas.
3092                let (content, tool_calls) = match emit_tools.borrow_mut().as_mut() {
3093                    Some(parser) => {
3094                        let (text, calls) =
3095                            tool_call_deltas(parser.push(&content), &emit_streamed_calls);
3096                        (text, calls)
3097                    }
3098                    None => (content, Vec::new()),
3099                };
3100                // Both parsers withhold partial markers, so a chunk can
3101                // legitimately produce nothing at all this time round.
3102                if reasoning.is_empty() && content.is_empty() && tool_calls.is_empty() {
3103                    return;
3104                }
3105                let role = if first { Some("assistant") } else { None };
3106                let request_id = first.then(|| head_request_id.clone());
3107                first = false;
3108                let payload = ChatCompletionChunk {
3109                    id: head_request_id.clone(),
3110                    request_id,
3111                    object: "chat.completion.chunk",
3112                    model: model_name.clone(),
3113                    choices: vec![ChatCompletionChunkChoice {
3114                        index: 0,
3115                        delta: ChatCompletionChunkDelta {
3116                            role,
3117                            content: (!content.is_empty()).then_some(content),
3118                            reasoning_content: (!reasoning.is_empty()).then_some(reasoning),
3119                            tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3120                        },
3121                        finish_reason: None,
3122                    }],
3123                    usage: None,
3124                };
3125                // Tier one of cancellation. A failed send means the SSE
3126                // receiver is gone -- the browser tab closed, the
3127                // client aborted, the connection dropped -- and until
3128                // this was checked the return value was discarded and
3129                // the decode loop happily generated the remaining
3130                // hundreds of tokens into nothing. Flipping the same
3131                // flag `/v1/cancel` sets means there is one stop path,
3132                // not two.
3133                if let Err(why) =
3134                    sse::send_or_orphan(&tx_chunks, Ok(emitter.event(&payload)), orphan_timeout)
3135                {
3136                    if why == sse::SendFailure::Orphaned {
3137                        tracing::warn!(
3138                            "SSE stream {head_request_id} accepted nothing for the orphan \
3139                             deadline; treating it as abandoned"
3140                        );
3141                    }
3142                    // Two features met here and only one of them may
3143                    // win. The orphan deadline exists to stop work
3144                    // nobody is reading. A resumable stream is exactly
3145                    // the case where a gone receiver must NOT stop the
3146                    // work: the client said it may come back, the
3147                    // buffer is still being filled for it, and
3148                    // cancelling would make every reconnect resume into
3149                    // a truncated answer. So the deadline still detects
3150                    // and logs, and only a non-resumable stream is
3151                    // cancelled by it. `POST /v1/cancel` is the stop
3152                    // path for the resumable ones.
3153                    if !emitter.is_resumable() {
3154                        cancel_token.cancel();
3155                    }
3156                }
3157            },
3158        );
3159
3160        // `first` is still true when nothing was streamed from the emit
3161        // closure (the buffered tool-call/batching path, or an empty
3162        // generation), so the id has not gone out yet. `take()` on the
3163        // way into each payload below guarantees it is announced
3164        // exactly once, on whichever chunk really is first.
3165        let mut pending_request_id = first.then(|| request_id.clone());
3166
3167        match result {
3168            // Streaming, so exactly one choice: `n` > 1 with `stream`
3169            // is refused at the route.
3170            Ok((choices, usage)) => {
3171                let one = choices
3172                    .into_iter()
3173                    .next()
3174                    .expect("a generation produces at least one choice");
3175                let (finish, full_text) = (one.finish, one.text);
3176                if let Some(id) = &session_id {
3177                    sessions.store_reply(
3178                        id,
3179                        ChatMessage {
3180                            role: "assistant".to_string(),
3181                            content: Some(MessageContent::Text(full_text.clone())),
3182                            tool_calls: None,
3183                            tool_call_id: None,
3184                            reasoning_content: None,
3185                        },
3186                    );
3187                }
3188                // Both parsers may still be holding a run that could
3189                // have become a marker and did not. It is ordinary
3190                // output; dropping it would truncate every answer whose
3191                // tail happens to look like the start of a `</think>`
3192                // or a `<tool_call>`.
3193                let mut streamed_finish: Option<&'static str> = None;
3194                if overlap {
3195                    let tail = stream_reasoning
3196                        .borrow_mut()
3197                        .as_mut()
3198                        .map(|parser| parser.flush())
3199                        .unwrap_or_default();
3200                    let (mut content, mut tool_calls) = (tail.content, Vec::new());
3201                    if let Some(parser) = stream_tools.borrow_mut().as_mut() {
3202                        let mut events = parser.push(&content);
3203                        events.extend(parser.finish());
3204                        let (text, calls) = tool_call_deltas(events, &streamed_calls);
3205                        content = text;
3206                        tool_calls = calls;
3207                    }
3208                    if !content.is_empty() || !tail.reasoning.is_empty() || !tool_calls.is_empty() {
3209                        let payload = ChatCompletionChunk {
3210                            id: request_id.clone(),
3211                            request_id: pending_request_id.take(),
3212                            object: "chat.completion.chunk",
3213                            model: model_name.clone(),
3214                            choices: vec![ChatCompletionChunkChoice {
3215                                index: 0,
3216                                delta: ChatCompletionChunkDelta {
3217                                    role: None,
3218                                    content: (!content.is_empty()).then_some(content),
3219                                    reasoning_content: (!tail.reasoning.is_empty())
3220                                        .then_some(tail.reasoning),
3221                                    tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3222                                },
3223                                finish_reason: None,
3224                            }],
3225                            usage: None,
3226                        };
3227                        let _ =
3228                            sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3229                    }
3230                    if streamed_calls.get() > 0 {
3231                        streamed_finish = Some("tool_calls");
3232                    }
3233                } else {
3234                    // The batched path had no incremental stream to
3235                    // ride on, so the whole answer goes out at once.
3236                    let parsed = output::parse_output(&full_text, &offered_tools, posture);
3237                    let tool_calls: Vec<ToolCallDelta> = parsed
3238                        .calls
3239                        .iter()
3240                        .enumerate()
3241                        .map(|(index, call)| {
3242                            ToolCallDelta::whole(index, call.name.clone(), call.arguments.clone())
3243                        })
3244                        .collect();
3245                    if !tool_calls.is_empty() {
3246                        streamed_finish = Some("tool_calls");
3247                    }
3248                    if !tool_calls.is_empty()
3249                        || !parsed.content.is_empty()
3250                        || parsed.reasoning.is_some()
3251                    {
3252                        let payload = ChatCompletionChunk {
3253                            id: request_id.clone(),
3254                            request_id: pending_request_id.take(),
3255                            object: "chat.completion.chunk",
3256                            model: model_name.clone(),
3257                            choices: vec![ChatCompletionChunkChoice {
3258                                index: 0,
3259                                delta: ChatCompletionChunkDelta {
3260                                    role: Some("assistant"),
3261                                    content: (!parsed.content.is_empty() && tool_calls.is_empty())
3262                                        .then(|| parsed.content.clone()),
3263                                    reasoning_content: parsed.reasoning.clone(),
3264                                    tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3265                                },
3266                                finish_reason: None,
3267                            }],
3268                            usage: None,
3269                        };
3270                        let _ =
3271                            sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3272                    }
3273                }
3274                // A truncated generation is `length` even if it managed
3275                // to open a call: the client must not treat a
3276                // half-written call as one it should execute.
3277                let final_finish_reason = match streamed_finish {
3278                    Some(reason) if finish.as_str() != "length" => reason,
3279                    _ => finish.as_str(),
3280                };
3281                let final_payload = ChatCompletionChunk {
3282                    id: request_id.clone(),
3283                    request_id: pending_request_id.take(),
3284                    object: "chat.completion.chunk",
3285                    model: model_name,
3286                    choices: vec![ChatCompletionChunkChoice {
3287                        index: 0,
3288                        delta: ChatCompletionChunkDelta {
3289                            role: None,
3290                            content: None,
3291                            reasoning_content: None,
3292                            tool_calls: None,
3293                        },
3294                        finish_reason: Some(final_finish_reason),
3295                    }],
3296                    usage: Some(usage.clone()),
3297                };
3298                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&final_payload)), orphan_timeout);
3299                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3300                // Recorded here rather than where the handler returned:
3301                // the handler returns as soon as the SSE headers go out,
3302                // which is before a single token exists, so timing it
3303                // there would report every stream as instant.
3304                stats_state.record_request(stats::Record {
3305                    request_id: &request_id,
3306                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3307                    model: Some(served_model.clone()),
3308                    status: 200,
3309                    stream: true,
3310                    duration_ms: started.elapsed().as_millis() as u64,
3311                    usage: Some(&usage),
3312                    attribution: &attribution,
3313                });
3314            }
3315            Err(e) => {
3316                tracing::warn!("decode error on streamed request {request_id}: {e}");
3317                // The socket carried 200 -- SSE headers precede the
3318                // first token -- but the request produced no completion.
3319                // The monitor records outcomes, and a 200 row with zero
3320                // tokens would read as a successful empty answer, so the
3321                // failure is stated as 500 here and only here.
3322                stats_state.record_request(stats::Record {
3323                    request_id: &request_id,
3324                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3325                    model: Some(served_model.clone()),
3326                    status: 500,
3327                    stream: true,
3328                    duration_ms: started.elapsed().as_millis() as u64,
3329                    usage: None,
3330                    attribution: &attribution,
3331                });
3332                let payload = ChatCompletionChunk {
3333                    id: request_id.clone(),
3334                    request_id: pending_request_id.take(),
3335                    object: "chat.completion.chunk",
3336                    model: model_name,
3337                    choices: vec![ChatCompletionChunkChoice {
3338                        index: 0,
3339                        delta: ChatCompletionChunkDelta {
3340                            role: Some("assistant"),
3341                            content: Some(format!("[error: {e}]")),
3342                            reasoning_content: None,
3343                            tool_calls: None,
3344                        },
3345                        finish_reason: Some("stop"),
3346                    }],
3347                    usage: None,
3348                };
3349                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3350                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3351            }
3352        }
3353        // The buffer is closed by dropping `emitter` here -- including
3354        // on a panic, which is the case an explicit call would miss.
3355        // See `resume::Emitter`'s `Drop`.
3356        drop(emitter);
3357    });
3358
3359    let stream = sse::with_keepalive(rx, keepalive, sse::KEEPALIVE_INTERVAL);
3360    // `X-Accel-Buffering: no` is the one header that actually reaches
3361    // the problem the plan names: nginx (and the proxies that copied
3362    // its convention) buffer `text/event-stream` by default, which
3363    // turns a token-by-token stream into one silent wait followed by
3364    // the whole answer at once -- indistinguishable, from the browser,
3365    // from a hung backend. axum already sets `Cache-Control: no-cache`
3366    // on an `Sse` response, so that half is covered.
3367    //
3368    // The keepalive every 15s is the other half: it gives an
3369    // idle-but-healthy stream something to send, so a client's stall
3370    // timeout measures the *connection* rather than the model's
3371    // time-to-first-token on a long prompt.
3372    //
3373    // **Not `Sse::keep_alive`.** axum's keepalive is an SSE COMMENT,
3374    // and a comment does not reach a client's event handler -- codex's
3375    // 300s stream-idle timeout only resets on a data frame, so a
3376    // comment-kept stream is reconnected mid-answer on a long prefill.
3377    // `sse::with_keepalive` sends a real `chat.completion.chunk` with
3378    // an empty delta instead: a concatenating client adds nothing, and
3379    // the transport sees traffic. It also covers the silence BEFORE
3380    // the first token, which is exactly the queue-wait and long-prefill
3381    // window where this matters most.
3382    Ok((
3383        [(
3384            axum::http::HeaderName::from_static("x-accel-buffering"),
3385            axum::http::HeaderValue::from_static("no"),
3386        )],
3387        Sse::new(stream),
3388    )
3389        .into_response())
3390}
3391
3392/// The axum pattern for one of the published path templates.
3393///
3394/// `frink_api::routes` writes placeholders in the OpenAPI style
3395/// because it is imported by clients that have never heard of this
3396/// server's router; axum 0.7 wants `:name`. Converting here keeps one
3397/// published spelling and one router spelling, and the test below fails
3398/// if they ever stop describing the same path.
3399///
3400/// This rewrites EVERY `{name}` it finds rather than one known
3401/// placeholder. The narrow version took `{request_id}` only, so the two
3402/// Responses templates were mounted with their braces intact and axum
3403/// read `{response_id}` as a literal segment: `GET /v1/responses/abc`
3404/// matched no route and got axum's bodiless 404 instead of the
3405/// handler's, and the one path that did match would have panicked on
3406/// `MissingPathParams`. Anything with a placeholder must go through
3407/// here.
3408/// Every route that sits behind `FRINK_API_KEY`, as ONE list.
3409///
3410/// Extracted because there were two of these: this one and a
3411/// hand-written copy in the test module, which had already drifted --
3412/// the test router was missing `/metrics`, `/cache/stats`, both rerank
3413/// spellings and half of `/admin`, so an HTTP test could pass against a
3414/// route the real server does not serve, or 404 on one it does. That is
3415/// this repo's dominant bug shape (two structures that must agree, with
3416/// nothing enforcing it) sitting inside the test harness, where it is
3417/// worst: it makes the tests agree with themselves.
3418///
3419/// `/health` is deliberately NOT here. It is the one route that must
3420/// stay reachable without a key, and it is registered separately for
3421/// that reason.
3422fn protected_routes() -> Router<Arc<AppState>> {
3423    use frink_api::routes;
3424
3425    Router::new()
3426        .route(routes::V1_MODELS, get(list_models))
3427        // The Responses surface decodes tokens, so it sits behind the
3428        // same key as `/v1/chat/completions`: it must cost what
3429        // decoding tokens costs.
3430        .route(routes::V1_RESPONSES, post(responses::responses))
3431        .route(
3432            &axum_path(routes::V1_RESPONSE),
3433            get(responses::responses_get),
3434        )
3435        .route(
3436            &axum_path(routes::V1_RESPONSE_CANCEL),
3437            post(responses::responses_cancel),
3438        )
3439        .route(&axum_path(routes::SLOTS_ID), post(slots::post_slot))
3440        .route(routes::V1_STATS, get(serving_stats))
3441        .route(routes::V1_REQUESTS, get(recent_requests))
3442        .route(routes::V1_CACHE_STATUS, get(cache_admin::cache_status))
3443        .route(routes::V1_CACHE_REBUILD, post(cache_admin::cache_rebuild))
3444        .route(routes::ADMIN_PREPARE_STOP, post(cache_admin::prepare_stop))
3445        .route(
3446            routes::LORA_ADAPTERS,
3447            get(lora::get_lora_adapters).post(lora::post_lora_adapters),
3448        )
3449        .route(routes::V1_CHAT_COMPLETIONS, post(chat_completions))
3450        // Behind the same key as the endpoint that started the work:
3451        // an unauthenticated caller must not be able to stop someone
3452        // else's generation by guessing at request ids.
3453        .route(routes::V1_CANCEL, post(cancel_generation))
3454        // Reconnect and the polling fallback, both behind the same key
3455        // as the request that filled the buffer: the replay window holds
3456        // the model's output, so reading it must cost what producing it
3457        // cost.
3458        .route(&axum_path(routes::V1_STREAM), get(resume::resume))
3459        .route(&axum_path(routes::V1_STREAM_POLL), get(resume::poll))
3460        .route(routes::V1_MESSAGES, post(anthropic::messages))
3461        .route(
3462            routes::V1_MESSAGES_COUNT_TOKENS,
3463            post(anthropic::count_tokens),
3464        )
3465        .route(routes::V1_COMPLETIONS, post(openai_extra::completions))
3466        // llama.cpp's NATIVE completion endpoint, under both spellings
3467        // it mounts. Not an alias of the line above: different request
3468        // fields, a different response object, and a stream that ends
3469        // without `[DONE]`. See `crate::completion`.
3470        .route(routes::COMPLETION, post(completion::completion))
3471        .route(routes::COMPLETIONS, post(completion::completion))
3472        .route(routes::V1_TOKENIZE, post(openai_extra::tokenize))
3473        .route(routes::V1_DETOKENIZE, post(openai_extra::detokenize))
3474        // llama.cpp's unprefixed spelling of the same two, on the SAME
3475        // handlers -- not copies. The `/v1/` prefix was frink's
3476        // invention (OpenAI has no tokenize endpoint), so every
3477        // llama.cpp client was getting a 404 that named nothing. Behind
3478        // the key with their twins: they read the loaded vocabulary.
3479        .route(routes::TOKENIZE, post(openai_extra::tokenize))
3480        .route(routes::DETOKENIZE, post(openai_extra::detokenize))
3481        .route(routes::V1_EMBEDDINGS, post(embeddings::embeddings))
3482        // Cross-encoder reranking, under the `/v1` spelling Cohere and
3483        // Jina clients use and the unprefixed one llama.cpp mounts.
3484        // Same handler: this really is an alias, not a second dialect.
3485        .route(routes::V1_RERANK, post(rerank::rerank))
3486        .route(routes::RERANK, post(rerank::rerank))
3487        .route(routes::CACHE_STATS, get(cache_stats))
3488        .route(routes::METRICS, get(metrics))
3489        // The control surface. Registered inside `protected` on
3490        // purpose: these routes change what the server serves and write
3491        // to disk, so they get the same FRINK_API_KEY gate as /v1/*
3492        // and never the unauthenticated treatment /health has.
3493        .route(routes::ADMIN_MODELS, get(admin::models))
3494        .route(routes::ADMIN_MODELS_LOAD, post(admin::load_model))
3495        .route(routes::ADMIN_MODELS_UNLOAD, post(admin::unload_model))
3496        .route(routes::ADMIN_DOWNLOAD, post(admin::download))
3497        .route(routes::ADMIN_TASKS, get(admin::tasks))
3498        .route(&admin::cancel_route(), post(admin::cancel_task))
3499        .route(routes::ADMIN_STATS, get(admin::stats))
3500        // Server-side conversation storage, mounted here so it inherits
3501        // the same key gate as the endpoint that generated the text it
3502        // stores. Routes and store both live in `conversations`.
3503        .merge(conversations::router())
3504}
3505
3506fn axum_path(template: &str) -> String {
3507    let mut out = String::with_capacity(template.len());
3508    let mut rest = template;
3509    while let Some(open) = rest.find('{') {
3510        let Some(close) = rest[open..].find('}').map(|c| open + c) else {
3511            break;
3512        };
3513        out.push_str(&rest[..open]);
3514        out.push(':');
3515        out.push_str(&rest[open + 1..close]);
3516        rest = &rest[close + 1..];
3517    }
3518    out.push_str(rest);
3519    out
3520}
3521
3522/// `POST /v1/cancel` -- the explicit half of two-tier cancellation.
3523///
3524/// Answers `200` when a live generation was signalled and `404` when
3525/// the id names nothing that is running. That difference is the whole
3526/// point of the endpoint returning a body at all: "already finished"
3527/// and "stopped it" are both fine outcomes, but only one of them saved
3528/// any work, and a UI told `ok: true` for both will claim it stopped
3529/// something it did not.
3530async fn cancel_generation(
3531    State(state): State<Arc<AppState>>,
3532    Json(req): Json<frink_api::CancelGenerationRequest>,
3533) -> Response {
3534    let cancelled = state.cancels.cancel(&req.request_id);
3535    let status = if cancelled {
3536        StatusCode::OK
3537    } else {
3538        StatusCode::NOT_FOUND
3539    };
3540    let detail = if cancelled {
3541        "the generation was asked to stop; it ends at its next token".to_string()
3542    } else {
3543        "no generation with that request_id is running -- it has already \
3544         finished, was never issued, or was served by a path that does \
3545         not register for cancellation"
3546            .to_string()
3547    };
3548    (
3549        status,
3550        Json(frink_api::CancelGenerationResponse {
3551            request_id: req.request_id,
3552            cancelled,
3553            detail,
3554        }),
3555    )
3556        .into_response()
3557}
3558
3559/// What a freshly loaded checkpoint becomes when it is published as the
3560/// active model: the model itself, its optional continuous-batching
3561/// worker, and the context ceiling both decode paths admit on.
3562type Activated = (
3563    Loaded,
3564    Option<serving::batch::ContinuousBatcher>,
3565    Option<Arc<budget::ContextCeiling>>,
3566);
3567
3568/// The scheduler config for a freshly loaded GGUF, with the ceilings an
3569/// operator did not configure *derived* from the checkpoint instead of
3570/// left absent.
3571///
3572/// This is the server half of `mem-preload-kv-budget`: `frink run`
3573/// already priced weights + `n_ctx * per_token_kv` + headroom against
3574/// the device budget before loading, while `frink-server` admitted on
3575/// whatever `FRINK_CB_*` happened to be set and otherwise on nothing.
3576///
3577/// Precedence is one-directional and deliberate: an explicit
3578/// `FRINK_CB_MAX_CONTEXT` / `FRINK_CB_KV_BLOCKS` is never overridden,
3579/// because an operator who names a number has information this
3580/// arithmetic does not. Derivation only ever fills an *absent* ceiling,
3581/// where the alternative is no ceiling at all.
3582///
3583/// `path` is `None` for the synthetic-weights fallback, which has no
3584/// checkpoint on disk to price.
3585fn price_batcher_config(path: Option<&str>) -> serving::batch::BatcherConfig {
3586    let mut batcher = serving::batch::BatcherConfig::from_env();
3587    if batcher.max_context.is_some() && batcher.kv_blocks.is_some() {
3588        // Nothing left to derive, and pricing the checkpoint would only
3589        // print arithmetic that decides nothing.
3590        return batcher;
3591    }
3592    let Some(path) = path else {
3593        return batcher;
3594    };
3595    // `frink_core::cache::KvCache` is `Vec<f32>` on both decode paths,
3596    // so f32 is the width really kept, even under Metal attention where
3597    // the *device* also holds an f16 copy. Budgeting the host store is
3598    // the conservative reading: it over-charges KV and therefore
3599    // under-states the context that fits.
3600    let priced = budget::price_gguf(path, frink_models::KvElem::F32, 1);
3601    let Some((priced, gguf_ctx, source)) = priced else {
3602        return batcher;
3603    };
3604    let Some(derived) = budget::derive_limits(&priced, gguf_ctx, batcher.kv_block_size) else {
3605        // See `budget`'s module doc: a fit of zero tokens is not a
3606        // ceiling of zero, it is an estimate saying this model should
3607        // not have loaded -- and it did. Say so and admit as before.
3608        tracing::warn!(
3609            "this checkpoint's weights leave no room for KV inside the {source}: {} weight \
3610             bytes against a {} byte budget. Serving with no derived context ceiling -- set \
3611             FRINK_DEVICE_BUDGET_BYTES if the probe is wrong, or FRINK_CB_MAX_CONTEXT to \
3612             admit on a number you choose.",
3613            priced.weights_bytes,
3614            priced.device_budget_bytes,
3615        );
3616        return batcher;
3617    };
3618    tracing::info!("{source}");
3619    tracing::info!("{}", derived.fit);
3620    let adopted = budget::apply_derived(&mut batcher, &derived);
3621    if adopted.max_context {
3622        tracing::info!(
3623            "derived per-request context ceiling: {} token positions (prompt + max_tokens); \
3624             override with FRINK_CB_MAX_CONTEXT",
3625            derived.max_context
3626        );
3627    }
3628    if adopted.kv_blocks {
3629        tracing::info!(
3630            "derived KV block budget: {} blocks x {} positions; override with FRINK_CB_KV_BLOCKS",
3631            derived.kv_blocks,
3632            batcher.kv_block_size
3633        );
3634    }
3635    if let Some(narrowed) = adopted.max_context_narrowed {
3636        tracing::info!(
3637            "per-request context ceiling narrowed to {narrowed} token positions: the whole KV              ledger is {} blocks x {} positions, so a longer request could never be admitted",
3638            batcher.kv_blocks.unwrap_or_default(),
3639            batcher.kv_block_size
3640        );
3641    }
3642    batcher
3643}
3644
3645/// Turns a freshly loaded checkpoint into the parts that get published
3646/// as the active model.
3647///
3648/// Extracted from `build_app_state` so `/admin/models/load` builds its
3649/// replacement exactly the way startup builds the first one -- a second
3650/// copy of this match would be a second place for a new engine variant
3651/// to be forgotten, and the difference would only show up as a model
3652/// that silently loses continuous batching after a swap.
3653pub(crate) fn activate_loaded_model(
3654    loaded: model::LoadedModel,
3655    enable_continuous_batching: bool,
3656    path: Option<&str>,
3657    paged_kv: Option<&generate::PagedKvConfig>,
3658) -> Activated {
3659    match loaded {
3660        model::LoadedModel::Gguf(g) => {
3661            let decoder = Arc::new(g.decoder);
3662            let tokenizer = Arc::new(g.tokenizer);
3663            let config = price_batcher_config(path);
3664            // Prefill is still a per-token `forward_token` loop on both
3665            // paths (see `sched-chunked-prefill`: chunking bought
3666            // fairness, not a batched prefill kernel), so a sliding
3667            // layer really does need only `window + 1 - 1` positions
3668            // live. `chunk = 1` here is the truth, not a simplification.
3669            let shape =
3670                frink_models::KvShape::from_config(&decoder.config, frink_models::KvElem::F32);
3671            let ceiling = Arc::new(budget::ContextCeiling::new(config.max_context, shape));
3672            let batcher = if enable_continuous_batching {
3673                tracing::info!(
3674                    "continuous batching enabled: decode steps share Decoder::forward_multi_seq \
3675                     (stop sequences use the same pending-buffer trim as the private generate loop)"
3676                );
3677                let tok = Arc::clone(&tokenizer);
3678                let decode = Arc::new(move |ids: &[usize]| tok.decode_bytes(ids));
3679                Some(serving::batch::ContinuousBatcher::spawn_with_ceiling(
3680                    Arc::clone(&decoder),
3681                    decode,
3682                    config,
3683                    Arc::clone(&ceiling),
3684                    paged_kv.cloned(),
3685                ))
3686            } else {
3687                None
3688            };
3689            (
3690                Loaded::Generative(Arc::new(Model::Gguf(GgufModel {
3691                    decoder,
3692                    tokenizer,
3693                    stop_tokens: g.stop_tokens,
3694                    bos_id: g.bos_id,
3695                    is_synthetic: g.is_synthetic,
3696                    chat_template: g.chat_template,
3697                }))),
3698                batcher,
3699                Some(ceiling),
3700            )
3701        }
3702        model::LoadedModel::Kimi(k) => (
3703            Loaded::Generative(Arc::new(Model::Kimi(KimiModel {
3704                engine: k.engine,
3705                tokenizer: k.tokenizer,
3706                stop_tokens: k.stop_tokens,
3707                chat_template: k.chat_template,
3708            }))),
3709            None,
3710            None,
3711        ),
3712        model::LoadedModel::Mla(m) => (
3713            Loaded::Generative(Arc::new(Model::Mla(MlaModel {
3714                engine: m.engine,
3715                tokenizer: m.tokenizer,
3716                stop_tokens: m.stop_tokens,
3717                bos_id: m.bos_id,
3718                name: m.name,
3719                chat_template: m.chat_template,
3720            }))),
3721            None,
3722            None,
3723        ),
3724        model::LoadedModel::Gemma4(m) => (
3725            Loaded::Generative(Arc::new(Model::Gemma4(Gemma4Model {
3726                engine: m.engine,
3727                tokenizer: m.tokenizer,
3728                stop_tokens: m.stop_tokens,
3729                bos_id: m.bos_id,
3730                name: m.name,
3731                chat_template: m.chat_template,
3732            }))),
3733            None,
3734            None,
3735        ),
3736        model::LoadedModel::Glm52(g) => (
3737            Loaded::Generative(Arc::new(Model::Glm52(Glm52Model {
3738                engine: g.engine,
3739                tokenizer: g.tokenizer,
3740                stop_tokens: g.stop_tokens,
3741                bos_id: g.bos_id,
3742                name: g.name,
3743                chat_template: g.chat_template,
3744            }))),
3745            None,
3746            None,
3747        ),
3748        // No batcher and no ceiling, and neither is an omission: an
3749        // encoder has no decode step to share between requests and no
3750        // KV cache to price a context against. Handing it either would
3751        // be pricing a cost it does not have.
3752        model::LoadedModel::Encoder(e) => (Loaded::Encoder(e), None, None),
3753    }
3754}
3755
3756/// The models a server starts with: the generation model, and the
3757/// embedding model when `FRINK_EMBEDDING_MODEL_PATH` names one.
3758///
3759/// One struct rather than two parameters because they are chosen
3760/// together at startup and are the only two things `build_app_state`
3761/// takes that are a *model*.
3762struct StartupModels {
3763    loaded: model::LoadedModel,
3764    embedding: Option<Arc<frink_models::EmbeddingModel>>,
3765}
3766
3767fn continuous_batching_env() -> Option<bool> {
3768    match std::env::var("FRINK_CONTINUOUS_BATCHING")
3769        .ok()
3770        .map(|v| v.trim().to_ascii_lowercase())
3771        .as_deref()
3772    {
3773        None => None,
3774        Some("1" | "true" | "yes" | "on") => Some(true),
3775        Some("0" | "false" | "no" | "off") => Some(false),
3776        _ => None,
3777    }
3778}
3779
3780fn metal_private_decode_active() -> bool {
3781    #[cfg(feature = "metal")]
3782    {
3783        BUILT_WITH_METAL
3784            && frink_metal::attn::metal_attn_enabled()
3785            && std::env::var("FRINK_METAL").ok().as_deref() != Some("0")
3786    }
3787    #[cfg(not(feature = "metal"))]
3788    {
3789        false
3790    }
3791}
3792
3793fn continuous_batching_compatible(
3794    loaded: &model::LoadedModel,
3795    kv_pool: &Option<generate::KvPoolConfig>,
3796    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3797    paged_kv: &Option<generate::PagedKvConfig>,
3798) -> bool {
3799    matches!(loaded, model::LoadedModel::Gguf(_))
3800        && (paged_kv.is_some() || (kv_pool.is_none() && prefix_cache.is_none()))
3801}
3802
3803fn resolve_continuous_batching_enabled(
3804    loaded: &model::LoadedModel,
3805    kv_pool: &Option<generate::KvPoolConfig>,
3806    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3807    paged_kv: &Option<generate::PagedKvConfig>,
3808) -> bool {
3809    if !continuous_batching_compatible(loaded, kv_pool, prefix_cache, paged_kv) {
3810        return false;
3811    }
3812    match continuous_batching_env() {
3813        Some(true) => true,
3814        Some(false) => false,
3815        None => metal_private_decode_active(),
3816    }
3817}
3818
3819fn acquire_metal_private_decode_gate(
3820    gate: Option<&std::sync::Mutex<()>>,
3821    used_batcher: bool,
3822) -> Option<std::sync::MutexGuard<'_, ()>> {
3823    if used_batcher {
3824        None
3825    } else {
3826        gate.map(|g| g.lock().unwrap_or_else(|p| p.into_inner()))
3827    }
3828}
3829
3830fn build_app_state(
3831    models: StartupModels,
3832    kv_pool: Option<generate::KvPoolConfig>,
3833    paged_kv: Option<generate::PagedKvConfig>,
3834    prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
3835    enable_continuous_batching: bool,
3836    mcp: Option<mcp::LoadedMcpConfig>,
3837    detection: Arc<health::Detection>,
3838) -> AppState {
3839    let StartupModels { loaded, embedding } = models;
3840    let configured_path = std::env::var("FRINK_MODEL_PATH").ok();
3841    let (loaded, batcher, ceiling) = activate_loaded_model(
3842        loaded,
3843        enable_continuous_batching,
3844        configured_path.as_deref(),
3845        paged_kv.as_ref(),
3846    );
3847    // The startup model's admin id is whichever discovered entry sits
3848    // at the configured path; `None` when it was not discovered (the
3849    // synthetic fallback, or a path outside the scanned directories),
3850    // in which case `/admin/models` reports nothing as active rather
3851    // than inventing an id no `load` request could name.
3852    let id = startup_model_id();
3853    let metal_private_decode_gate = if enable_continuous_batching || !metal_private_decode_active()
3854    {
3855        None
3856    } else {
3857        tracing::info!(
3858            "Metal private-loop decode will serialize concurrent requests until \
3859             continuous batching is enabled (FRINK_CONTINUOUS_BATCHING=1 or --cont-batching)"
3860        );
3861        Some(Arc::new(std::sync::Mutex::new(())))
3862    };
3863    AppState {
3864        embedding,
3865        active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
3866            id,
3867            loaded,
3868            batcher,
3869            ceiling,
3870            checkpoint_path: configured_path.as_deref().map(PathBuf::from),
3871        }))),
3872        paged_kv,
3873        load_in_progress: std::sync::atomic::AtomicBool::new(false),
3874        tasks: Arc::new(tasks::TaskRegistry::new()),
3875        cancels: Arc::new(cancel::CancelRegistry::new()),
3876        stats: stats::Stats::new(),
3877        streams: resume::StreamRegistry::new(),
3878        model_dir: admin::model_dirs().into_iter().next(),
3879        response_cache: Mutex::new(ResponseCache::new(1000, Duration::from_secs(3600))),
3880        kv_pool,
3881        prefix_cache,
3882        sessions: session::SessionStore::new(),
3883        requests_total: std::sync::atomic::AtomicU64::new(0),
3884        request_errors_total: std::sync::atomic::AtomicU64::new(0),
3885        started_at: std::time::Instant::now(),
3886        last_request_ms: std::sync::atomic::AtomicU64::new(0),
3887        detection,
3888        mcp,
3889        continuous_batching_enabled: enable_continuous_batching,
3890        metal_private_decode_gate,
3891        loading_model: Mutex::new(None),
3892        last_load_error: Mutex::new(None),
3893        serving: Mutex::new(crate::stats::ServingStats::default()),
3894        maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
3895        footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
3896        started_unix: unix_now(),
3897    }
3898}
3899
3900/// Builds the `/v1/embeddings` encoder from
3901/// `FRINK_EMBEDDING_MODEL_PATH`, or `None` when the variable is unset.
3902///
3903/// A failure here is fatal rather than deferred: a server that starts
3904/// with a misspelt path and then answers embedding requests out of the
3905/// *decoder* would be handing back vectors from the wrong model with
3906/// nothing in the response saying so.
3907fn load_embedding_model() -> anyhow::Result<Option<Arc<frink_models::EmbeddingModel>>> {
3908    let Ok(path) = std::env::var("FRINK_EMBEDDING_MODEL_PATH") else {
3909        return Ok(None);
3910    };
3911    let model = frink_models::EmbeddingModel::from_gguf_path(&path)
3912        .map_err(|e| anyhow::anyhow!("FRINK_EMBEDDING_MODEL_PATH={path}: {e}"))?;
3913    tracing::info!(
3914        "loaded embedding model '{}' ({}, {} dims, pooling {}, max {} tokens)",
3915        model.name(),
3916        model.architecture(),
3917        model.n_embd(),
3918        model.pooling_type().name(),
3919        model.n_ctx_train(),
3920    );
3921    Ok(Some(Arc::new(model)))
3922}
3923
3924/// Seconds since the epoch, or zero on a machine whose clock is set
3925/// before it. Only ever used to make an id distinct between process
3926/// generations, so a nonsense clock costs distinctness and nothing
3927/// else.
3928fn unix_now() -> u64 {
3929    std::time::SystemTime::now()
3930        .duration_since(std::time::UNIX_EPOCH)
3931        .map(|d| d.as_secs())
3932        .unwrap_or(0)
3933}
3934
3935/// The `/admin/models` id of the checkpoint `FRINK_MODEL_PATH` names,
3936/// when discovery finds it. Matching on the resolved path rather than
3937/// on the filename keeps two same-named files in different directories
3938/// from claiming each other's id.
3939fn startup_model_id() -> Option<String> {
3940    let configured = std::env::var("FRINK_MODEL_PATH").ok()?;
3941    let configured = std::fs::canonicalize(&configured).ok()?;
3942    admin::discover(&admin::model_dirs())
3943        .into_iter()
3944        .find(|d| {
3945            std::fs::canonicalize(&d.path)
3946                .map(|p| p == configured)
3947                .unwrap_or(false)
3948        })
3949        .map(|d| d.id)
3950}
3951
3952/// Builds the global rayon pool up front, on the main thread, with an
3953/// explicit width and QoS (see [`frink_core::threads`]).
3954///
3955/// Doing this from `main` rather than letting rayon build lazily is the
3956/// point: the first rayon call inside this server happens on a Tokio
3957/// `spawn_blocking` thread, so the workers used to inherit that thread's
3958/// QoS class -- which on macOS decides whether they land on performance
3959/// or efficiency cores.
3960fn init_cpu_pool() {
3961    match frink_core::threads::init_cpu_pool() {
3962        Some(n) => eprintln!(
3963            "frink-server: rayon pool {n} threads (perf cores {}; override with FRINK_CPU_THREADS)",
3964            frink_core::threads::perf_core_count()
3965        ),
3966        None => eprintln!("frink-server: global rayon pool already built; leaving it alone"),
3967    }
3968}
3969
3970/// Prints the machine-readable ready line (see `frink_api::lifecycle`)
3971/// on stdout and flushes it.
3972///
3973/// This one line is what makes `--port 0` usable, and it deletes a whole
3974/// feature from any supervising process: no "is the port free" probe, no
3975/// `lsof` to work out whether an existing listener is a stale copy of
3976/// ourselves or a stranger's server, no dialog to explain the result.
3977/// The kernel picks the port and the child says what it got.
3978///
3979/// Shares stdout with the tracing subscriber on purpose -- a parent
3980/// reads stdout line by line and ignores anything that is not the ready
3981/// event, which `ServerReady::from_line` does for it.
3982fn announce_ready(addr: SocketAddr, scheme: &str) {
3983    use std::io::Write;
3984    let ready =
3985        frink_api::ServerReady::new(addr, scheme, env!("CARGO_PKG_VERSION"), std::process::id());
3986    let mut stdout = std::io::stdout().lock();
3987    let _ = writeln!(stdout, "{}", ready.to_line());
3988    let _ = stdout.flush();
3989}
3990
3991/// Resolves when the server should stop serving.
3992///
3993/// Stdin-close is the one orphan-prevention mechanism that behaves
3994/// identically on macOS, Windows and Linux and survives a parent that
3995/// dies rather than exiting cleanly: the kernel closes the pipe either
3996/// way. The POSIX alternative -- a signal handler plus an exit hook plus
3997/// a reaper -- has no Windows equivalent at all, since there is no
3998/// SIGTERM there.
3999///
4000/// When disabled this future never resolves, which is exactly the
4001/// previous behaviour: serve until the process is stopped externally.
4002async fn shutdown_signal(exit_on_stdin_close: bool) {
4003    if !exit_on_stdin_close {
4004        std::future::pending::<()>().await;
4005        return;
4006    }
4007    let _ = tokio::task::spawn_blocking(|| {
4008        use std::io::Read;
4009        let mut sink = [0u8; 256];
4010        let mut stdin = std::io::stdin().lock();
4011        loop {
4012            match stdin.read(&mut sink) {
4013                // EOF: the parent is gone, or closed the pipe.
4014                Ok(0) => break,
4015                // Input on stdin is not a protocol here; drain it.
4016                Ok(_) => continue,
4017                Err(e) => {
4018                    tracing::warn!("stdin read failed ({e}); treating it as closed");
4019                    break;
4020                }
4021            }
4022        }
4023    })
4024    .await;
4025    tracing::info!("stdin closed; shutting down");
4026}
4027
4028/// Tokio worker threads. The default is one per logical core, which on a
4029/// 10-core M2 Pro means 10 async workers oversubscribing the same cores
4030/// the rayon decode pool needs. Serving work here is almost entirely I/O
4031/// plus `spawn_blocking` handoff, so a small fixed pool is enough.
4032fn tokio_worker_threads() -> usize {
4033    std::env::var("FRINK_TOKIO_WORKERS")
4034        .ok()
4035        .and_then(|v| v.trim().parse::<usize>().ok())
4036        .filter(|n| *n > 0)
4037        .unwrap_or(2)
4038}
4039
4040/// Parses llama-server-style options and applies their environment
4041/// overrides before creating Tokio or Rayon worker threads. It then
4042/// brackets the async server lifecycle with journal records.
4043/// Install rustls' `ring` crypto provider as the process default.
4044///
4045/// `axum-server` is built with `tls-rustls-no-provider`, which
4046/// deliberately does NOT pick a backend -- see the comment on the
4047/// dependency in `Cargo.toml`. rustls then has no default provider, and
4048/// building a `ServerConfig` without one fails at ACCEPT time rather
4049/// than at compile time, which is the worst place for it to surface: a
4050/// server that started cleanly and refuses every TLS connection.
4051///
4052/// So this runs unconditionally at startup, not lazily in the TLS arm.
4053/// `install_default` returns `Err` if a provider is already installed,
4054/// which is not a failure -- it means something else got there first
4055/// and the invariant we care about (there IS a provider) already holds.
4056fn install_ring_crypto_provider() {
4057    let _ = rustls::crypto::ring::default_provider().install_default();
4058}
4059
4060/// Runs the server to completion.
4061///
4062/// Takes already-parsed arguments so the same library backs both the
4063/// `frink-server` binary and frink-cli's optional `serve` feature,
4064/// and neither front end can drift into its own startup logic.
4065pub fn run_server(args: ServerArgs) -> anyhow::Result<()> {
4066    if args.list_devices {
4067        frink_models::devices::print_available_devices();
4068        return Ok(());
4069    }
4070    apply_cli_overrides(&args)?;
4071
4072    // Before the model is loaded and before the port is bound: refuse
4073    // to be the second process holding weights on this host. Held for
4074    // the life of the process -- dropping it deregisters us.
4075    let _instance = {
4076        use frink_core::instance::{register, InstancePolicy};
4077        let policy = if args.allow_multiple_instances {
4078            InstancePolicy::Multi
4079        } else {
4080            InstancePolicy::from_env_or(InstancePolicy::Single)
4081        };
4082        let model = std::env::var("FRINK_MODEL_PATH").ok();
4083        register(
4084            "server",
4085            model.as_deref(),
4086            frink_core::instance::current_backend(),
4087            policy,
4088        )
4089        .map_err(|conflict| anyhow::anyhow!("{conflict}"))?
4090    };
4091
4092    let journal = journal::Journal::from_env();
4093    eprintln!(
4094        "frink-server: process lifecycle journal at {:?} (override with FRINK_JOURNAL_PATH)",
4095        journal.path()
4096    );
4097    journal.append(&journal::Record::session_start(
4098        env!("CARGO_PKG_VERSION"),
4099        std::process::id(),
4100    ));
4101    journal::install_panic_hook(journal.clone());
4102
4103    let mcp_config_path = args.mcp_config.clone();
4104    let exit_on_stdin_close = args.exit_on_stdin_close
4105        || std::env::var("FRINK_EXIT_ON_STDIN_CLOSE")
4106            .map(|v| v == "1")
4107            .unwrap_or(false);
4108
4109    // Before Tokio exists, so the decode pool's threads are not spawned
4110    // from (and do not inherit the QoS of) a blocking-pool thread.
4111    // SAFETY: still single-threaded here.
4112    unsafe { frink_core::weight_matrix::default_cpu_int_dot_on() };
4113    init_cpu_pool();
4114
4115    let runtime = tokio::runtime::Builder::new_multi_thread()
4116        .worker_threads(tokio_worker_threads())
4117        .enable_all()
4118        .build()?;
4119    let result = runtime.block_on(run(mcp_config_path, exit_on_stdin_close));
4120
4121    let reason = match &result {
4122        Ok(()) => "normal".to_string(),
4123        Err(e) => e.to_string(),
4124    };
4125    journal.append(&journal::Record::session_exit(reason));
4126
4127    // Dropping the runtime instead would wait for blocking tasks, and
4128    // the stdin watcher parks in a blocking read that may never return
4129    // (a terminal keeps stdin open forever). The serving future has
4130    // already finished by here, so nothing useful is being abandoned.
4131    runtime.shutdown_background();
4132
4133    result
4134}
4135
4136async fn run(mcp_config_path: Option<PathBuf>, exit_on_stdin_close: bool) -> anyhow::Result<()> {
4137    // `try_init`, not `init`. As a library this runs inside a process
4138    // that may already have a subscriber: frink-cli installs one
4139    // before it dispatches, so `frink serve` would panic on startup
4140    // with "a global default trace dispatcher has already been set".
4141    // Losing the race is not an error, it means logging is configured.
4142    let _ = tracing_subscriber::fmt::try_init();
4143
4144    // Fail-closed listener check, before anything else (including
4145    // loading the model, so a misconfigured bind fails fast rather than
4146    // after however long that takes): refuse to start bound to a
4147    // non-loopback address with no API key configured, unless the
4148    // operator has explicitly opted into that via
4149    // FRINK_ALLOW_UNAUTHENTICATED_REMOTE=1 -- see
4150    // `security::check_bind_authorization`'s doc comment for why an
4151    // address that doesn't even parse as loopback is treated the same
4152    // as a confirmed non-loopback one.
4153    let addr = std::env::var("FRINK_ADDR").unwrap_or_else(|_| "127.0.0.1:8383".to_string());
4154    let api_key_configured = std::env::var("FRINK_API_KEY").is_ok();
4155    let allow_unauthenticated_remote = std::env::var("FRINK_ALLOW_UNAUTHENTICATED_REMOTE")
4156        .map(|v| v == "1")
4157        .unwrap_or(false);
4158    if let Err(msg) =
4159        security::check_bind_authorization(&addr, api_key_configured, allow_unauthenticated_remote)
4160    {
4161        anyhow::bail!(msg);
4162    }
4163
4164    // Loaded before the generation model, so a bad path fails the
4165    // start rather than the first `/v1/embeddings` request. This is the
4166    // SIDE-CAR: a second checkpoint beside a generative one. An encoder
4167    // at `FRINK_MODEL_PATH` needs none of this -- it goes through
4168    // `model::load()` below like any other checkpoint and becomes the
4169    // active model.
4170    let embedding_model = load_embedding_model()?;
4171
4172    let mut loaded = model::load()?;
4173    match &loaded {
4174        model::LoadedModel::Gguf(g) => tracing::info!(
4175            "loaded GGUF model '{}' (synthetic={}, tokenizer={})",
4176            g.decoder.config.name,
4177            g.is_synthetic,
4178            g.tokenizer.kind()
4179        ),
4180        model::LoadedModel::Kimi(k) => tracing::info!(
4181            "loaded Kimi K3 checkpoint (tokenizer={} base tokens)",
4182            k.tokenizer.vocab_size()
4183        ),
4184        model::LoadedModel::Mla(m) => tracing::info!(
4185            "loaded MLA GGUF '{}' (tokenizer={})",
4186            m.name,
4187            m.tokenizer.kind()
4188        ),
4189        model::LoadedModel::Gemma4(m) => tracing::info!(
4190            "loaded Gemma4 GGUF '{}' (tokenizer={})",
4191            m.name,
4192            m.tokenizer.kind()
4193        ),
4194        model::LoadedModel::Glm52(g) => tracing::info!(
4195            "loaded GLM-5.2 GGUF '{}' (tokenizer={})",
4196            g.name,
4197            g.tokenizer.kind()
4198        ),
4199        // `model::load_encoder_checkpoint` has already logged the
4200        // dimensions, the pooling rule and which endpoint serves it.
4201        model::LoadedModel::Encoder(_) => {}
4202    }
4203    // Opt-in VRAM budget for GPU-resident MoE experts. When unset but
4204    // Metal is active, default to a large budget so routed experts that
4205    // have Metal-capable quants run via `run_expert_placed` (Metal
4206    // matvec) instead of staying on CPU after Metal attention. Explicit
4207    // `FRINK_GPU_VRAM_BUDGET_BYTES=0` keeps the historical all-CPU MoE
4208    // placement. CUDA builds still require an explicit budget (Vast /
4209    // multi-GPU hosts vary too much for a safe default).
4210    let metal_default_moe_budget = {
4211        #[cfg(feature = "metal")]
4212        {
4213            frink_core::metal_dense_enabled()
4214                && std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES").is_err()
4215        }
4216        #[cfg(not(feature = "metal"))]
4217        {
4218            false
4219        }
4220    };
4221    if let Ok(budget_str) = std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES") {
4222        let budget: u64 = budget_str
4223            .parse()
4224            .expect("FRINK_GPU_VRAM_BUDGET_BYTES must be a non-negative integer");
4225        match &mut loaded {
4226            model::LoadedModel::Gguf(g) => {
4227                tracing::info!(
4228                    "GPU expert placement enabled: {budget} byte VRAM budget for routed experts \
4229                     (CUDA and/or Metal matvecs when built with the matching feature)"
4230                );
4231                g.decoder.gpu_vram_budget_bytes = Some(budget);
4232            }
4233            model::LoadedModel::Kimi(_) => {
4234                tracing::warn!(
4235                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Kimi K3 -- not \
4236                     supported yet (its MoE stack isn't wired to PlacementPlan), ignoring"
4237                );
4238            }
4239            model::LoadedModel::Mla(_) => {
4240                tracing::warn!(
4241                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is MLA -- dense \
4242                     FFN path only today; ignoring expert VRAM budget"
4243                );
4244            }
4245            model::LoadedModel::Gemma4(_) => {
4246                tracing::warn!(
4247                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Gemma4 -- \
4248                     ignoring expert VRAM budget"
4249                );
4250            }
4251            model::LoadedModel::Glm52(_) => {
4252                tracing::warn!(
4253                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is GLM-5.2 DSA -- \
4254                     GPU expert placement not wired yet; ignoring"
4255                );
4256            }
4257            model::LoadedModel::Encoder(_) => {
4258                tracing::warn!(
4259                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is an encoder -- \
4260                     it has no routed experts to place; ignoring"
4261                );
4262            }
4263        }
4264    } else if metal_default_moe_budget {
4265        // ~64 GiB sentinel: place as many experts as the planner allows;
4266        // Metal unified memory makes a hard VRAM split less meaningful
4267        // than on discrete CUDA cards.
4268        const METAL_DEFAULT_MOE_BUDGET: u64 = 64 * 1024 * 1024 * 1024;
4269        if let model::LoadedModel::Gguf(g) = &mut loaded {
4270            tracing::info!(
4271                "Metal MoE expert placement default-on ({METAL_DEFAULT_MOE_BUDGET} byte budget); \
4272                 set FRINK_GPU_VRAM_BUDGET_BYTES=0 to force CPU experts"
4273            );
4274            g.decoder.gpu_vram_budget_bytes = Some(METAL_DEFAULT_MOE_BUDGET);
4275        }
4276    }
4277    #[cfg(feature = "cuda")]
4278    {
4279        if frink_core::cuda_dense_enabled() {
4280            tracing::info!(
4281                "CUDA dense matvec enabled for WeightMatrix::apply \
4282                 (FRINK_CUDA=0|cpu forces CPU; weight buffers stay resident after first upload)"
4283            );
4284        } else {
4285            tracing::info!(
4286                "CUDA dense matvec disabled (FRINK_CUDA); dense decode uses CPU or Metal"
4287            );
4288        }
4289    }
4290    #[cfg(feature = "metal")]
4291    {
4292        if frink_core::metal_dense_enabled() {
4293            tracing::info!(
4294                "Metal dense matvec enabled for WeightMatrix::apply \
4295                 (FRINK_METAL=0|cpu forces CPU; weight buffers stay resident after first upload)"
4296            );
4297            match std::env::var("FRINK_METAL_ATTN").ok().as_deref() {
4298                Some("1") | Some("true") | Some("on") | Some("attn") => {
4299                    tracing::info!(
4300                        "Metal fused attention requested (FRINK_METAL_ATTN): \
4301                         QKV→RoPE→GQA→O on-GPU for Norm/NeoX decode without QKV bias/QK-norm"
4302                    );
4303                }
4304                _ => {}
4305            }
4306            tracing::info!(
4307                "Metal greedy GPU argmax: temperature<=0 folds \
4308                 final_norm+lm_head+argmax into the dense stack"
4309            );
4310        } else {
4311            tracing::info!("Metal dense matvec disabled (FRINK_METAL); dense decode uses CPU");
4312        }
4313    }
4314    // Both env vars are required together to enable pooling; unset ->
4315    // caches keep their original unbounded-per-request growth. This
4316    // mirrors the FRINK_API_KEY / FRINK_RATE_LIMIT_PER_MINUTE
4317    // pattern below: opt-in, off by default.
4318    //
4319    // Block count can be set explicitly (`FRINK_KV_POOL_BLOCKS` +
4320    // `FRINK_KV_POOL_BLOCK_SIZE`) or derived from a byte budget
4321    // (`FRINK_KV_BYTE_BUDGET` + `FRINK_KV_POOL_BLOCK_SIZE`, GGUF
4322    // models only). `FRINK_KV_POOL_BLOCKS` and
4323    // `FRINK_KV_BYTE_BUDGET` are mutually exclusive.
4324    let blocks_env = std::env::var("FRINK_KV_POOL_BLOCKS");
4325    let block_size_env = std::env::var("FRINK_KV_POOL_BLOCK_SIZE");
4326    let byte_budget_env = std::env::var("FRINK_KV_BYTE_BUDGET");
4327    if blocks_env.is_ok() && byte_budget_env.is_ok() {
4328        panic!(
4329            "FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive \
4330             (set one block-count source plus FRINK_KV_POOL_BLOCK_SIZE, or neither to disable)"
4331        );
4332    }
4333    let kv_pool = match (blocks_env, block_size_env, byte_budget_env) {
4334        (Ok(blocks), Ok(block_size), Err(_)) => {
4335            let total_blocks: usize = blocks
4336                .parse()
4337                .expect("FRINK_KV_POOL_BLOCKS must be a positive integer");
4338            let block_size: usize = block_size
4339                .parse()
4340                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4341            // Optional and independent of the two above: how long a
4342            // request retries before giving up when the pool is
4343            // momentarily exhausted, instead of rejecting on the very
4344            // first failed attempt. Zero (the default if unset)
4345            // preserves the original reject-immediately behavior.
4346            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4347                .ok()
4348                .map(|v| {
4349                    v.parse()
4350                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4351                })
4352                .unwrap_or(0);
4353            tracing::info!(
4354                "KV cache block pool enabled: {total_blocks} blocks x {block_size} positions \
4355                 each, shared across all concurrent requests, {queue_wait_ms}ms admission queue wait"
4356            );
4357            Some(generate::KvPoolConfig {
4358                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4359                queue_wait: Duration::from_millis(queue_wait_ms),
4360            })
4361        }
4362        (Err(_), Ok(block_size), Ok(byte_budget)) => {
4363            let block_size: usize = block_size
4364                .parse()
4365                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4366            let budget: u64 = byte_budget
4367                .parse()
4368                .expect("FRINK_KV_BYTE_BUDGET must be a positive integer");
4369            let cfg = match &loaded {
4370                model::LoadedModel::Gguf(g) => &g.decoder.config,
4371                model::LoadedModel::Kimi(_)
4372                | model::LoadedModel::Mla(_)
4373                | model::LoadedModel::Gemma4(_)
4374                | model::LoadedModel::Glm52(_)
4375                | model::LoadedModel::Encoder(_) => {
4376                    panic!(
4377                        "FRINK_KV_BYTE_BUDGET requires a GGUF decoder model \
4378                         (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4379                    );
4380                }
4381            };
4382            let bytes_per_block = block_size
4383                * cfg.kv_heads_all_layers()
4384                * (cfg.head_dim + cfg.v_head_dim())
4385                * std::mem::size_of::<f32>();
4386            assert!(
4387                bytes_per_block > 0,
4388                "derived KV block byte size must be positive (check model config and block size)"
4389            );
4390            let total_blocks = (budget as usize / bytes_per_block).max(1);
4391            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4392                .ok()
4393                .map(|v| {
4394                    v.parse()
4395                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4396                })
4397                .unwrap_or(0);
4398            tracing::info!(
4399                "KV cache block pool enabled from byte budget: {budget} bytes / \
4400                 {bytes_per_block} bytes per block ({block_size} positions x {} layers) -> \
4401                 {total_blocks} blocks, {queue_wait_ms}ms admission queue wait",
4402                cfg.n_layers
4403            );
4404            Some(generate::KvPoolConfig {
4405                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4406                queue_wait: Duration::from_millis(queue_wait_ms),
4407            })
4408        }
4409        (Err(_), Err(_), Err(_)) => None,
4410        (Err(_), Ok(_), Err(_)) => panic!(
4411            "FRINK_KV_POOL_BLOCK_SIZE requires FRINK_KV_POOL_BLOCKS or FRINK_KV_BYTE_BUDGET \
4412             (or unset all three to disable KV cache pooling)"
4413        ),
4414        (Ok(_), Ok(_), Ok(_)) => {
4415            unreachable!("FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive")
4416        }
4417        (Ok(_), Err(_), _) | (Err(_), Err(_), Ok(_)) => panic!(
4418            "FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET and FRINK_KV_POOL_BLOCK_SIZE must be \
4419             set together (or neither, to disable KV cache pooling)"
4420        ),
4421    };
4422    // Paged KV: per-layer shared page storage rather than a private
4423    // contiguous buffer per request. Refused alongside the pool and the
4424    // prefix cache rather than silently preferred over either -- an
4425    // operator who set two of these meant one of them, and picking for
4426    // them is how a deployment ends up not running what it thinks.
4427    let paged_kv = match (
4428        std::env::var("FRINK_PAGED_KV_BLOCKS"),
4429        std::env::var("FRINK_PAGED_KV_BLOCK_SIZE"),
4430    ) {
4431        (Ok(blocks), Ok(block_size)) => {
4432            assert!(
4433                kv_pool.is_none(),
4434                "FRINK_PAGED_KV_BLOCKS and FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET are \
4435                 mutually exclusive: both bound the same KV memory, by different means. \
4436                 Set one."
4437            );
4438            // Paged KV used to be refused here on any GPU backend,
4439            // because it returned fluent wrong tokens on Metal: the
4440            // prefill left K/V on the device and filled the host cache
4441            // with `KvCache::advance_len` placeholders, and the paged
4442            // prefill then copied those placeholders into the page
4443            // store. The decode that followed attended over a prompt
4444            // the model never saw.
4445            //
4446            // Fixed in `frink_models::Decoder`, which now downloads
4447            // the real rows for the caller that reads them, and pinned
4448            // on hardware by `paged_metal_parity` -- greedy ids
4449            // identical between paged and contiguous KV on a dense
4450            // model, an MoE model and a sliding-window model.
4451            let blocks_per_layer: usize = blocks
4452                .parse()
4453                .expect("FRINK_PAGED_KV_BLOCKS must be a positive integer");
4454            let block_size: usize = block_size
4455                .parse()
4456                .expect("FRINK_PAGED_KV_BLOCK_SIZE must be a positive integer");
4457            let gguf = match &loaded {
4458                model::LoadedModel::Gguf(g) => g,
4459                _ => panic!(
4460                    "FRINK_PAGED_KV_BLOCKS requires a GGUF decoder model \
4461                     (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4462                ),
4463            };
4464            let cfg = &gguf.decoder.config;
4465            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4466                .ok()
4467                .map(|v| {
4468                    v.parse()
4469                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4470                })
4471                .unwrap_or(0);
4472            tracing::info!(
4473                "Paged KV enabled: {blocks_per_layer} blocks x {block_size} positions per \
4474                 layer across {} layers, shared by all concurrent requests, \
4475                 {queue_wait_ms}ms admission queue wait",
4476                cfg.n_layers
4477            );
4478            // Prefix sharing rides on the same switch: paged KV is
4479            // what makes it possible at all, since sharing means two
4480            // sequences pointing at one page rather than one of them
4481            // holding a copy.
4482            let radix = Some(Arc::new(Mutex::new(crate::policy::radix::RadixCache::new(
4483                block_size,
4484            ))));
4485            // The anchor: the position an agentic turn will come back
4486            // to. Resolved ONCE here, from the served checkpoint's own
4487            // family and its own tokenizer, because it has to be a
4488            // single token id for the slide to recognize it on the hot
4489            // path for nothing. A checkpoint whose opener is more than
4490            // one token, or whose family has no opener at all (harmony
4491            // opens a call with an ordinary channel header), simply gets
4492            // no anchors and the slide follows the cursor.
4493            let anchor_token = crate::policy::anchor::resolve_anchor_token(
4494                crate::policy::parser::ToolCallFormat::infer(
4495                    &std::env::var("FRINK_MODEL_PATH").unwrap_or_default(),
4496                )
4497                .opener(),
4498                |text| {
4499                    gguf.tokenizer
4500                        .encode(text, SpecialTokens::Parse)
4501                        .into_iter()
4502                        .map(|t| t as u32)
4503                        .collect()
4504                },
4505            );
4506            if let Some(id) = anchor_token {
4507                tracing::info!(
4508                    "Paged KV window slide: tool-call anchor is token {id}, so a turn's \
4509                     window stops short of where its next turn rejoins"
4510                );
4511            }
4512            let slide_interval: usize = std::env::var("FRINK_PAGED_KV_SLIDE_INTERVAL")
4513                .ok()
4514                .map(|v| {
4515                    v.parse()
4516                        .expect("FRINK_PAGED_KV_SLIDE_INTERVAL must be a positive integer")
4517                })
4518                .unwrap_or(crate::policy::pool_budget::DEFAULT_SWA_EVICTION_INTERVAL);
4519            if let Some(window) = cfg.uniform_sliding_window() {
4520                tracing::info!(
4521                    "Paged KV window slide enabled: every layer slides by {window} every \
4522                     {slide_interval} decode steps, so a request holds its prompt and a \
4523                     window rather than its whole context"
4524                );
4525            } else if cfg.kv_block_window().is_some() {
4526                tracing::info!(
4527                    "Paged KV window slide NOT enabled: this model has full-attention layers, \
4528                     and a page group holds one block in every layer"
4529                );
4530            }
4531            Some(generate::PagedKvConfig {
4532                // Per layer, because a per-layer-shape model's layers do
4533                // not all cache the same width (`layer_shapes`).
4534                store: Arc::new(cfg.new_paged_kv(block_size, blocks_per_layer)),
4535                queue_wait: Duration::from_millis(queue_wait_ms),
4536                radix,
4537                anchor_token,
4538                slide_interval,
4539            })
4540        }
4541        (Err(_), Err(_)) => None,
4542        _ => panic!(
4543            "FRINK_PAGED_KV_BLOCKS and FRINK_PAGED_KV_BLOCK_SIZE must be set together \
4544             (or neither, to disable paged KV)"
4545        ),
4546    };
4547    // Mutually exclusive with kv_pool (see generate::generate's doc
4548    // comment on why a pool-backed cache can't safely be restored from
4549    // a prefix-cache clone): if both are set, the KV pool wins and
4550    // prefix caching is simply never consulted -- generate() already
4551    // enforces this per-request, so this is a heads-up for the
4552    // operator, not a hard failure.
4553    let prefix_cache = std::env::var("FRINK_PREFIX_CACHE_ENTRIES").ok().map(|v| {
4554        let max_entries: usize = v
4555            .parse()
4556            .expect("FRINK_PREFIX_CACHE_ENTRIES must be a positive integer");
4557        if kv_pool.is_some() {
4558            tracing::warn!(
4559                "FRINK_PREFIX_CACHE_ENTRIES is set but so is the KV pool -- prefix \
4560                     caching will never be consulted while a KV pool is configured"
4561            );
4562        }
4563        // A hard refusal rather than the warning above, because the
4564        // outcome is worse than "never consulted": `PrefixCache` stores
4565        // `Vec<KvCache>` snapshots, and a paged request has none to
4566        // give, so every store would be skipped and every lookup miss.
4567        // An operator would see a prefix cache configured, reporting
4568        // zero hits forever, with nothing saying why.
4569        assert!(
4570            paged_kv.is_none(),
4571            "FRINK_PREFIX_CACHE_ENTRIES and FRINK_PAGED_KV_BLOCKS are mutually exclusive: \
4572             the prefix cache stores contiguous KV snapshots, which a paged request does not \
4573             produce, so the cache could never hit. Set one."
4574        );
4575        tracing::info!(
4576            "KV-prefix cache enabled: up to {max_entries} stored prefixes, shared across \
4577                 all requests"
4578        );
4579        Arc::new(Mutex::new(PrefixCache::new(max_entries)))
4580    });
4581    if matches!(
4582        loaded,
4583        model::LoadedModel::Kimi(_) | model::LoadedModel::Mla(_) | model::LoadedModel::Glm52(_)
4584    ) && (kv_pool.is_some() || prefix_cache.is_some())
4585    {
4586        tracing::warn!(
4587            "KV pool / prefix cache are configured but the loaded model is Kimi, MLA, or GLM-5.2 -- \
4588             neither is consulted for those engines (state shapes differ from Decoder KV); see \
4589             frink_models::engine's module docs"
4590        );
4591    }
4592    let enable_cb =
4593        resolve_continuous_batching_enabled(&loaded, &kv_pool, &prefix_cache, &paged_kv);
4594    if enable_cb && continuous_batching_env().is_none() && metal_private_decode_active() {
4595        tracing::info!(
4596            "continuous batching enabled by default on Metal for safe parallel serving \
4597             (set FRINK_CONTINUOUS_BATCHING=0 or --no-cont-batching to use the private path)"
4598        );
4599    }
4600    if continuous_batching_env() == Some(true)
4601        && !continuous_batching_compatible(&loaded, &kv_pool, &prefix_cache, &paged_kv)
4602        && (kv_pool.is_some() || prefix_cache.is_some())
4603    {
4604        tracing::warn!(
4605            "FRINK_CONTINUOUS_BATCHING=1 ignored while KV pool or prefix cache is configured \
4606             (those modes keep the private generate path)"
4607        );
4608    }
4609    if let Ok(n) = std::env::var("FRINK_CHUNKED_PREFILL") {
4610        if let Ok(chunk) = n.parse::<usize>() {
4611            if chunk > 0 {
4612                tracing::info!("chunked prefill enabled: {chunk} tokens per forward_batch chunk");
4613            }
4614        }
4615    }
4616    if matches!(
4617        std::env::var("FRINK_CPU_KV_OFFLOAD").ok().as_deref(),
4618        Some("1")
4619    ) {
4620        tracing::warn!(
4621            "FRINK_CPU_KV_OFFLOAD=1: syncing Metal KV to host after each decode step \
4622             (minimal spill; full layer offload still planned)"
4623        );
4624    }
4625
4626    let mcp = match mcp_config_path {
4627        Some(path) => {
4628            let loaded = mcp::load_mcp_config(&path)?;
4629            tracing::info!(
4630                "MCP config loaded from {} ({} server(s); invocation not wired yet)",
4631                loaded.path,
4632                loaded.servers.len()
4633            );
4634            Some(loaded)
4635        }
4636        None => None,
4637    };
4638
4639    // Started before the router is built so the probe overlaps with
4640    // binding the port: by the time a client can ask, it has usually
4641    // already landed.
4642    let detection = health::Detection::spawn();
4643
4644    let state = Arc::new(build_app_state(
4645        StartupModels {
4646            loaded,
4647            embedding: embedding_model,
4648        },
4649        kv_pool,
4650        paged_kv,
4651        prefix_cache,
4652        enable_cb,
4653        mcp,
4654        detection,
4655    ));
4656
4657    // Paths come from `frink_api::routes` rather than string literals
4658    // so the UI, `frink chat` and this router cannot disagree about
4659    // what the surface is.
4660    use frink_api::routes;
4661
4662    // Frink Studio is a separate app served by its own dev/static
4663    // server (see `ui/` at the repository root); it reaches this
4664    // process over the public HTTP API like any other client, so there
4665    // is nothing to mount here and `/` stays a 404.
4666    let public = Router::new().route(routes::HEALTH, get(health));
4667
4668    let mut protected = protected_routes();
4669
4670    // Both off by default; set the corresponding env var to enable.
4671    // route_layer (not layer) so these apply only to the routes above,
4672    // never to /health, which stays reachable for liveness/readiness
4673    // probes regardless of auth or rate-limit configuration.
4674    if let Ok(key) = std::env::var("FRINK_API_KEY") {
4675        tracing::info!("API key auth enabled");
4676        let auth = limits::AuthConfig {
4677            api_key: Arc::new(key),
4678        };
4679        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4680            auth,
4681            limits::require_api_key,
4682        ));
4683    }
4684    if let Ok(rpm) = std::env::var("FRINK_RATE_LIMIT_PER_MINUTE") {
4685        let rpm: u32 = rpm
4686            .parse()
4687            .expect("FRINK_RATE_LIMIT_PER_MINUTE must be a positive integer");
4688        tracing::info!("rate limiting enabled: {rpm} requests/minute (global)");
4689        let limiter = Arc::new(limits::RateLimiter::per_minute(rpm));
4690        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4691            limiter,
4692            limits::rate_limit,
4693        ));
4694    }
4695    // Off by default; set FRINK_CORS_ORIGINS (comma-separated exact
4696    // origins) to enable. No wildcard support by design -- see
4697    // `security::parse_cors_origins`'s doc comment. Added last (so it's
4698    // the outermost route_layer, run before auth/rate-limiting): a CORS
4699    // preflight (OPTIONS) request carries no Authorization header and
4700    // is answered directly by `CorsLayer` itself, so it must not be
4701    // blocked by the auth/rate-limit layers underneath.
4702    if let Ok(spec) = std::env::var("FRINK_CORS_ORIGINS") {
4703        let origins = security::parse_cors_origins(&spec)
4704            .unwrap_or_else(|e| panic!("FRINK_CORS_ORIGINS: {e}"));
4705        tracing::info!(
4706            "CORS enabled: {} allow-listed origin(s) ({})",
4707            origins.len(),
4708            spec
4709        );
4710        let cors = tower_http::cors::CorsLayer::new()
4711            .allow_origin(tower_http::cors::AllowOrigin::list(origins))
4712            .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
4713            .allow_headers([
4714                axum::http::header::CONTENT_TYPE,
4715                axum::http::header::AUTHORIZATION,
4716                // The self-declared client label the monitor records
4717                // (see `attribution`). A custom header makes every
4718                // cross-origin call preflighted, so omitting it here
4719                // would not merely drop the label -- it would fail the
4720                // request outright.
4721                axum::http::HeaderName::from_static(attribution::CLIENT_HEADER),
4722                // Set by hand rather than by `EventSource`, because
4723                // this API needs POST and a bearer token. Same
4724                // consequence if it is missing.
4725                axum::http::HeaderName::from_static("last-event-id"),
4726            ]);
4727        protected = protected.route_layer(cors);
4728    }
4729
4730    // Outermost on purpose: every 503 this server can emit -- from a
4731    // handler, from `require_active`, or from the batch scheduler's
4732    // queue cap -- leaves with a `Retry-After` a client can act on.
4733    let app = public
4734        .merge(protected)
4735        .layer(axum::middleware::from_fn(limits::retry_after))
4736        .with_state(state);
4737
4738    // TLS is off by default -- set FRINK_TLS_CERT and FRINK_TLS_KEY
4739    // together to serve HTTPS instead of plain HTTP; unset (either or
4740    // both) preserves the original plain-HTTP behavior exactly. See
4741    // `security::tls_paths_from_env`'s doc comment for why this can't
4742    // be meaningfully unit-tested here.
4743    let tls_paths = security::tls_paths_from_env().unwrap_or_else(|e| panic!("{e}"));
4744    install_ring_crypto_provider();
4745    // Both arms bind first and read the address back off the socket
4746    // rather than trusting the requested one: with `--port 0` the
4747    // requested port is a lie by construction, and the ready line has
4748    // to carry what the kernel actually handed out.
4749    match tls_paths {
4750        Some(paths) => {
4751            let config =
4752                axum_server::tls_rustls::RustlsConfig::from_pem_file(&paths.cert, &paths.key)
4753                    .await
4754                    .map_err(|e| {
4755                        anyhow::anyhow!(
4756                            "failed to load TLS cert/key ({:?}, {:?}): {e}",
4757                            paths.cert,
4758                            paths.key
4759                        )
4760                    })?;
4761            let socket_addr: std::net::SocketAddr = addr
4762                .parse()
4763                .map_err(|e| anyhow::anyhow!("invalid FRINK_ADDR {addr:?} for TLS: {e}"))?;
4764            let listener = std::net::TcpListener::bind(socket_addr)?;
4765            // Tokio panics outright when handed a BLOCKING socket
4766            // ("Registering a blocking socket with the tokio runtime is
4767            // unsupported"), and axum-server registers this one
4768            // internally. Without this the TLS arm binds, prints its
4769            // ready line, and then panics on the first accept -- so the
4770            // failure looks like a healthy start followed by a server
4771            // that answers nothing.
4772            listener.set_nonblocking(true)?;
4773            let bound = listener.local_addr()?;
4774            tracing::info!("TLS enabled: frink-server listening on https://{bound}");
4775            announce_ready(bound, "https");
4776
4777            let handle = axum_server::Handle::new();
4778            let shutdown_handle = handle.clone();
4779            tokio::spawn(async move {
4780                shutdown_signal(exit_on_stdin_close).await;
4781                shutdown_handle.graceful_shutdown(Some(Duration::from_secs(5)));
4782            });
4783            axum_server::from_tcp_rustls(listener, config)?
4784                .handle(handle)
4785                .serve(app.into_make_service())
4786                .await?;
4787        }
4788        None => {
4789            let listener = tokio::net::TcpListener::bind(&addr).await?;
4790            let bound = listener.local_addr()?;
4791            tracing::info!("frink-server listening on {bound}");
4792            announce_ready(bound, "http");
4793            axum::serve(listener, app)
4794                .with_graceful_shutdown(shutdown_signal(exit_on_stdin_close))
4795                .await?;
4796        }
4797    }
4798    Ok(())
4799}
4800
4801#[cfg(test)]
4802pub(crate) mod tests {
4803    use super::*;
4804    use frink_models::config::test_dense_fixture;
4805
4806    #[test]
4807    fn the_ready_line_round_trips_through_a_parent_reading_stdout() {
4808        let addr: SocketAddr = "127.0.0.1:51999".parse().unwrap();
4809        let ready = frink_api::ServerReady::new(addr, "http", "0.5.0", std::process::id());
4810        let parsed = frink_api::ServerReady::from_line(&ready.to_line()).unwrap();
4811        assert_eq!(parsed.port, 51999);
4812        assert_eq!(parsed.base_url(), "http://127.0.0.1:51999");
4813        // A parent reads stdout line by line; tracing shares the stream.
4814        assert!(frink_api::ServerReady::from_line("INFO frink-server listening").is_none());
4815    }
4816
4817    fn test_model() -> Model {
4818        // Tiny vocab (32): raw byte ids ≥32 (e.g. ASCII "hello") are OOV.
4819        // HTTP/chat-template tests that need full ASCII use
4820        // `test_model_full_byte_vocab` instead.
4821        let cfg = test_dense_fixture();
4822        Model::Gguf(GgufModel {
4823            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 32)),
4824            tokenizer: Arc::new(ServerTokenizer::Byte),
4825            stop_tokens: StopTokens::default(),
4826            bos_id: None,
4827            is_synthetic: true,
4828            chat_template: chat_template::PromptTemplate::plain(),
4829        })
4830    }
4831
4832    fn greedy_params(max_tokens: usize) -> GenerationParams {
4833        GenerationParams {
4834            wants_logprobs: false,
4835            n: 1,
4836            reasoning: None,
4837            max_tokens,
4838            sampling: SamplingParams::default(),
4839            seed: 1,
4840            stop: Vec::new(),
4841            stop_token_ids: Vec::new(),
4842            json_object: false,
4843            grammar: None,
4844            cancel: None,
4845            ignore_eos: false,
4846            reasoning_budget: crate::reasoning_budget::ReasoningBudget::Unrestricted,
4847            lora: None,
4848        }
4849    }
4850
4851    /// Declares a full 0..255 byte-compatible vocab so HTTP-level tests
4852    /// that render chat templates (ASCII role names) do not spuriously
4853    /// reject their own prompt prefixes.
4854    fn test_model_full_byte_vocab() -> Model {
4855        test_model_full_byte_vocab_with_eos(None)
4856    }
4857
4858    /// [`test_model_full_byte_vocab`] with an end-of-generation id, so a
4859    /// test can tell a turn the MODEL ended from one that merely ran out
4860    /// of budget -- which is the only way `ignore_eos` is observable.
4861    ///
4862    /// Parameterised rather than copied: a second `Model` literal here
4863    /// is one more place a field has to be remembered.
4864    fn test_model_full_byte_vocab_with_eos(eos: Option<usize>) -> Model {
4865        let mut cfg = test_dense_fixture();
4866        cfg.vocab_size = 256;
4867        Model::Gguf(GgufModel {
4868            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4869            tokenizer: Arc::new(ServerTokenizer::Byte),
4870            stop_tokens: StopTokens::from_eos(eos),
4871            bos_id: None,
4872            is_synthetic: true,
4873            chat_template: chat_template::PromptTemplate::plain(),
4874        })
4875    }
4876
4877    /// One `AppState` for the HTTP-level tests, so a new field on the
4878    /// struct is added in one place rather than in every test that
4879    /// builds one.
4880    pub(crate) fn test_state(model: Model, response_cache: ResponseCache) -> AppState {
4881        AppState {
4882            embedding: None,
4883            paged_kv: None,
4884            active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
4885                id: None,
4886                loaded: Loaded::Generative(Arc::new(model)),
4887                batcher: None,
4888                ceiling: None,
4889                checkpoint_path: None,
4890            }))),
4891            load_in_progress: std::sync::atomic::AtomicBool::new(false),
4892            tasks: Arc::new(tasks::TaskRegistry::new()),
4893            cancels: Arc::new(cancel::CancelRegistry::new()),
4894            stats: stats::Stats::new(),
4895            streams: resume::StreamRegistry::new(),
4896            model_dir: None,
4897            response_cache: Mutex::new(response_cache),
4898            kv_pool: None,
4899            prefix_cache: None,
4900            sessions: session::SessionStore::new(),
4901            requests_total: std::sync::atomic::AtomicU64::new(0),
4902            request_errors_total: std::sync::atomic::AtomicU64::new(0),
4903            started_at: std::time::Instant::now(),
4904            last_request_ms: std::sync::atomic::AtomicU64::new(0),
4905            detection: Arc::new(health::Detection::ready(health::probe_backends())),
4906            mcp: None,
4907            continuous_batching_enabled: false,
4908            metal_private_decode_gate: None,
4909            loading_model: Mutex::new(None),
4910            last_load_error: Mutex::new(None),
4911            serving: Mutex::new(crate::stats::ServingStats::default()),
4912            maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
4913            footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
4914            started_unix: unix_now(),
4915        }
4916    }
4917
4918    /// A real axum `Router` wired exactly like `main()`'s (minus auth/
4919    /// rate-limiting, which are orthogonal and already covered by
4920    /// `limits`'s own tests), backed by a fresh
4921    /// `test_model_full_byte_vocab()` -- so tool-calling/session tests
4922    /// exercise the real HTTP request/response path (JSON
4923    /// (de)serialization, routing, handler wiring, chat-template
4924    /// rendering) via `tower::ServiceExt::oneshot`, not just the inner
4925    /// functions directly.
4926    pub(crate) fn test_app() -> Router {
4927        test_app_with_state(Arc::new(test_state(
4928            test_model_full_byte_vocab(),
4929            ResponseCache::new(1000, Duration::from_secs(3600)),
4930        )))
4931    }
4932
4933    /// [`test_app`] over a caller-owned state, so a test can reach in
4934    /// and swap or unload the model behind a live router.
4935    pub(crate) fn test_app_with_state(state: Arc<AppState>) -> Router {
4936        // The SAME route list the server builds, not a hand-written
4937        // copy of it. The copy that used to live here had drifted from
4938        // the real one, which is the failure mode that makes an HTTP
4939        // test worthless: it can only ever confirm that the tests agree
4940        // with the tests. See `protected_routes`.
4941        //
4942        // No auth, rate-limit or CORS layer: those are configured from
4943        // the environment in `run`, and a test that set the environment
4944        // would race every other test in the process.
4945        Router::new()
4946            .route(frink_api::routes::HEALTH, get(health))
4947            .merge(protected_routes())
4948            .with_state(state)
4949    }
4950
4951    fn named_test_model(name: &'static str, vocab_size: usize) -> Model {
4952        let mut cfg = test_dense_fixture();
4953        cfg.name = name;
4954        cfg.vocab_size = vocab_size;
4955        Model::Gguf(GgufModel {
4956            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4957            tokenizer: Arc::new(ServerTokenizer::Byte),
4958            stop_tokens: StopTokens::default(),
4959            bos_id: None,
4960            is_synthetic: true,
4961            chat_template: chat_template::PromptTemplate::plain(),
4962        })
4963    }
4964
4965    /// The same model, served through a real checkpoint's template
4966    /// rather than the role-labeled builtin -- so a test can ask what
4967    /// gets advertised for a checkpoint that actually has gears.
4968    fn model_with_template(name: &'static str, source: &str) -> Model {
4969        let mut cfg = test_dense_fixture();
4970        cfg.name = name;
4971        cfg.vocab_size = 256;
4972        Model::Gguf(GgufModel {
4973            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4974            tokenizer: Arc::new(ServerTokenizer::Byte),
4975            stop_tokens: StopTokens::default(),
4976            bos_id: None,
4977            is_synthetic: true,
4978            chat_template: chat_template::PromptTemplate::from_gguf_metadata(
4979                Some(source),
4980                Some("qwen3"),
4981                false,
4982                true,
4983                None,
4984                None,
4985            ),
4986        })
4987    }
4988
4989    /// Once a `200` and `text/event-stream` are on the wire, a
4990    /// rejection can only ride *in* the stream, where several agents
4991    /// render it as an empty response. So the prompt is rendered before
4992    /// the stream is committed, and a template that rejects this
4993    /// particular conversation is an ordinary 400 with a body.
4994    ///
4995    /// Fails if `prompt_from_messages` moves back inside the spawned
4996    /// generation task.
4997    #[tokio::test]
4998    async fn a_template_that_rejects_the_conversation_is_a_400_on_the_streaming_path() {
4999        // Raises on a second user turn, the way a real strict template
5000        // rejects an ordering it was never trained on.
5001        let strict = "{% if messages | length > 1 %}\
5002             {{ raise_exception('this template takes one turn') }}\
5003             {% endif %}{{ messages[0].content }}";
5004        let state = Arc::new(test_state(
5005            model_with_template("strict", strict),
5006            ResponseCache::new(4, Duration::from_secs(60)),
5007        ));
5008        let app = test_app_with_state(state);
5009
5010        let (status, body) = post_json_uri(
5011            &app,
5012            "/v1/chat/completions",
5013            serde_json::json!({
5014                "model": "strict",
5015                "stream": true,
5016                "messages": [
5017                    {"role": "user", "content": "one"},
5018                    {"role": "user", "content": "two"},
5019                ],
5020            }),
5021        )
5022        .await;
5023        assert_eq!(status, StatusCode::BAD_REQUEST);
5024        assert_eq!(body["error"]["param"], serde_json::json!("messages"));
5025        assert!(
5026            body["error"]["message"]
5027                .as_str()
5028                .unwrap()
5029                .contains("one turn"),
5030            "the template's own message must reach the caller: {body}"
5031        );
5032
5033        // And the same template serves a conversation it accepts.
5034        let (status, _) = post_json_uri(
5035            &app,
5036            "/v1/chat/completions",
5037            serde_json::json!({
5038                "model": "strict",
5039                "stream": true,
5040                "max_tokens": 1,
5041                "messages": [{"role": "user", "content": "one"}],
5042            }),
5043        )
5044        .await;
5045        assert_eq!(status, StatusCode::OK);
5046    }
5047
5048    /// A client should not have to guess which gears a checkpoint has.
5049    #[tokio::test]
5050    async fn models_advertises_the_gears_this_checkpoint_actually_has() {
5051        let reasoning = "{% if enable_thinking %}<think>{% endif %}\
5052             {% if reasoning_effort %}\
5053               {% if reasoning_effort not in ['low','medium','high'] %}\
5054                 {{ raise_exception('bad effort') }}\
5055               {% endif %}[{{ reasoning_effort }}]\
5056             {% endif %}{{ messages[0].content }}";
5057        let state = Arc::new(test_state(
5058            model_with_template("thinker", reasoning),
5059            ResponseCache::new(4, Duration::from_secs(60)),
5060        ));
5061        let app = test_app_with_state(state);
5062        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5063        assert_eq!(status, StatusCode::OK);
5064        let entry = &models["data"][0];
5065        assert_eq!(
5066            entry["supported_reasoning_efforts"],
5067            serde_json::json!(["off", "low", "medium", "high"])
5068        );
5069        assert_eq!(entry["default_reasoning_effort"], serde_json::json!("off"));
5070    }
5071
5072    /// The other half of the acceptance criterion: neither field, not
5073    /// an empty one. An empty list would say the question was asked and
5074    /// the answer was "no gears"; absence says it is not that kind of
5075    /// model.
5076    #[tokio::test]
5077    async fn a_checkpoint_with_no_thinking_controls_advertises_neither_field() {
5078        let app = test_app();
5079        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5080        let entry = &models["data"][0];
5081        assert!(entry.get("supported_reasoning_efforts").is_none());
5082        assert!(entry.get("default_reasoning_effort").is_none());
5083    }
5084
5085    fn active_model(state: &AppState, name: &'static str) -> Arc<ActiveModel> {
5086        Arc::new(ActiveModel {
5087            id: Some(name.to_string()),
5088            loaded: Loaded::Generative(Arc::new(named_test_model(name, 256))),
5089            batcher: None,
5090            ceiling: None,
5091            checkpoint_path: None,
5092        })
5093        .tap_into(state)
5094    }
5095
5096    /// Small helper so the swap tests read as "publish this model".
5097    trait TapInto {
5098        fn tap_into(self, state: &AppState) -> Self;
5099    }
5100    impl TapInto for Arc<ActiveModel> {
5101        fn tap_into(self, state: &AppState) -> Self {
5102            state.swap_active(Some(Arc::clone(&self)));
5103            self
5104        }
5105    }
5106
5107    /// The load-order guarantee the whole swap design exists to make:
5108    /// a request that has already taken its handle finishes against the
5109    /// weights it started on, even though a different model has since
5110    /// been published. Anything else would splice two checkpoints into
5111    /// one completion.
5112    #[test]
5113    fn an_in_flight_request_keeps_the_model_it_started_on() {
5114        let state = test_state(
5115            named_test_model("model-a", 256),
5116            ResponseCache::new(4, Duration::from_secs(60)),
5117        );
5118
5119        // A request that has begun: it has cloned the handle and is
5120        // about to decode against it.
5121        let in_flight = state.active().expect("a model is loaded");
5122        assert_eq!(in_flight.name(), "model-a");
5123
5124        active_model(&state, "model-b");
5125
5126        // The swap is visible to anything that asks *now*...
5127        assert_eq!(state.active().unwrap().name(), "model-b");
5128        // ...and completely invisible to the request already running.
5129        assert_eq!(in_flight.name(), "model-a");
5130        let (choices, _usage) = run_generation(
5131            in_flight.generative().unwrap(),
5132            "hi",
5133            &greedy_params(3),
5134            None,
5135            None,
5136            None,
5137            None,
5138            None,
5139            None,
5140        )
5141        .expect("the old model must still decode after being swapped out");
5142        assert!(matches!(
5143            choices[0].finish,
5144            FinishReason::Length | FinishReason::Stop
5145        ));
5146    }
5147
5148    /// The other half of the same guarantee: the old model is not freed
5149    /// at swap time, it is freed when the last holder lets go. A design
5150    /// that dropped it eagerly would free weights out from under a
5151    /// decode loop.
5152    #[test]
5153    fn a_swapped_out_model_lives_until_its_last_holder_releases_it() {
5154        let state = test_state(
5155            named_test_model("model-a", 256),
5156            ResponseCache::new(4, Duration::from_secs(60)),
5157        );
5158        let in_flight = state.active().expect("a model is loaded");
5159        let weights = Arc::clone(in_flight.generative().unwrap());
5160        assert!(Arc::strong_count(&weights) >= 2);
5161
5162        let previous = state.swap_active(Some(Arc::new(ActiveModel {
5163            id: Some("model-b".to_string()),
5164            loaded: Loaded::Generative(Arc::new(named_test_model("model-b", 256))),
5165            batcher: None,
5166            ceiling: None,
5167            checkpoint_path: None,
5168        })));
5169        drop(previous);
5170        // The registry has let go; the in-flight request has not.
5171        assert!(Arc::strong_count(&weights) >= 2);
5172        drop(in_flight);
5173        assert_eq!(Arc::strong_count(&weights), 1);
5174    }
5175
5176    /// Unload is not "keep serving the last thing loaded". A request
5177    /// that arrives afterwards must be told there is no model, not
5178    /// quietly served by a checkpoint the operator dropped.
5179    #[tokio::test]
5180    async fn unloading_answers_503_instead_of_serving_the_dropped_model() {
5181        let state = Arc::new(test_state(
5182            named_test_model("model-a", 256),
5183            ResponseCache::new(4, Duration::from_secs(60)),
5184        ));
5185        let app = test_app_with_state(Arc::clone(&state));
5186
5187        let (status, body) = post_json_uri(
5188            &app,
5189            frink_api::routes::ADMIN_MODELS_UNLOAD,
5190            serde_json::json!({}),
5191        )
5192        .await;
5193        assert_eq!(status, StatusCode::OK);
5194        assert_eq!(body["ok"], true);
5195        assert!(body["active"].is_null());
5196        assert!(state.active().is_none());
5197
5198        let (status, _) = get_json(&app, frink_api::routes::V1_MODELS).await;
5199        assert_eq!(status, StatusCode::OK);
5200        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5201        assert_eq!(models["data"].as_array().unwrap().len(), 0);
5202
5203        let (status, body) = post_json_uri(
5204            &app,
5205            "/v1/chat/completions",
5206            serde_json::json!({
5207                "model": "x",
5208                "messages": [{"role": "user", "content": "hi"}]
5209            }),
5210        )
5211        .await;
5212        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5213        assert_eq!(body["error"]["type"], "model_not_loaded");
5214    }
5215
5216    /// `/health` must keep answering with nothing loaded -- a supervisor
5217    /// polls it to decide whether to kill the process, and "no model"
5218    /// is not "no server".
5219    #[tokio::test]
5220    async fn health_reports_the_unloaded_state_rather_than_going_silent() {
5221        let state = Arc::new(test_state(
5222            named_test_model("model-a", 256),
5223            ResponseCache::new(4, Duration::from_secs(60)),
5224        ));
5225        let app = test_app_with_state(Arc::clone(&state));
5226        state.swap_active(None);
5227
5228        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
5229        // Not `ready`: a supervisor reading 200 here would route traffic
5230        // that is guaranteed to 503 on arrival.
5231        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5232        assert_eq!(body["state"], "unavailable");
5233        assert_eq!(body["reason"], "model_not_loaded");
5234        assert!(body["model"].is_null());
5235        let real_weights = body["capabilities"]
5236            .as_array()
5237            .unwrap()
5238            .iter()
5239            .find(|c| c["id"] == "real_weights")
5240            .cloned()
5241            .expect("real_weights is always reported");
5242        assert_eq!(real_weights["available"], false);
5243        assert_eq!(real_weights["reason"], "model_not_loaded");
5244    }
5245
5246    /// The API-monitor contract: a finished request lands in the ring
5247    /// buffer keyed by the id the response carried, with the two
5248    /// durations reported separately.
5249    #[tokio::test]
5250    async fn a_finished_request_lands_in_the_stats_ring_with_both_durations() {
5251        let app = test_app();
5252
5253        let (status, completion) = post_json_uri(
5254            &app,
5255            "/v1/chat/completions",
5256            serde_json::json!({
5257                "model": "x",
5258                "messages": [{"role": "user", "content": "hi"}],
5259                "max_tokens": 4
5260            }),
5261        )
5262        .await;
5263        assert_eq!(status, StatusCode::OK);
5264        let request_id = completion["request_id"].as_str().unwrap().to_string();
5265
5266        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5267        assert_eq!(status, StatusCode::OK);
5268        let recent = stats["recent"].as_array().unwrap();
5269        assert_eq!(recent.len(), 1);
5270        let row = &recent[0];
5271        assert_eq!(row["request_id"], request_id);
5272        assert_eq!(row["route"], frink_api::routes::V1_CHAT_COMPLETIONS);
5273        assert_eq!(row["status"], 200);
5274        assert_eq!(row["stream"], false);
5275        // Separate fields, and the decode phase is a real measurement
5276        // rather than a copy of the total.
5277        assert!(row["duration_ms"].is_number());
5278        assert!(row["decode_ms"].is_number());
5279        assert!(stats["tokens_generated_total"].as_u64().unwrap() > 0);
5280        assert_eq!(
5281            stats["tokens_prompt_total"].as_u64().unwrap(),
5282            row["prompt_tokens"].as_u64().unwrap()
5283        );
5284    }
5285
5286    /// A rejected request is still a request the monitor should show;
5287    /// otherwise the screen quietly omits exactly the traffic someone
5288    /// is debugging.
5289    #[tokio::test]
5290    async fn a_rejected_request_is_recorded_too() {
5291        let state = Arc::new(test_state(
5292            named_test_model("model-a", 256),
5293            ResponseCache::new(4, Duration::from_secs(60)),
5294        ));
5295        let app = test_app_with_state(Arc::clone(&state));
5296        state.swap_active(None);
5297
5298        let (status, _) = post_json_uri(
5299            &app,
5300            "/v1/chat/completions",
5301            serde_json::json!({"model": "x", "messages": [{"role": "user", "content": "hi"}]}),
5302        )
5303        .await;
5304        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5305
5306        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5307        let recent = stats["recent"].as_array().unwrap();
5308        assert_eq!(recent.len(), 1);
5309        assert_eq!(recent[0]["status"], 503);
5310        assert_eq!(recent[0]["completion_tokens"], 0);
5311        assert!(recent[0]["decode_ms"].is_null());
5312        assert_eq!(stats["errors_total"], 1);
5313    }
5314
5315    /// POSTs with caller-supplied headers, so the attribution tests
5316    /// exercise the same header parsing a real client's request goes
5317    /// through rather than calling `Attribution::from_headers` twice.
5318    async fn post_json_with_headers(
5319        app: &Router,
5320        uri: &str,
5321        body: serde_json::Value,
5322        headers: &[(&str, &str)],
5323    ) -> (StatusCode, serde_json::Value) {
5324        use http_body_util::BodyExt;
5325        use tower::ServiceExt;
5326
5327        let mut builder = axum::http::Request::builder()
5328            .method("POST")
5329            .uri(uri)
5330            .header("content-type", "application/json");
5331        for (name, value) in headers {
5332            builder = builder.header(*name, *value);
5333        }
5334        let response = app
5335            .clone()
5336            .oneshot(
5337                builder
5338                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5339                    .unwrap(),
5340            )
5341            .await
5342            .unwrap();
5343        let status = response.status();
5344        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5345        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
5346        (status, json)
5347    }
5348
5349    /// The three small endpoints used to be served and never recorded,
5350    /// which made the monitor wrong rather than incomplete: an editor
5351    /// hammering `/v1/embeddings` showed up as an idle server.
5352    #[tokio::test]
5353    async fn tokenize_detokenize_and_embeddings_all_land_in_the_ring() {
5354        let app = test_app();
5355
5356        let (status, _) = post_json_uri(
5357            &app,
5358            frink_api::routes::V1_TOKENIZE,
5359            serde_json::json!({"prompt": "hello"}),
5360        )
5361        .await;
5362        assert_eq!(status, StatusCode::OK);
5363        let (status, _) = post_json_uri(
5364            &app,
5365            frink_api::routes::V1_DETOKENIZE,
5366            serde_json::json!({"tokens": [104, 105]}),
5367        )
5368        .await;
5369        assert_eq!(status, StatusCode::OK);
5370        let (status, _) = post_json_uri(
5371            &app,
5372            frink_api::routes::V1_EMBEDDINGS,
5373            serde_json::json!({"input": "hello"}),
5374        )
5375        .await;
5376        assert_eq!(status, StatusCode::OK);
5377
5378        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5379        let routes: Vec<&str> = stats["recent"]
5380            .as_array()
5381            .unwrap()
5382            .iter()
5383            .map(|row| row["route"].as_str().unwrap())
5384            .collect();
5385        for expected in [
5386            frink_api::routes::V1_TOKENIZE,
5387            frink_api::routes::V1_DETOKENIZE,
5388            frink_api::routes::V1_EMBEDDINGS,
5389        ] {
5390            assert!(
5391                routes.contains(&expected),
5392                "{expected} is missing: {routes:?}"
5393            );
5394        }
5395
5396        let row = |route: &str| {
5397            stats["recent"]
5398                .as_array()
5399                .unwrap()
5400                .iter()
5401                .find(|r| r["route"] == route)
5402                .cloned()
5403                .unwrap()
5404        };
5405        // Embeddings run a forward pass, so their prompt tokens are
5406        // real prompt tokens. There is no decode loop, so `decode_ms`
5407        // stays null instead of borrowing the total.
5408        let embed = row(frink_api::routes::V1_EMBEDDINGS);
5409        assert!(embed["prompt_tokens"].as_u64().unwrap() > 0);
5410        assert!(embed["decode_ms"].is_null());
5411        assert_eq!(embed["completion_tokens"], 0);
5412        // Tokenizing runs the tokenizer and not the model, so it
5413        // contributes nothing to the token counters those counters
5414        // claim to measure.
5415        assert_eq!(row(frink_api::routes::V1_TOKENIZE)["prompt_tokens"], 0);
5416        assert_eq!(
5417            stats["tokens_prompt_total"].as_u64().unwrap(),
5418            embed["prompt_tokens"].as_u64().unwrap(),
5419            "only the forward pass counted"
5420        );
5421    }
5422
5423    /// A router over a model that is NOT flagged synthetic, so the
5424    /// decode loop actually emits chunks: `run_generation_emit`
5425    /// suppresses `emit` for a synthetic model, and a streaming test
5426    /// against one would see only the terminal frame.
5427    fn streaming_test_app() -> Router {
5428        let mut cfg = test_dense_fixture();
5429        cfg.vocab_size = 256;
5430        let model = Model::Gguf(GgufModel {
5431            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5432            tokenizer: Arc::new(ServerTokenizer::Byte),
5433            stop_tokens: StopTokens::default(),
5434            bos_id: None,
5435            is_synthetic: false,
5436            chat_template: chat_template::PromptTemplate::plain(),
5437        });
5438        test_app_with_state(Arc::new(test_state(
5439            model,
5440            ResponseCache::new(1000, Duration::from_secs(3600)),
5441        )))
5442    }
5443
5444    /// llama.cpp's native endpoint is a different WIRE, not a shorter
5445    /// path to the OpenAI one. If this ever starts answering `choices`,
5446    /// every llama.cpp client reading `content` breaks silently.
5447    /// Chat logprobs: the CHAT shape (`content[]` with `token`,
5448    /// `logprob`, `bytes` and a nested `top_logprobs`), not the
5449    /// completions wire's parallel arrays, and a request that asks for
5450    /// them must MISS the response cache -- which stores text and
5451    /// finish reasons, never distributions.
5452    #[tokio::test]
5453    async fn chat_logprobs_are_rendered_and_are_never_served_from_cache() {
5454        let app = test_app();
5455        let body = |logprobs: Option<(bool, Option<u32>)>| {
5456            let mut b = serde_json::json!({
5457                "model": "x",
5458                "messages": [{"role": "user", "content": "hi"}],
5459                "max_tokens": 4
5460            });
5461            if let Some((on, top)) = logprobs {
5462                b["logprobs"] = serde_json::json!(on);
5463                if let Some(n) = top {
5464                    b["top_logprobs"] = serde_json::json!(n);
5465                }
5466            }
5467            b
5468        };
5469
5470        // Without: absent, not an empty object.
5471        let (status, plain) =
5472            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(None)).await;
5473        assert_eq!(status, StatusCode::OK, "{plain}");
5474        assert!(plain["choices"][0]["logprobs"].is_null(), "{plain}");
5475
5476        // With: the chat object, and never a cache hit -- twice in a
5477        // row, because the second is exactly when a cacheable request
5478        // would replay.
5479        for attempt in 0..2 {
5480            let (status, with) = post_json_uri(
5481                &app,
5482                frink_api::routes::V1_CHAT_COMPLETIONS,
5483                body(Some((true, Some(2)))),
5484            )
5485            .await;
5486            assert_eq!(status, StatusCode::OK, "{with}");
5487            assert_ne!(
5488                with["frink_cache"], "hit",
5489                "attempt {attempt} replayed a cached answer for a logprobs request: {with}"
5490            );
5491            let lp = &with["choices"][0]["logprobs"];
5492            assert!(lp.is_object(), "attempt {attempt}: {with}");
5493            let content = lp["content"].as_array().expect("content");
5494            // It is the CHAT shape, so there are no parallel arrays.
5495            assert!(lp["tokens"].is_null(), "completions shape leaked: {lp}");
5496            for entry in content {
5497                assert!(entry["token"].is_string(), "{entry}");
5498                assert!(entry["bytes"].is_array(), "{entry}");
5499                let v = entry["logprob"].as_f64().expect("a real number");
5500                assert!(v <= 0.0 && v.is_finite(), "{entry}");
5501                let top = entry["top_logprobs"].as_array().expect("top_logprobs");
5502                assert!(top.len() <= 2, "asked for 2, got {}", top.len());
5503            }
5504        }
5505    }
5506
5507    /// `top_logprobs` without `logprobs: true` is not a valid request
5508    /// upstream, and is refused here rather than read as an implied
5509    /// `true` -- guessing which of two fields the caller meant is how
5510    /// a server answers a question nobody asked. A count above the cap
5511    /// is a 400 on the VALUE, not a 501 on the field.
5512    #[tokio::test]
5513    async fn the_chat_logprobs_pair_is_validated() {
5514        let app = test_app();
5515        for (extra, why) in [
5516            (serde_json::json!({"top_logprobs": 3}), "without logprobs"),
5517            (
5518                serde_json::json!({"logprobs": true, "top_logprobs": 21}),
5519                "above the cap",
5520            ),
5521        ] {
5522            let mut body = serde_json::json!({
5523                "model": "x",
5524                "messages": [{"role": "user", "content": "hi"}],
5525                "max_tokens": 2
5526            });
5527            for (k, v) in extra.as_object().unwrap() {
5528                body[k] = v.clone();
5529            }
5530            let (status, answer) =
5531                post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await;
5532            assert_eq!(status, StatusCode::BAD_REQUEST, "{why}: {answer}");
5533            assert!(
5534                answer["error"]["message"]
5535                    .as_str()
5536                    .is_some_and(|m| m.contains("top_logprobs")),
5537                "{why}: {answer}"
5538            );
5539        }
5540    }
5541
5542    /// `n` on the chat route: several choices from one prefill, each
5543    /// parsed for tool calls and reasoning in its own right, and the
5544    /// STREAMING pair refused by name because the choices would arrive
5545    /// one after another rather than interleaved by index.
5546    #[tokio::test]
5547    async fn chat_serves_several_choices_and_refuses_the_streaming_pair() {
5548        let app = test_app();
5549        let body = |n: u32, stream: bool| {
5550            serde_json::json!({
5551                "model": "x",
5552                "messages": [{"role": "user", "content": "hi"}],
5553                "max_tokens": 4,
5554                "temperature": 1.0,
5555                "n": n,
5556                "stream": stream
5557            })
5558        };
5559
5560        let (status, one) =
5561            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(1, false)).await;
5562        assert_eq!(status, StatusCode::OK, "{one}");
5563
5564        let (status, three) =
5565            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(3, false)).await;
5566        assert_eq!(status, StatusCode::OK, "{three}");
5567        let choices = three["choices"].as_array().expect("an array");
5568        assert_eq!(choices.len(), 3, "{three}");
5569        for (i, c) in choices.iter().enumerate() {
5570            assert_eq!(c["index"], i);
5571            assert!(c["message"]["role"].is_string(), "{c}");
5572            assert!(c["finish_reason"].is_string(), "{c}");
5573        }
5574        // One prompt, billed once: the prefill was shared.
5575        assert_eq!(
5576            three["usage"]["prompt_tokens"], one["usage"]["prompt_tokens"],
5577            "n = 3 billed the prompt more than once"
5578        );
5579
5580        // Streaming with several choices is refused BY NAME, not
5581        // collapsed to one.
5582        let (status, refused) =
5583            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(3, true)).await;
5584        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{refused}");
5585        let message = refused["error"]["message"].as_str().unwrap_or_default();
5586        assert!(
5587            message.contains('n') && message.contains("stream"),
5588            "{refused}"
5589        );
5590    }
5591
5592    /// The three generation routes must agree about every field this
5593    /// server does not implement. They did not: `n: 3` was a 501 on
5594    /// `/v1/chat/completions` and a 200 on `/v1/completions`, measured
5595    /// on a running server, because the chat route hand-wrote its own
5596    /// check and the other two never learned it.
5597    ///
5598    /// This is the test that would have caught that, and it is driven
5599    /// from one list so a field added to `unimplemented_fields` is
5600    /// checked on all three wires at once.
5601    #[tokio::test]
5602    async fn every_route_refuses_the_same_unimplemented_fields() {
5603        let app = test_app();
5604        let fields = [
5605            ("n", serde_json::json!(3)),
5606            ("best_of", serde_json::json!(2)),
5607            ("prompt_logprobs", serde_json::json!(1)),
5608            ("echo", serde_json::json!(true)),
5609            ("use_beam_search", serde_json::json!(true)),
5610            ("truncate_prompt_tokens", serde_json::json!(8)),
5611            ("prompt_embeds", serde_json::json!("AA==")),
5612            ("allowed_token_ids", serde_json::json!([1, 2])),
5613            ("bad_words", serde_json::json!(["x"])),
5614            ("skip_special_tokens", serde_json::json!(false)),
5615            ("return_tokens_as_token_ids", serde_json::json!(true)),
5616        ];
5617        for (field, value) in fields {
5618            for (uri, base) in [
5619                (
5620                    frink_api::routes::V1_CHAT_COMPLETIONS,
5621                    serde_json::json!({
5622                        "model": "x",
5623                        "messages": [{"role": "user", "content": "hi"}],
5624                        "max_tokens": 2
5625                    }),
5626                ),
5627                (
5628                    frink_api::routes::V1_COMPLETIONS,
5629                    serde_json::json!({"prompt": "hi", "max_tokens": 2}),
5630                ),
5631                (
5632                    frink_api::routes::COMPLETION,
5633                    serde_json::json!({"prompt": "hi", "n_predict": 2}),
5634                ),
5635            ] {
5636                let mut body = base;
5637                body[field] = value.clone();
5638                // `n` is SERVED where the response has a `choices`
5639                // array to carry the answers, which is the one
5640                // per-route exception in the table
5641                // (`unimplemented_fields::SERVES_SEVERAL_CHOICES`).
5642                if field == "n"
5643                    && (uri == frink_api::routes::V1_COMPLETIONS
5644                        || uri == frink_api::routes::V1_CHAT_COMPLETIONS)
5645                {
5646                    let (status, answer) = post_json_uri(&app, uri, body).await;
5647                    assert_eq!(
5648                        status,
5649                        StatusCode::OK,
5650                        "{uri} refused a served `n`: {answer}"
5651                    );
5652                    assert_eq!(
5653                        answer["choices"].as_array().map(Vec::len),
5654                        Some(3),
5655                        "{answer}"
5656                    );
5657                    continue;
5658                }
5659                let (status, answer) = post_json_uri(&app, uri, body).await;
5660                assert_eq!(
5661                    status,
5662                    StatusCode::NOT_IMPLEMENTED,
5663                    "{uri} served `{field}` instead of refusing it: {answer}"
5664                );
5665                assert!(
5666                    answer["error"]["message"]
5667                        .as_str()
5668                        .is_some_and(|m| m.contains(field)),
5669                    "{uri} refused `{field}` without naming it: {answer}"
5670                );
5671            }
5672        }
5673    }
5674
5675    #[tokio::test]
5676    async fn the_native_completion_wire_is_not_the_openai_one() {
5677        let app = test_app();
5678
5679        let (status, native) = post_json_uri(
5680            &app,
5681            frink_api::routes::COMPLETION,
5682            serde_json::json!({"prompt": "hi", "n_predict": 4}),
5683        )
5684        .await;
5685        assert_eq!(status, StatusCode::OK, "{native}");
5686        assert!(native["content"].is_string(), "{native}");
5687        assert_eq!(native["stop"], true);
5688        assert_eq!(native["stop_type"], "limit");
5689        assert_eq!(native["stopping_word"], "");
5690        assert_eq!(native["truncated"], false);
5691        assert_eq!(native["id_slot"], -1);
5692        assert!(native["timings"]["prompt_n"].is_number(), "{native}");
5693        assert!(native["generation_settings"]["n_predict"] == 4, "{native}");
5694        assert!(
5695            native.get("choices").is_none(),
5696            "the native shape has no `choices`: {native}"
5697        );
5698
5699        let (status, openai) = post_json_uri(
5700            &app,
5701            frink_api::routes::V1_COMPLETIONS,
5702            serde_json::json!({"prompt": "hi", "max_tokens": 4}),
5703        )
5704        .await;
5705        assert_eq!(status, StatusCode::OK);
5706        assert!(openai["choices"][0]["text"].is_string(), "{openai}");
5707        assert!(
5708            openai.get("content").is_none(),
5709            "the OpenAI shape has no top-level `content`: {openai}"
5710        );
5711    }
5712
5713    /// llama.cpp mounts the native endpoint under both spellings
5714    /// (`server.cpp:240-241`), and its own web UI uses the plural. One
5715    /// handler, so the two cannot answer differently.
5716    #[tokio::test]
5717    async fn both_native_spellings_reach_the_same_handler() {
5718        let app = test_app();
5719        for route in [
5720            frink_api::routes::COMPLETION,
5721            frink_api::routes::COMPLETIONS,
5722        ] {
5723            let (status, body) = post_json_uri(
5724                &app,
5725                route,
5726                serde_json::json!({"prompt": "hi", "n_predict": 2, "seed": 1}),
5727            )
5728            .await;
5729            assert_eq!(status, StatusCode::OK, "{route}: {body}");
5730            assert_eq!(body["stop"], true, "{route}");
5731            assert!(body["content"].is_string(), "{route}");
5732        }
5733
5734        // And the ring records which one was called, so the split
5735        // between clients stays visible.
5736        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5737        let routes: Vec<&str> = stats["recent"]
5738            .as_array()
5739            .unwrap()
5740            .iter()
5741            .map(|row| row["route"].as_str().unwrap())
5742            .collect();
5743        assert!(
5744            routes.contains(&frink_api::routes::COMPLETION),
5745            "{routes:?}"
5746        );
5747        assert!(
5748            routes.contains(&frink_api::routes::COMPLETIONS),
5749            "{routes:?}"
5750        );
5751    }
5752
5753    /// The native stream is not OpenAI's. Frames are bare objects with
5754    /// `content` and `stop`, the last one carries `stop: true` and the
5755    /// whole terminal body, and there is **no `[DONE]`** -- a client
5756    /// waiting for one would hang, and one that got it would try to
5757    /// parse it as JSON.
5758    #[tokio::test]
5759    async fn a_native_stream_ends_on_a_stop_frame_with_no_done_sentinel() {
5760        let app = streaming_test_app();
5761        let raw = post_sse_raw_uri(
5762            &app,
5763            frink_api::routes::COMPLETION,
5764            serde_json::json!({"prompt": "hi", "n_predict": 6, "stream": true, "seed": 7}),
5765        )
5766        .await;
5767
5768        assert!(
5769            !raw.contains("[DONE]"),
5770            "llama.cpp's native stream has no sentinel: {raw}"
5771        );
5772        let frames: Vec<serde_json::Value> = raw
5773            .lines()
5774            .filter_map(|line| line.strip_prefix("data: "))
5775            .map(|json| serde_json::from_str(json).expect("every frame is one JSON object"))
5776            .collect();
5777        assert!(frames.len() >= 2, "expected partials then a final: {raw}");
5778
5779        let (last, partials) = frames.split_last().unwrap();
5780        assert_eq!(last["stop"], true, "the last frame closes the stream");
5781        assert!(last["timings"].is_object(), "{last}");
5782        assert!(last["stop_type"].is_string(), "{last}");
5783        for partial in partials {
5784            assert_eq!(partial["stop"], false, "{partial}");
5785            assert!(partial["content"].is_string(), "{partial}");
5786            // Upstream's documented partial carries content/tokens/stop
5787            // and nothing else; the terminal fields belong to the last
5788            // frame only.
5789            assert!(partial.get("timings").is_none(), "{partial}");
5790            assert!(partial.get("generation_settings").is_none(), "{partial}");
5791        }
5792        // The concatenated partials are the answer, so a client that
5793        // streams sees what a client that buffers would get.
5794        let streamed: String = partials
5795            .iter()
5796            .filter_map(|p| p["content"].as_str())
5797            .collect();
5798        assert_eq!(last["content"].as_str().unwrap(), streamed);
5799    }
5800
5801    /// `n_predict: -1` is llama.cpp's default AND its "until the
5802    /// context is full". With no derived ceiling there is no context to
5803    /// be full of, and quietly substituting a small budget would hand a
5804    /// caller a truncated answer it never asked for.
5805    #[tokio::test]
5806    async fn an_unbounded_n_predict_is_refused_rather_than_quietly_shrunk() {
5807        let app = test_app();
5808        for body in [
5809            serde_json::json!({"prompt": "hi"}),
5810            serde_json::json!({"prompt": "hi", "n_predict": -1}),
5811        ] {
5812            let (status, refusal) =
5813                post_json_uri(&app, frink_api::routes::COMPLETION, body.clone()).await;
5814            assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}: {refusal}");
5815            assert!(
5816                refusal["error"]["message"]
5817                    .as_str()
5818                    .unwrap()
5819                    .contains("n_predict"),
5820                "{refusal}"
5821            );
5822        }
5823        // An explicit budget is served, so the refusal is about the
5824        // unbounded case and not about the endpoint.
5825        let (status, _) = post_json_uri(
5826            &app,
5827            frink_api::routes::COMPLETION,
5828            serde_json::json!({"prompt": "hi", "n_predict": 2}),
5829        )
5830        .await;
5831        assert_eq!(status, StatusCode::OK);
5832    }
5833
5834    /// A caller's `stop` must actually reach the sampler, and be named
5835    /// back in llama.cpp's own vocabulary. Dropping it is the dangerous
5836    /// silent failure: the caller believes generation halts at its
5837    /// sentinel and instead gets the whole budget of text past it.
5838    ///
5839    /// Deterministic without depending on what random weights say:
5840    /// generate once with no stop, then take a character out of that
5841    /// answer and demand the second run halt before it.
5842    #[tokio::test]
5843    async fn a_stop_string_halts_the_answer_and_is_named_back() {
5844        let app = streaming_test_app();
5845        let ask = |stop: serde_json::Value| {
5846            let app = app.clone();
5847            async move {
5848                post_json_uri(
5849                    &app,
5850                    frink_api::routes::COMPLETION,
5851                    serde_json::json!({
5852                        "prompt": "hi",
5853                        "n_predict": 64,
5854                        "ignore_eos": true,
5855                        "stop": stop,
5856                    }),
5857                )
5858                .await
5859                .1
5860            }
5861        };
5862
5863        let baseline = ask(serde_json::json!([])).await;
5864        assert_eq!(baseline["stop_type"], "limit");
5865        assert_eq!(baseline["stopping_word"], "");
5866        let text = baseline["content"].as_str().unwrap().to_string();
5867        // Two characters, so the sentinel is more than one token in
5868        // this vocabulary and goes through the output-suffix layer that
5869        // reports WHICH string matched. A single-token stop is caught
5870        // by the token layer, which does not carry the string back --
5871        // see `stop_type`'s note and docs/API.md.
5872        let sentinel: String = text.chars().skip(1).take(2).collect();
5873        assert_eq!(
5874            sentinel.chars().count(),
5875            2,
5876            "the fixture must produce enough output to cut: {text:?}"
5877        );
5878        let cut = text.find(&sentinel).expect("it came out of this text");
5879
5880        let stopped = ask(serde_json::json!([sentinel])).await;
5881        assert_eq!(stopped["stop_type"], "word", "{stopped}");
5882        assert_eq!(stopped["stopping_word"], sentinel);
5883        assert_eq!(
5884            stopped["content"].as_str().unwrap(),
5885            &text[..cut],
5886            "the answer must be cut at the sentinel, not run past it"
5887        );
5888    }
5889
5890    /// llama.cpp mounts these two unprefixed and sends `content`, not
5891    /// `prompt`. frink mounted only the `/v1/` spelling it invented,
5892    /// so every llama.cpp client got a 404 that named nothing. The
5893    /// alias must reach the SAME handler -- identical ids for identical
5894    /// text -- rather than a second implementation of it.
5895    #[tokio::test]
5896    async fn the_llama_cpp_spelling_of_tokenize_reaches_the_same_handler() {
5897        let app = test_app();
5898
5899        let (v1_status, v1) = post_json_uri(
5900            &app,
5901            frink_api::routes::V1_TOKENIZE,
5902            serde_json::json!({"prompt": "hello"}),
5903        )
5904        .await;
5905        let (alias_status, alias) = post_json_uri(
5906            &app,
5907            frink_api::routes::TOKENIZE,
5908            serde_json::json!({"content": "hello"}),
5909        )
5910        .await;
5911        assert_eq!(v1_status, StatusCode::OK);
5912        assert_eq!(alias_status, StatusCode::OK, "{alias}");
5913        assert_eq!(v1["tokens"], alias["tokens"]);
5914        assert!(!alias["tokens"].as_array().unwrap().is_empty());
5915
5916        // And the reverse: frink's own field still works on llama.cpp's
5917        // path, so a client that switches URLs need not switch dialects.
5918        let (status, both_ways) = post_json_uri(
5919            &app,
5920            frink_api::routes::TOKENIZE,
5921            serde_json::json!({"prompt": "hello"}),
5922        )
5923        .await;
5924        assert_eq!(status, StatusCode::OK);
5925        assert_eq!(both_ways["tokens"], v1["tokens"]);
5926    }
5927
5928    /// llama.cpp answers detokenize under `content`
5929    /// (`server-context.cpp:4970`); frink has always answered under
5930    /// `text`. Both keys carry the same string, so neither dialect's
5931    /// client reads a null.
5932    #[tokio::test]
5933    async fn detokenize_answers_under_both_dialects_keys() {
5934        let app = test_app();
5935        for route in [
5936            frink_api::routes::DETOKENIZE,
5937            frink_api::routes::V1_DETOKENIZE,
5938        ] {
5939            let (status, body) =
5940                post_json_uri(&app, route, serde_json::json!({"tokens": [104, 105]})).await;
5941            assert_eq!(status, StatusCode::OK, "{route}");
5942            assert_eq!(body["text"], "hi", "{route}");
5943            assert_eq!(body["content"], body["text"], "{route}");
5944        }
5945    }
5946
5947    /// The alias is one handler, so the ring must not attribute a
5948    /// llama.cpp client's traffic to the frink spelling: the row
5949    /// carries the path that was actually matched.
5950    #[tokio::test]
5951    async fn the_alias_is_recorded_under_the_path_the_client_called() {
5952        let app = test_app();
5953        let (status, _) = post_json_uri(
5954            &app,
5955            frink_api::routes::TOKENIZE,
5956            serde_json::json!({"content": "hello"}),
5957        )
5958        .await;
5959        assert_eq!(status, StatusCode::OK);
5960
5961        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5962        let routes: Vec<&str> = stats["recent"]
5963            .as_array()
5964            .unwrap()
5965            .iter()
5966            .map(|row| row["route"].as_str().unwrap())
5967            .collect();
5968        assert!(
5969            routes.contains(&frink_api::routes::TOKENIZE),
5970            "the alias must be its own row: {routes:?}"
5971        );
5972        assert!(
5973            !routes.contains(&frink_api::routes::V1_TOKENIZE),
5974            "nothing called /v1/tokenize: {routes:?}"
5975        );
5976    }
5977
5978    /// `add_special` is llama.cpp's "prepend BOS". Honoured, and with
5979    /// the id the generation path itself would prepend -- a tokenize
5980    /// endpoint that disagrees with the decoder about the prompt is
5981    /// worse than one that has no such option.
5982    #[tokio::test]
5983    async fn add_special_prepends_the_same_bos_the_decoder_would() {
5984        let mut cfg = test_dense_fixture();
5985        cfg.vocab_size = 256;
5986        let model = Model::Gguf(GgufModel {
5987            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5988            tokenizer: Arc::new(ServerTokenizer::Byte),
5989            stop_tokens: StopTokens::default(),
5990            bos_id: Some(7),
5991            is_synthetic: true,
5992            chat_template: chat_template::PromptTemplate::plain(),
5993        });
5994        let app = test_app_with_state(Arc::new(test_state(
5995            model,
5996            ResponseCache::new(1000, Duration::from_secs(3600)),
5997        )));
5998
5999        let (_, plain) = post_json_uri(
6000            &app,
6001            frink_api::routes::TOKENIZE,
6002            serde_json::json!({"content": "hi"}),
6003        )
6004        .await;
6005        let (_, special) = post_json_uri(
6006            &app,
6007            frink_api::routes::TOKENIZE,
6008            serde_json::json!({"content": "hi", "add_special": true}),
6009        )
6010        .await;
6011
6012        assert_eq!(plain["tokens"], serde_json::json!([104, 105]));
6013        assert_eq!(special["tokens"], serde_json::json!([7, 104, 105]));
6014        assert_eq!(special["count"], 3);
6015    }
6016
6017    /// A failed small-endpoint call is still traffic. A 400 that leaves
6018    /// no row is indistinguishable from a request that was never sent.
6019    #[tokio::test]
6020    async fn a_rejected_embeddings_request_is_recorded_with_its_status() {
6021        let app = test_app();
6022        let (status, _) = post_json_uri(
6023            &app,
6024            frink_api::routes::V1_EMBEDDINGS,
6025            serde_json::json!({"input": "hi", "encoding_format": "base64"}),
6026        )
6027        .await;
6028        assert_eq!(status, StatusCode::BAD_REQUEST);
6029
6030        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6031        let recent = stats["recent"].as_array().unwrap();
6032        assert_eq!(recent.len(), 1);
6033        assert_eq!(recent[0]["route"], frink_api::routes::V1_EMBEDDINGS);
6034        assert_eq!(recent[0]["status"], 400);
6035        assert_eq!(
6036            recent[0]["prompt_tokens"], 0,
6037            "a rejected call embedded nothing"
6038        );
6039    }
6040
6041    /// Attribution: which key served a request, and what the caller
6042    /// says it is. The key itself must never appear.
6043    #[tokio::test]
6044    async fn a_row_names_the_key_that_served_it_without_carrying_the_key() {
6045        let app = test_app();
6046        let key = "sk-monitor-secret";
6047        let (status, _) = post_json_with_headers(
6048            &app,
6049            "/v1/chat/completions",
6050            serde_json::json!({
6051                "model": "x",
6052                "messages": [{"role": "user", "content": "hi"}],
6053                "max_tokens": 2
6054            }),
6055            &[
6056                ("authorization", &format!("Bearer {key}")),
6057                ("x-frink-client", "frink-studio"),
6058            ],
6059        )
6060        .await;
6061        assert_eq!(status, StatusCode::OK);
6062
6063        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6064        let row = stats["recent"].as_array().unwrap()[0].clone();
6065        let fingerprint = row["via_api_key"]
6066            .as_str()
6067            .expect("the row names the key that served it")
6068            .to_string();
6069        assert_eq!(fingerprint, attribution::key_fingerprint(key));
6070        assert!(!fingerprint.contains(key));
6071        assert!(
6072            !serde_json::to_string(&stats).unwrap().contains(key),
6073            "the stats payload must not carry the key in any form"
6074        );
6075        assert_eq!(row["client"], "frink-studio");
6076    }
6077
6078    /// Two different keys are two different callers, and no key at all
6079    /// is a third answer -- not a copy of either.
6080    #[tokio::test]
6081    async fn different_keys_are_different_callers_and_no_key_is_null() {
6082        let app = test_app();
6083        let body = serde_json::json!({
6084            "model": "x",
6085            "messages": [{"role": "user", "content": "hi"}],
6086            "max_tokens": 1
6087        });
6088        for headers in [
6089            vec![("authorization", "Bearer key-one")],
6090            vec![("authorization", "Bearer key-two")],
6091            vec![],
6092        ] {
6093            let (status, _) =
6094                post_json_with_headers(&app, "/v1/chat/completions", body.clone(), &headers).await;
6095            assert_eq!(status, StatusCode::OK);
6096        }
6097
6098        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6099        let recent = stats["recent"].as_array().unwrap();
6100        assert_eq!(recent.len(), 3);
6101        let one = recent[0]["via_api_key"].as_str().unwrap();
6102        let two = recent[1]["via_api_key"].as_str().unwrap();
6103        assert_ne!(one, two, "two keys must not collapse into one caller");
6104        assert!(
6105            recent[2]["via_api_key"].is_null(),
6106            "an unauthenticated call is null, not a fingerprint of nothing"
6107        );
6108        assert!(recent[2]["client"].is_null());
6109    }
6110
6111    /// The row names the model that SERVED the request. `req.model` is
6112    /// ignored by this server -- it decodes against whatever is loaded
6113    /// -- so echoing that string back would make the log agree with the
6114    /// caller's belief instead of with what happened.
6115    #[tokio::test]
6116    async fn a_row_names_the_model_that_served_it_not_the_one_requested() {
6117        let state = Arc::new(test_state(
6118            named_test_model("really-loaded", 256),
6119            ResponseCache::new(4, Duration::from_secs(60)),
6120        ));
6121        let app = test_app_with_state(Arc::clone(&state));
6122
6123        let (status, _) = post_json_uri(
6124            &app,
6125            "/v1/chat/completions",
6126            serde_json::json!({
6127                "model": "gpt-4-turbo-that-is-not-here",
6128                "messages": [{"role": "user", "content": "hi"}],
6129                "max_tokens": 2
6130            }),
6131        )
6132        .await;
6133        assert_eq!(status, StatusCode::OK);
6134
6135        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6136        assert_eq!(stats["recent"][0]["model"], "really-loaded");
6137
6138        // Nothing loaded: nothing served it, and the row says so rather
6139        // than repeating what the request asked for.
6140        state.swap_active(None);
6141        let (status, _) = post_json_uri(
6142            &app,
6143            "/v1/chat/completions",
6144            serde_json::json!({
6145                "model": "gpt-4-turbo-that-is-not-here",
6146                "messages": [{"role": "user", "content": "hi"}]
6147            }),
6148        )
6149        .await;
6150        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
6151        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6152        let recent = stats["recent"].as_array().unwrap();
6153        assert!(recent[recent.len() - 1]["model"].is_null());
6154    }
6155
6156    /// A streamed request names its model too, and names the handle it
6157    /// decoded against rather than whatever a swap made current while it
6158    /// was running.
6159    #[tokio::test]
6160    async fn a_streamed_row_names_the_model_it_decoded_against() {
6161        let state = Arc::new(test_state(
6162            named_test_model("model-before", 256),
6163            ResponseCache::new(4, Duration::from_secs(60)),
6164        ));
6165        let app = test_app_with_state(Arc::clone(&state));
6166        let _ = post_sse_raw(&app, resumable_request()).await;
6167        // The stream has finished; a swap now must not rewrite history.
6168        active_model(&state, "model-after");
6169
6170        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6171        assert_eq!(stats["recent"][0]["model"], "model-before");
6172    }
6173
6174    /// The queue gauge reports a queue that exists or says there is
6175    /// none. `0` would claim an empty queue was measured.
6176    #[tokio::test]
6177    async fn the_queue_gauge_is_null_when_nothing_can_queue() {
6178        let app = test_app();
6179        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6180        assert_eq!(status, StatusCode::OK);
6181        assert!(
6182            stats["queue_depth"].is_null(),
6183            "without continuous batching nothing queues, so there is nothing to measure"
6184        );
6185        assert!(stats["queue_rejected_total"].is_null());
6186        assert_eq!(
6187            stats["generating_now"], 0,
6188            "work in progress is measured and really is zero here"
6189        );
6190    }
6191
6192    /// The raw SSE body, so the tests below can assert on the `id:` and
6193    /// `retry:` fields themselves rather than only on the JSON inside
6194    /// `data:`. Those two fields are the whole of the replay contract
6195    /// on the wire.
6196    async fn post_sse_raw(app: &Router, body: serde_json::Value) -> String {
6197        post_sse_raw_uri(app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await
6198    }
6199
6200    /// The same, on any route: `/completion` streams a different
6201    /// protocol over the same transport, and a second copy of this
6202    /// helper would be a second thing to keep in step.
6203    async fn post_sse_raw_uri(app: &Router, uri: &str, body: serde_json::Value) -> String {
6204        use http_body_util::BodyExt;
6205        use tower::ServiceExt;
6206
6207        let response = app
6208            .clone()
6209            .oneshot(
6210                axum::http::Request::builder()
6211                    .method("POST")
6212                    .uri(uri)
6213                    .header("content-type", "application/json")
6214                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
6215                    .unwrap(),
6216            )
6217            .await
6218            .unwrap();
6219        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6220        String::from_utf8(bytes.to_vec()).unwrap()
6221    }
6222
6223    async fn get_json_with_headers(
6224        app: &Router,
6225        uri: &str,
6226        headers: &[(&str, &str)],
6227    ) -> (StatusCode, serde_json::Value) {
6228        use http_body_util::BodyExt;
6229        use tower::ServiceExt;
6230
6231        let mut builder = axum::http::Request::builder().method("GET").uri(uri);
6232        for (name, value) in headers {
6233            builder = builder.header(*name, *value);
6234        }
6235        let response = app
6236            .clone()
6237            .oneshot(builder.body(axum::body::Body::empty()).unwrap())
6238            .await
6239            .unwrap();
6240        let status = response.status();
6241        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6242        (
6243            status,
6244            serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({})),
6245        )
6246    }
6247
6248    fn sse_field<'a>(body: &'a str, field: &str) -> Vec<&'a str> {
6249        body.lines()
6250            .filter_map(|line| line.strip_prefix(field))
6251            .map(str::trim)
6252            .collect()
6253    }
6254
6255    fn resumable_request() -> serde_json::Value {
6256        serde_json::json!({
6257            "model": "m",
6258            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6259            "max_tokens": 4,
6260            "temperature": 0,
6261            "stream": true,
6262            "stream_resumable": true,
6263        })
6264    }
6265
6266    /// The wire half of the replay contract: every event is numbered,
6267    /// the numbers are qualified by the request so a `Last-Event-ID`
6268    /// cannot be mistaken for a position in another stream, and the
6269    /// reconnect delay is stated once.
6270    #[tokio::test]
6271    async fn a_resumable_stream_numbers_every_event_and_states_retry_once() {
6272        let app = test_app();
6273        let body = post_sse_raw(&app, resumable_request()).await;
6274
6275        let request_id = body
6276            .lines()
6277            .find_map(|l| l.strip_prefix("data: "))
6278            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
6279            .and_then(|v| v["request_id"].as_str().map(str::to_string))
6280            .expect("the first chunk names the request");
6281
6282        let ids = sse_field(&body, "id:");
6283        let datas = sse_field(&body, "data:");
6284        assert_eq!(
6285            ids.len(),
6286            datas.len(),
6287            "every event carries an id, or a reconnect cannot name where it stopped"
6288        );
6289        for (i, id) in ids.iter().enumerate() {
6290            assert_eq!(*id, format!("{request_id}:{i}"));
6291        }
6292        let retries = sse_field(&body, "retry:");
6293        assert_eq!(
6294            retries.len(),
6295            1,
6296            "the reconnect delay is stated once, not on every event"
6297        );
6298        assert_eq!(retries[0], "1500");
6299        assert!(
6300            body.contains("data: [DONE]"),
6301            "the end of stream is still stated"
6302        );
6303    }
6304
6305    /// The refusal this feature was written around: an `id:` with no
6306    /// replay buffer behind it tells a client it may reconnect into
6307    /// something that does not exist.
6308    #[tokio::test]
6309    async fn a_plain_stream_carries_no_id_because_nothing_could_replay_it() {
6310        let app = test_app();
6311        let mut request = resumable_request();
6312        request["stream_resumable"] = serde_json::json!(false);
6313        let body = post_sse_raw(&app, request).await;
6314        assert!(!sse_field(&body, "data:").is_empty(), "it still streams");
6315        assert!(
6316            sse_field(&body, "id:").is_empty(),
6317            "an id promises a replay this stream cannot serve"
6318        );
6319        assert!(sse_field(&body, "retry:").is_empty());
6320    }
6321
6322    /// The polling fallback, which is the answer to the proxy that
6323    /// buffers `text/event-stream`: the same events, over a short JSON
6324    /// response nothing can hold back.
6325    #[tokio::test]
6326    async fn the_polling_fallback_serves_exactly_what_the_stream_delivered() {
6327        let app = test_app();
6328        let body = post_sse_raw(&app, resumable_request()).await;
6329        let request_id = sse_field(&body, "id:")[0]
6330            .rsplit_once(':')
6331            .unwrap()
6332            .0
6333            .to_string();
6334        let streamed: Vec<String> = sse_field(&body, "data:")
6335            .iter()
6336            .map(|d| d.to_string())
6337            .collect();
6338
6339        let (status, polled) = get_json(
6340            &app,
6341            &format!("{}?from=0", frink_api::routes::v1_stream_poll(&request_id)),
6342        )
6343        .await;
6344        assert_eq!(status, StatusCode::OK);
6345        let events: Vec<String> = polled["events"]
6346            .as_array()
6347            .unwrap()
6348            .iter()
6349            .map(|e| e["data"].as_str().unwrap().to_string())
6350            .collect();
6351        assert_eq!(
6352            events, streamed,
6353            "the fallback must deliver the same answer, not a re-run of it"
6354        );
6355        assert_eq!(polled["request_id"], request_id);
6356        assert_eq!(
6357            polled["done"], false,
6358            "events were still being handed out, so the client must ask again"
6359        );
6360
6361        // Drained: only now is it done, so a client that stops on
6362        // `done` never discards events it was not given.
6363        let next = polled["next_index"].as_u64().unwrap();
6364        let (_, drained) = get_json(
6365            &app,
6366            &format!(
6367                "{}?from={next}",
6368                frink_api::routes::v1_stream_poll(&request_id)
6369            ),
6370        )
6371        .await;
6372        assert_eq!(drained["done"], true);
6373        assert_eq!(drained["events"].as_array().unwrap().len(), 0);
6374    }
6375
6376    /// A resume returns what was missed and not what was already
6377    /// rendered -- repeating delivered tokens would make replay worse
6378    /// than starting over.
6379    #[tokio::test]
6380    async fn a_resume_continues_after_the_last_event_id_rather_than_repeating() {
6381        let app = test_app();
6382        let body = post_sse_raw(&app, resumable_request()).await;
6383        let ids = sse_field(&body, "id:");
6384        let datas: Vec<String> = sse_field(&body, "data:")
6385            .iter()
6386            .map(|d| d.to_string())
6387            .collect();
6388        assert!(
6389            ids.len() >= 3,
6390            "need a few events to resume into the middle"
6391        );
6392        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
6393
6394        let (status, resumed) = get_json_with_headers(
6395            &app,
6396            &format!("{}/poll", frink_api::routes::v1_stream(&request_id)),
6397            &[],
6398        )
6399        .await;
6400        assert_eq!(status, StatusCode::OK);
6401        assert_eq!(resumed["events"].as_array().unwrap().len(), datas.len());
6402
6403        // Now from the middle, the way a reconnect would.
6404        let (_, tail) = get_json(
6405            &app,
6406            &format!("{}?from=2", frink_api::routes::v1_stream_poll(&request_id)),
6407        )
6408        .await;
6409        let tail_events: Vec<String> = tail["events"]
6410            .as_array()
6411            .unwrap()
6412            .iter()
6413            .map(|e| e["data"].as_str().unwrap().to_string())
6414            .collect();
6415        assert_eq!(tail_events, datas[2..].to_vec());
6416    }
6417
6418    /// Reconnecting over SSE picks up where the last id left off, with
6419    /// the ids still attached so a second drop can be resumed too.
6420    #[tokio::test]
6421    async fn an_sse_reconnect_resumes_from_the_last_event_id() {
6422        use http_body_util::BodyExt;
6423        use tower::ServiceExt;
6424
6425        let app = test_app();
6426        let body = post_sse_raw(&app, resumable_request()).await;
6427        let ids = sse_field(&body, "id:");
6428        let datas: Vec<String> = sse_field(&body, "data:")
6429            .iter()
6430            .map(|d| d.to_string())
6431            .collect();
6432        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
6433
6434        let response = app
6435            .clone()
6436            .oneshot(
6437                axum::http::Request::builder()
6438                    .method("GET")
6439                    .uri(frink_api::routes::v1_stream(&request_id))
6440                    .header("last-event-id", format!("{request_id}:0"))
6441                    .body(axum::body::Body::empty())
6442                    .unwrap(),
6443            )
6444            .await
6445            .unwrap();
6446        assert_eq!(response.status(), StatusCode::OK);
6447        assert_eq!(
6448            response
6449                .headers()
6450                .get("x-accel-buffering")
6451                .and_then(|v| v.to_str().ok()),
6452            Some("no"),
6453            "the reconnect needs the same anti-buffering header as the stream"
6454        );
6455        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6456        let resumed = String::from_utf8(bytes.to_vec()).unwrap();
6457        assert_eq!(
6458            sse_field(&resumed, "data:")
6459                .iter()
6460                .map(|d| d.to_string())
6461                .collect::<Vec<_>>(),
6462            datas[1..].to_vec()
6463        );
6464        assert_eq!(sse_field(&resumed, "id:")[0], format!("{request_id}:1"));
6465    }
6466
6467    /// A `Last-Event-ID` from another stream is refused rather than
6468    /// rounded down to zero: replaying a whole different answer would
6469    /// be a silent, confident lie.
6470    #[tokio::test]
6471    async fn a_last_event_id_from_another_stream_is_refused() {
6472        let app = test_app();
6473        let body = post_sse_raw(&app, resumable_request()).await;
6474        let request_id = sse_field(&body, "id:")[0]
6475            .rsplit_once(':')
6476            .unwrap()
6477            .0
6478            .to_string();
6479
6480        let (status, err) = get_json_with_headers(
6481            &app,
6482            &frink_api::routes::v1_stream(&request_id),
6483            &[("last-event-id", "chatcmpl-someone-else:3")],
6484        )
6485        .await;
6486        assert_eq!(status, StatusCode::BAD_REQUEST);
6487        assert_eq!(err["error"]["code"], "bad_last_event_id");
6488    }
6489
6490    /// A stream that was never resumable, or has been forgotten, is a
6491    /// 404 that says which -- not an empty stream that reads as an
6492    /// answer with no tokens in it.
6493    #[tokio::test]
6494    async fn resuming_a_stream_that_was_never_resumable_is_a_404_that_says_why() {
6495        let app = test_app();
6496        let mut request = resumable_request();
6497        request["stream_resumable"] = serde_json::json!(false);
6498        let body = post_sse_raw(&app, request).await;
6499        let request_id = body
6500            .lines()
6501            .find_map(|l| l.strip_prefix("data: "))
6502            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
6503            .and_then(|v| v["request_id"].as_str().map(str::to_string))
6504            .unwrap();
6505
6506        let (status, err) = get_json(&app, &frink_api::routes::v1_stream_poll(&request_id)).await;
6507        assert_eq!(status, StatusCode::NOT_FOUND);
6508        assert_eq!(err["error"]["code"], "stream_not_found");
6509        assert!(err["error"]["message"]
6510            .as_str()
6511            .unwrap()
6512            .contains("stream_resumable"));
6513    }
6514
6515    /// The published template and the router's pattern must describe
6516    /// the same path, or a client built from `frink_api::routes` asks
6517    /// for something this server does not serve.
6518    #[test]
6519    fn the_axum_stream_patterns_match_the_published_templates() {
6520        assert_eq!(
6521            axum_path(frink_api::routes::V1_STREAM),
6522            "/v1/stream/:request_id"
6523        );
6524        assert_eq!(
6525            axum_path(frink_api::routes::V1_STREAM_POLL),
6526            "/v1/stream/:request_id/poll"
6527        );
6528        assert_eq!(
6529            frink_api::routes::v1_stream("abc"),
6530            axum_path(frink_api::routes::V1_STREAM).replace(":request_id", "abc")
6531        );
6532    }
6533
6534    /// Every published template goes through the converter, and what
6535    /// comes out has no braces left in it.
6536    ///
6537    /// The two Responses routes were mounted raw, so axum matched the
6538    /// literal segment `{response_id}` and a real id fell through to a
6539    /// bodiless 404. The test router had the same two lines, which is
6540    /// why nothing caught it. This walks the templates instead of
6541    /// naming them, so the next one added is covered without anybody
6542    /// remembering to come back here.
6543    #[test]
6544    fn no_published_template_reaches_the_router_with_its_braces() {
6545        for template in [
6546            frink_api::routes::V1_STREAM,
6547            frink_api::routes::V1_STREAM_POLL,
6548            frink_api::routes::V1_RESPONSE,
6549            frink_api::routes::V1_RESPONSE_CANCEL,
6550            frink_api::routes::ADMIN_TASK_CANCEL,
6551        ] {
6552            assert!(
6553                template.contains('{'),
6554                "{template} is in the template list but has no placeholder"
6555            );
6556            let mounted = axum_path(template);
6557            assert!(
6558                !mounted.contains('{') && !mounted.contains('}'),
6559                "{template} would be mounted as {mounted}, whose braces axum reads as a literal segment"
6560            );
6561            assert!(
6562                mounted.contains(':'),
6563                "{template} lost its placeholder entirely and would match one path only"
6564            );
6565        }
6566    }
6567
6568    /// A real id must reach the handler, not axum's catch-all 404.
6569    ///
6570    /// The distinction is the whole point: axum answers an unmatched
6571    /// path with an empty body, while the handler answers an unknown id
6572    /// with a reasoned JSON error. Asserting on the body rather than
6573    /// the status is what separates "the route is missing" from "the
6574    /// response is not here".
6575    #[tokio::test]
6576    async fn an_unknown_response_id_gets_the_handler_not_a_bare_404() {
6577        let app = test_app();
6578        let (status, body) = get_json(&app, "/v1/responses/resp_nonexistent").await;
6579        assert_eq!(status, StatusCode::NOT_FOUND);
6580        assert!(
6581            !body.is_null(),
6582            "empty body means axum never matched the route, so the id was read as a literal segment"
6583        );
6584    }
6585
6586    /// An empty task list is a list, not a missing key -- the UI renders
6587    /// "no jobs" from it rather than from an error.
6588    #[tokio::test]
6589    async fn the_task_list_starts_empty_rather_than_absent() {
6590        let app = test_app();
6591        let (status, body) = get_json(&app, frink_api::routes::ADMIN_TASKS).await;
6592        assert_eq!(status, StatusCode::OK);
6593        assert_eq!(body["tasks"].as_array().unwrap().len(), 0);
6594    }
6595
6596    /// The slots route exists, is reachable, and refuses by naming the
6597    /// flag that would turn it on -- rather than 404ing, which is what
6598    /// an unregistered route would do and is indistinguishable from
6599    /// "this build has no slots".
6600    ///
6601    /// The condition is reachable by default: `FRINK_SLOT_SAVE_PATH`
6602    /// is unset unless an operator passes `--slot-save-path`, so this
6603    /// is the answer every stock server gives.
6604    #[tokio::test]
6605    async fn the_slots_route_is_registered_and_refuses_by_naming_slot_save_path() {
6606        assert!(
6607            std::env::var("FRINK_SLOT_SAVE_PATH").is_err(),
6608            "this test asserts the unconfigured behaviour"
6609        );
6610        let app = test_app();
6611        let (status, body) = post_json_uri(
6612            &app,
6613            &format!("{}?action=save", frink_api::routes::slots_id(0)),
6614            serde_json::json!({"filename": "sys.fslot", "prompt": "hi"}),
6615        )
6616        .await;
6617        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
6618        assert!(
6619            body["error"]["message"]
6620                .as_str()
6621                .unwrap()
6622                .contains("--slot-save-path"),
6623            "{body}"
6624        );
6625    }
6626
6627    pub(crate) async fn post_json_uri(
6628        app: &Router,
6629        uri: &str,
6630        body: serde_json::Value,
6631    ) -> (StatusCode, serde_json::Value) {
6632        use http_body_util::BodyExt;
6633        use tower::ServiceExt;
6634
6635        let response = app
6636            .clone()
6637            .oneshot(
6638                axum::http::Request::builder()
6639                    .method("POST")
6640                    .uri(uri)
6641                    .header("content-type", "application/json")
6642                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
6643                    .unwrap(),
6644            )
6645            .await
6646            .unwrap();
6647        let status = response.status();
6648        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6649        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
6650        (status, json)
6651    }
6652
6653    async fn post_json(app: &Router, body: serde_json::Value) -> serde_json::Value {
6654        post_json_uri(app, "/v1/chat/completions", body).await.1
6655    }
6656
6657    /// The engine's live footprint, beside the budget it was sized
6658    /// against. Two things are asserted rather than the number itself,
6659    /// which is a property of the host: it is never a ZERO (an engine
6660    /// using no memory is not a thing that happens, so a zero would be
6661    /// a failed read presented as a fact), and it always says WHICH
6662    /// quantity it is -- a caller comparing a PSS figure with an RSS
6663    /// one is comparing two different things and will read the
6664    /// difference as a leak.
6665    #[tokio::test]
6666    async fn stats_says_what_the_engine_is_using_and_which_quantity_that_is() {
6667        let app = test_app();
6668        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
6669        assert_eq!(status, StatusCode::OK);
6670
6671        let memory = &body["memory"];
6672        if memory.is_null() {
6673            // No `/proc`: absent is the honest answer, and the point of
6674            // this branch is that it is absent rather than zero.
6675            return;
6676        }
6677        assert!(
6678            memory["bytes"].as_u64().is_some_and(|b| b > 0),
6679            "a read that produced a zero is a broken read, not an idle \
6680             engine: {memory}"
6681        );
6682        assert!(
6683            ["pss", "rss"].contains(&memory["kind"].as_str().unwrap_or("")),
6684            "the quantity must travel with the number: {memory}"
6685        );
6686    }
6687
6688    /// A pool this deployment does not have is reported `null`, never
6689    /// as a zero row. "No window pool" and "a window pool with nothing
6690    /// in it" are different facts, and an operator shown the second for
6691    /// the first sizes against a pool that does not exist. The test
6692    /// state runs with no shared KV pool, so all three are absent here.
6693    #[tokio::test]
6694    async fn stats_reports_a_pool_it_does_not_have_as_absent_and_not_as_zero() {
6695        let app = test_app();
6696        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
6697        assert_eq!(status, StatusCode::OK);
6698        for pool in ["kv_pages", "window_slots", "state_slots"] {
6699            assert!(
6700                body["pools"][pool].is_null(),
6701                "{pool} must be null rather than a zero row: {}",
6702                body["pools"]
6703            );
6704        }
6705    }
6706
6707    /// A streamed `/v1/messages` can be cancelled only if the client
6708    /// can learn the id, and the Anthropic protocol has no field for
6709    /// it -- the `message_start` `msg_...` is a different identifier
6710    /// the cancel registry has never seen. So the header carries it,
6711    /// on the success path and on the error path alike, because a
6712    /// client that logs one id per call should not lose it exactly
6713    /// when something went wrong.
6714    #[tokio::test]
6715    async fn a_messages_response_states_the_id_that_v1_cancel_takes() {
6716        use http_body_util::BodyExt;
6717        use tower::ServiceExt;
6718
6719        let app = test_app();
6720        let send = |body: serde_json::Value| {
6721            let app = app.clone();
6722            async move {
6723                app.oneshot(
6724                    axum::http::Request::builder()
6725                        .method("POST")
6726                        .uri(frink_api::routes::V1_MESSAGES)
6727                        .header("content-type", "application/json")
6728                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
6729                        .unwrap(),
6730                )
6731                .await
6732                .unwrap()
6733            }
6734        };
6735
6736        let ok = send(serde_json::json!({
6737            "model": "test",
6738            "max_tokens": 1,
6739            "messages": [{"role": "user", "content": "hi"}],
6740        }))
6741        .await;
6742        assert_eq!(ok.status(), StatusCode::OK);
6743        let id = ok
6744            .headers()
6745            .get("request-id")
6746            .expect("a served message names its id")
6747            .to_str()
6748            .unwrap()
6749            .to_string();
6750        assert!(!id.is_empty());
6751
6752        // A rejected body still gets one, and a different one: two calls
6753        // must never collide in the ring.
6754        let bad = send(serde_json::json!({"model": "test"})).await;
6755        assert!(bad.status().is_client_error());
6756        let other = bad.headers().get("request-id").expect("errors too");
6757        assert_ne!(other.to_str().unwrap(), id);
6758        let _ = bad.into_body().collect().await.unwrap();
6759    }
6760
6761    /// The gate is the point of the rebuild endpoint: a request that
6762    /// arrives while the KV pool is being re-split must be refused,
6763    /// because admitting it would let a decode allocate out of a pool
6764    /// whose block count is about to change under it. `503` and not
6765    /// `500` -- the caller should retry in a moment, and the body says
6766    /// which of the four closed states it hit so a client can tell
6767    /// "not yet" from "not ever".
6768    #[tokio::test]
6769    async fn a_request_that_arrives_mid_rebuild_is_refused_and_admitted_again_after() {
6770        let state = Arc::new(test_state(
6771            test_model_full_byte_vocab(),
6772            ResponseCache::new(1000, Duration::from_secs(3600)),
6773        ));
6774        let app = test_app_with_state(Arc::clone(&state));
6775        let body = serde_json::json!({
6776            "model": "test",
6777            "messages": [{"role": "user", "content": "hi"}],
6778            "max_tokens": 1,
6779        });
6780
6781        state
6782            .maintenance
6783            .lock()
6784            .unwrap()
6785            .begin_rebuild()
6786            .expect("a fresh server is serving, so the rebuild starts");
6787        let (status, refused) = post_json_uri(&app, "/v1/chat/completions", body.clone()).await;
6788        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
6789        assert_eq!(refused["error"]["type"], "cache_rebuilding");
6790
6791        state.maintenance.lock().unwrap().finish_rebuild(true);
6792        let (status, _) = post_json_uri(&app, "/v1/chat/completions", body).await;
6793        assert_eq!(
6794            status,
6795            StatusCode::OK,
6796            "the gate reopens; a rebuild is not a latch"
6797        );
6798    }
6799
6800    /// Cancelling an id that is not generating must not answer `200`.
6801    /// A UI told "ok" for an already-finished request would report that
6802    /// it stopped work it did not stop, and the two outcomes are the
6803    /// only thing this endpoint exists to distinguish.
6804    #[tokio::test]
6805    async fn cancelling_an_id_that_is_not_generating_is_a_404_that_says_so() {
6806        let app = test_app();
6807        let (status, body) = post_json_uri(
6808            &app,
6809            frink_api::routes::V1_CANCEL,
6810            serde_json::json!({ "request_id": "chatcmpl-never-issued" }),
6811        )
6812        .await;
6813        assert_eq!(status, StatusCode::NOT_FOUND);
6814        assert_eq!(body["cancelled"], serde_json::json!(false));
6815        assert_eq!(body["request_id"], "chatcmpl-never-issued");
6816        assert!(
6817            body["detail"].as_str().is_some_and(|d| !d.is_empty()),
6818            "the verdict must carry a human reason: {body}"
6819        );
6820    }
6821
6822    /// The endpoint reaches the registry the streaming path registers
6823    /// into -- not a second, parallel one. Registered by hand here
6824    /// because a `oneshot` router cannot hold a stream open.
6825    #[tokio::test]
6826    async fn cancelling_a_live_generation_signals_its_token_and_answers_200() {
6827        let state = Arc::new(test_state(
6828            test_model_full_byte_vocab(),
6829            ResponseCache::new(1000, Duration::from_secs(3600)),
6830        ));
6831        let app = test_app_with_state(Arc::clone(&state));
6832        let (token, _guard) = state.cancels.register("chatcmpl-live");
6833
6834        let (status, before) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6835        assert_eq!(status, StatusCode::OK);
6836        assert_eq!(before["generating_now"], serde_json::json!(1));
6837
6838        let (status, body) = post_json_uri(
6839            &app,
6840            frink_api::routes::V1_CANCEL,
6841            serde_json::json!({ "request_id": "chatcmpl-live" }),
6842        )
6843        .await;
6844        assert_eq!(status, StatusCode::OK);
6845        assert_eq!(body["cancelled"], serde_json::json!(true));
6846        assert!(
6847            token.is_cancelled(),
6848            "the endpoint answered ok without setting the flag the decode loop reads"
6849        );
6850    }
6851
6852    #[tokio::test]
6853    async fn tokenize_detokenize_roundtrip_and_embeddings_mean() {
6854        let app = test_app();
6855        let (status, tok) =
6856            post_json_uri(&app, "/v1/tokenize", serde_json::json!({ "prompt": "Hi" })).await;
6857        assert_eq!(status, StatusCode::OK);
6858        let tokens = tok["tokens"].as_array().unwrap();
6859        assert_eq!(tok["count"], tokens.len());
6860        assert!(!tokens.is_empty());
6861
6862        let (status, detok) = post_json_uri(
6863            &app,
6864            "/v1/detokenize",
6865            serde_json::json!({ "tokens": tokens }),
6866        )
6867        .await;
6868        assert_eq!(status, StatusCode::OK);
6869        assert_eq!(detok["text"], "Hi");
6870
6871        let (status, emb) = post_json_uri(
6872            &app,
6873            "/v1/embeddings",
6874            serde_json::json!({
6875                "input": "Hi",
6876                "embedding_type": "mean"
6877            }),
6878        )
6879        .await;
6880        assert_eq!(status, StatusCode::OK);
6881        let vec = emb["data"][0]["embedding"].as_array().unwrap();
6882        assert!(!vec.is_empty());
6883        assert!(vec.iter().all(|v| v.as_f64().is_some()));
6884    }
6885
6886    /// The decoder path's accepted `embedding_type` set must not have
6887    /// widened when the encoder path arrived: `cls` is row 0 of a
6888    /// decoder's hidden states, which is its BOS position and means
6889    /// nothing, so it stays refused here and the refusal names what is
6890    /// accepted.
6891    #[tokio::test]
6892    async fn the_decoder_path_still_refuses_a_pooling_it_cannot_mean() {
6893        let app = test_app();
6894        let (status, body) = post_json_uri(
6895            &app,
6896            "/v1/embeddings",
6897            serde_json::json!({ "input": "Hi", "embedding_type": "cls" }),
6898        )
6899        .await;
6900        assert_eq!(status, StatusCode::BAD_REQUEST);
6901        let msg = body["error"]["message"].as_str().unwrap();
6902        assert!(msg.contains("mean") && msg.contains("last"), "{msg}");
6903    }
6904
6905    /// A real BGE checkpoint served through the route: CLS by default
6906    /// because the file says `pooling_type = 2`, 384 dims, unit norm,
6907    /// and `usage.prompt_tokens` counting the `[CLS]`/`[SEP]` the model
6908    /// actually saw.
6909    #[tokio::test]
6910    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
6911    async fn a_real_embedding_model_serves_v1_embeddings() {
6912        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6913            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
6914        if !path.exists() {
6915            eprintln!("SKIP: {} not present", path.display());
6916            return;
6917        }
6918        let encoder = frink_models::EmbeddingModel::from_gguf_path(&path).expect("load bge");
6919        let mut state = test_state(
6920            test_model_full_byte_vocab(),
6921            ResponseCache::new(1000, Duration::from_secs(3600)),
6922        );
6923        state.embedding = Some(Arc::new(encoder));
6924        let app = test_app_with_state(Arc::new(state));
6925
6926        let (status, body) = post_json_uri(
6927            &app,
6928            "/v1/embeddings",
6929            serde_json::json!({ "input": ["Hello world", "a second input"] }),
6930        )
6931        .await;
6932        assert_eq!(status, StatusCode::OK, "{body}");
6933        assert_eq!(body["model"], "bge-small-en-v1.5");
6934        let data = body["data"].as_array().unwrap();
6935        assert_eq!(data.len(), 2);
6936        for (i, row) in data.iter().enumerate() {
6937            assert_eq!(row["index"], i);
6938            let v: Vec<f64> = row["embedding"]
6939                .as_array()
6940                .unwrap()
6941                .iter()
6942                .map(|x| x.as_f64().unwrap())
6943                .collect();
6944            assert_eq!(v.len(), 384, "the encoder\'s width, not the decoder\'s");
6945            let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
6946            assert!((norm - 1.0).abs() < 1e-4, "not L2-normalized: {norm}");
6947        }
6948        // "Hello world" is [CLS] hello world [SEP] = 4, and the second
6949        // input adds its own two specials.
6950        assert!(body["usage"]["prompt_tokens"].as_u64().unwrap() >= 4 + 2);
6951
6952        // The default came from the file. Asking for MEAN must give a
6953        // different vector, which is what proves CLS was not a
6954        // coincidence of this input.
6955        let (status, mean) = post_json_uri(
6956            &app,
6957            "/v1/embeddings",
6958            serde_json::json!({ "input": "Hello world", "embedding_type": "mean" }),
6959        )
6960        .await;
6961        assert_eq!(status, StatusCode::OK);
6962        assert_ne!(mean["data"][0]["embedding"], data[0]["embedding"]);
6963    }
6964
6965    /// The same BGE checkpoint as `FRINK_MODEL_PATH` -- the *loaded*
6966    /// model, not a side-car.
6967    ///
6968    /// Four claims, and the third is the one this whole seam exists
6969    /// for: the loader routes an encoder-only GGUF away from every
6970    /// decoder path, `/v1/embeddings` serves it, `/v1/chat/completions`
6971    /// refuses it NAMING IT AS AN EMBEDDING MODEL (before this, the
6972    /// same file died in `tokenizer_from_gguf` with a message about
6973    /// WordPiece being unreadable -- true, and the wrong thing to send
6974    /// a user after), and `/v1/models` says which endpoint it is for so
6975    /// a client need not send a request to find out.
6976    #[tokio::test]
6977    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
6978    async fn an_encoder_can_be_the_loaded_model() {
6979        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6980            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
6981        if !path.exists() {
6982            eprintln!("SKIP: {} not present", path.display());
6983            return;
6984        }
6985
6986        // Through the real `FRINK_MODEL_PATH` loader, not by
6987        // constructing an `EmbeddingModel` directly: the routing
6988        // decision is half of what is under test.
6989        let loaded = model::load_from_path(path.to_str().unwrap()).expect("load bge as the model");
6990        assert!(
6991            matches!(loaded, model::LoadedModel::Encoder(_)),
6992            "an encoder-only GGUF reached a decoder loader"
6993        );
6994        let (loaded, batcher, ceiling) = activate_loaded_model(loaded, true, None, None);
6995        assert!(
6996            matches!(loaded, Loaded::Encoder(_)),
6997            "the encoder did not stay an encoder through activation"
6998        );
6999        assert!(
7000            batcher.is_none() && ceiling.is_none(),
7001            "an encoder was given a decode batcher or a KV ceiling it has no use for"
7002        );
7003
7004        let state = test_state(
7005            test_model_full_byte_vocab(),
7006            ResponseCache::new(1000, Duration::from_secs(3600)),
7007        );
7008        state.swap_active(Some(Arc::new(ActiveModel {
7009            id: None,
7010            loaded,
7011            batcher,
7012            ceiling,
7013            checkpoint_path: None,
7014        })));
7015        let app = test_app_with_state(Arc::new(state));
7016
7017        // 1. It embeds.
7018        let (status, body) = post_json_uri(
7019            &app,
7020            "/v1/embeddings",
7021            serde_json::json!({ "input": "Hello world" }),
7022        )
7023        .await;
7024        assert_eq!(status, StatusCode::OK, "{body}");
7025        assert_eq!(body["model"], "bge-small-en-v1.5");
7026        let v = body["data"][0]["embedding"].as_array().unwrap();
7027        assert_eq!(v.len(), 384, "the encoder's width, not the decoder's");
7028
7029        // 2. It refuses to chat, by name.
7030        let (status, body) = post_json_uri(
7031            &app,
7032            "/v1/chat/completions",
7033            serde_json::json!({
7034                "model": "bge-small-en-v1.5",
7035                "messages": [{"role": "user", "content": "hi"}],
7036            }),
7037        )
7038        .await;
7039        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}");
7040        let msg = body["error"]["message"].as_str().unwrap();
7041        for fact in [
7042            "bge-small-en-v1.5",
7043            "bert",
7044            "embedding model",
7045            "/v1/embeddings",
7046        ] {
7047            assert!(msg.contains(fact), "the refusal does not say {fact}: {msg}");
7048        }
7049
7050        // 3. `/v1/models` lists it as what it is.
7051        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
7052        assert_eq!(status, StatusCode::OK);
7053        let entry = &models["data"][0];
7054        assert_eq!(entry["id"], "bge-small-en-v1.5");
7055        assert_eq!(entry["frink_model_kind"], "embedding");
7056        assert_eq!(entry["frink_tokenizer"], "gguf-wordpiece");
7057        assert_eq!(entry["frink_n_embd"], 384);
7058        assert_eq!(entry["frink_pooling"], "CLS");
7059        assert_eq!(
7060            entry["frink_endpoints"],
7061            serde_json::json!(["/v1/embeddings"])
7062        );
7063        // A reasoning-gear field here would be an invented answer about
7064        // a template the checkpoint does not have.
7065        assert!(entry.get("supported_reasoning_efforts").is_none());
7066
7067        // 4. `/health` is ready, and says which endpoint is ready.
7068        let (status, health) = get_json(&app, frink_api::routes::HEALTH).await;
7069        assert_eq!(status, StatusCode::OK, "an encoder is a loaded model");
7070        assert_eq!(health["model"]["id"], "bge-small-en-v1.5");
7071        assert_eq!(health["model"]["synthetic_weights"], false);
7072        let weights = health["capabilities"]
7073            .as_array()
7074            .unwrap()
7075            .iter()
7076            .find(|c| c["id"] == frink_api::health::capability::REAL_WEIGHTS)
7077            .expect("a real-weights capability row");
7078        let detail = weights["detail"].as_str().unwrap_or_default();
7079        assert!(detail.contains("ENCODER"), "{detail}");
7080        // 5. It tokenizes, and round-trips. An embedding model's whole
7081        // contract is the vector it returns for a string, so when that
7082        // vector surprises you the first question is what tokens it
7083        // actually saw. These routes used to go through
7084        // `generative()?` and answer 501 "not a generative model",
7085        // which left no way to ask without loading the checkpoint in a
7086        // second tool (issue #28).
7087        let (status, body) = post_json_uri(
7088            &app,
7089            frink_api::routes::V1_TOKENIZE,
7090            serde_json::json!({ "content": "hello world" }),
7091        )
7092        .await;
7093        assert_eq!(
7094            status,
7095            StatusCode::OK,
7096            "an encoder has a real tokenizer: {body}"
7097        );
7098        let tokens = body["tokens"].as_array().expect("tokens array").clone();
7099        assert!(!tokens.is_empty(), "WordPiece produced nothing: {body}");
7100
7101        let (status, body) = post_json_uri(
7102            &app,
7103            frink_api::routes::V1_DETOKENIZE,
7104            serde_json::json!({ "tokens": tokens }),
7105        )
7106        .await;
7107        assert_eq!(status, StatusCode::OK, "{body}");
7108        let round_tripped = body["content"].as_str().expect("content").to_string();
7109        assert!(
7110            round_tripped.contains("hello") && round_tripped.contains("world"),
7111            "the ids did not decode back through the encoder's own vocabulary: {round_tripped}"
7112        );
7113
7114        // And the refusal that must NOT have been weakened: a decode is
7115        // still a decode, and this checkpoint still cannot do one.
7116        let (status, _) = post_json_uri(
7117            &app,
7118            "/v1/completions",
7119            serde_json::json!({ "model": "m", "prompt": "hi", "max_tokens": 1 }),
7120        )
7121        .await;
7122        assert_eq!(
7123            status,
7124            StatusCode::NOT_IMPLEMENTED,
7125            "tokenizing an encoder must not have opened a path to generating with one"
7126        );
7127    }
7128
7129    /// The /metrics endpoint must expose the bounded expert cache's
7130    /// counters when the model streams routed experts, and the
7131    /// counters must reflect real decode activity (a forward pass
7132    /// through store-backed MoE layers produces misses/hits).
7133    #[tokio::test]
7134    async fn metrics_exposes_expert_store_counters_when_streaming_is_active() {
7135        use http_body_util::BodyExt;
7136        use tower::ServiceExt;
7137
7138        let fixture = concat!(
7139            "../frink-models/tests/fixtures/",
7140            "frink_real_moe_test.gguf"
7141        );
7142        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
7143        let decoder = Decoder::from_gguf_with_expert_cache(
7144            &fixture,
7145            frink_models::config::test_moe_fixture(),
7146            Some(1024 * 1024),
7147        )
7148        .expect("MoE fixture must load store-backed");
7149
7150        // Drive one real forward pass so the store sees decode
7151        // activity (the fixture's tiny vocab can't survive the HTTP
7152        // path's template text, so decode directly).
7153        let mut caches: Vec<frink_core::cache::KvCache> = decoder.config.new_kv_caches();
7154        decoder.forward_token(1, 0, &mut caches);
7155
7156        let model = Model::Gguf(GgufModel {
7157            decoder: Arc::new(decoder),
7158            tokenizer: Arc::new(ServerTokenizer::Byte),
7159            stop_tokens: StopTokens::default(),
7160            bos_id: None,
7161            is_synthetic: false,
7162            chat_template: chat_template::PromptTemplate::plain(),
7163        });
7164        let state = Arc::new(test_state(
7165            model,
7166            ResponseCache::new(16, Duration::from_secs(60)),
7167        ));
7168        let app = Router::new()
7169            .route("/metrics", axum::routing::get(metrics))
7170            .route("/v1/chat/completions", post(chat_completions))
7171            .with_state(state);
7172
7173        let fetch_metrics = |app: Router| async move {
7174            let resp = app
7175                .oneshot(
7176                    axum::http::Request::builder()
7177                        .method("GET")
7178                        .uri("/metrics")
7179                        .body(axum::body::Body::empty())
7180                        .unwrap(),
7181                )
7182                .await
7183                .unwrap();
7184            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
7185            String::from_utf8(bytes.to_vec()).unwrap()
7186        };
7187
7188        let after = fetch_metrics(app.clone()).await;
7189        assert!(
7190            after.contains("frink_expert_cache_misses_total"),
7191            "streaming model must expose expert-cache metrics: {after}"
7192        );
7193        let misses: u64 = after
7194            .lines()
7195            .find(|l| l.starts_with("frink_expert_cache_misses_total"))
7196            .and_then(|l| l.split_whitespace().nth(1))
7197            .and_then(|v| v.parse().ok())
7198            .expect("misses metric line must parse");
7199        assert!(
7200            misses > 0,
7201            "decode must have read experts through the store: {after}"
7202        );
7203    }
7204
7205    fn weather_tool() -> serde_json::Value {
7206        serde_json::json!({
7207            "type": "function",
7208            "function": {
7209                "name": "get_weather",
7210                "description": "Get the current weather for a location.",
7211                "parameters": {
7212                    "type": "object",
7213                    "properties": {"location": {"type": "string"}},
7214                    "required": ["location"]
7215                }
7216            }
7217        })
7218    }
7219
7220    fn weather_tool_def() -> ToolDef {
7221        ToolDef {
7222            kind: "function".to_string(),
7223            function: ToolFunctionDef {
7224                name: "get_weather".to_string(),
7225                description: Some("Get the current weather for a location.".to_string()),
7226                parameters: Some(serde_json::json!({
7227                    "type": "object",
7228                    "properties": {"location": {"type": "string"}},
7229                    "required": ["location"]
7230                })),
7231            },
7232        }
7233    }
7234
7235    #[test]
7236    fn tool_preamble_mentions_every_tool_name_and_description() {
7237        let preamble = tool_preamble(&[weather_tool_def()]);
7238        assert!(preamble.contains("get_weather"));
7239        assert!(preamble.contains("Get the current weather for a location."));
7240        assert!(preamble.contains("<tool_call>"));
7241        assert!(preamble.contains("</tool_call>"));
7242    }
7243
7244    #[test]
7245    fn a_real_marker_becomes_a_structured_tool_call() {
7246        let text = "sure, let me check.<tool_call>{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}</tool_call>";
7247        let (message, finish) = build_response_message(
7248            text.to_string(),
7249            &[weather_tool_def()],
7250            output::OutputPosture::for_model("test-model"),
7251            "stop",
7252        );
7253        assert_eq!(finish, "tool_calls");
7254        let calls = message.tool_calls.expect("must carry a tool call");
7255        assert_eq!(calls[0].function.name, "get_weather");
7256        let parsed: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
7257        assert_eq!(parsed["location"], "Paris");
7258    }
7259
7260    #[test]
7261    fn a_plain_answer_is_not_promoted_to_a_tool_call() {
7262        let (message, finish) = build_response_message(
7263            "just an answer".to_string(),
7264            &[weather_tool_def()],
7265            output::OutputPosture::for_model("test-model"),
7266            "stop",
7267        );
7268        assert_eq!(finish, "stop");
7269        assert!(message.tool_calls.is_none());
7270        assert_eq!(message.content.as_deref(), Some("just an answer"));
7271    }
7272
7273    /// Malformed JSON inside the marker is not a call. Returning it as
7274    /// one would hand a client arguments it cannot parse.
7275    #[test]
7276    fn a_malformed_payload_is_not_a_tool_call() {
7277        let (message, finish) = build_response_message(
7278            "<tool_call>not valid json at all</tool_call>".to_string(),
7279            &[weather_tool_def()],
7280            output::OutputPosture::for_model("test-model"),
7281            "stop",
7282        );
7283        assert_eq!(finish, "stop");
7284        assert!(message.tool_calls.is_none());
7285    }
7286
7287    /// A call to something the request never offered is refused: the
7288    /// client would be asked to execute a tool it does not have.
7289    #[test]
7290    fn a_tool_that_was_never_offered_is_not_returned() {
7291        let (message, finish) = build_response_message(
7292            "<tool_call>{\"name\": \"ping\", \"arguments\": {}}</tool_call>".to_string(),
7293            &[weather_tool_def()],
7294            output::OutputPosture::for_model("test-model"),
7295            "stop",
7296        );
7297        assert_eq!(finish, "stop");
7298        assert!(message.tool_calls.is_none());
7299    }
7300
7301    /// With no tools offered at all, marker text is just text.
7302    #[test]
7303    fn marker_text_with_no_tools_offered_stays_content() {
7304        let (message, finish) = build_response_message(
7305            "<tool_call>{\"name\": \"get_weather\", \"arguments\": {}}</tool_call>".to_string(),
7306            &[],
7307            output::OutputPosture::for_model("test-model"),
7308            "stop",
7309        );
7310        assert_eq!(finish, "stop");
7311        assert!(message.tool_calls.is_none());
7312        assert!(message.content.is_some());
7313    }
7314
7315    /// The streaming contract a coding agent depends on: the call's
7316    /// identity arrives first, then its arguments in pieces, and the
7317    /// pieces concatenate to exactly the final arguments.
7318    #[test]
7319    fn a_streamed_call_opens_then_delivers_its_arguments_in_pieces() {
7320        let opened = std::cell::Cell::new(0usize);
7321        let mut parser = crate::policy::parser::ToolCallParser::new(
7322            crate::policy::parser::ToolCallFormat::Qwen3Coder,
7323            vec![
7324                crate::policy::parser::tool_call::ToolSchema::with_parameters(
7325                    "write_file",
7326                    serde_json::json!({"type": "object", "properties": {
7327                        "path": {"type": "string"},
7328                        "contents": {"type": "string"}
7329                    }}),
7330                ),
7331            ],
7332        );
7333        let wire = "<tool_call><function=write_file>\
7334                    <parameter=path>\n/tmp/x\n</parameter>\
7335                    <parameter=contents>\nhello world\n</parameter>\
7336                    </function></tool_call>";
7337
7338        let mut deltas = Vec::new();
7339        let mut text = String::new();
7340        for piece in wire.as_bytes().chunks(7) {
7341            let chunk = String::from_utf8_lossy(piece).into_owned();
7342            let (more_text, more) = tool_call_deltas(parser.push(&chunk), &opened);
7343            text.push_str(&more_text);
7344            deltas.extend(more);
7345        }
7346        let (more_text, more) = tool_call_deltas(parser.finish(), &opened);
7347        text.push_str(&more_text);
7348        deltas.extend(more);
7349
7350        assert_eq!(opened.get(), 1, "one call opened");
7351        assert!(text.is_empty(), "the markers are not content: {text:?}");
7352
7353        let first = &deltas[0];
7354        assert_eq!(first.index, 0);
7355        assert_eq!(first.id.as_deref(), Some("call_0"));
7356        assert_eq!(first.kind, Some("function"));
7357        assert_eq!(first.function.name.as_deref(), Some("write_file"));
7358
7359        // Everything after the opening delta is argument text only,
7360        // and it parses once concatenated.
7361        let joined: String = deltas
7362            .iter()
7363            .filter_map(|d| d.function.arguments.clone())
7364            .collect();
7365        let parsed: serde_json::Value =
7366            serde_json::from_str(&joined).expect("the fragments concatenate to valid JSON");
7367        assert_eq!(parsed["path"], serde_json::json!("/tmp/x"));
7368        assert_eq!(parsed["contents"], serde_json::json!("hello world"));
7369        assert!(
7370            deltas.len() >= 3,
7371            "the arguments arrived in pieces, not whole: {}",
7372            deltas.len()
7373        );
7374        assert!(
7375            deltas[1..].iter().all(|d| d.function.name.is_none()),
7376            "only the opening delta carries identity"
7377        );
7378    }
7379
7380    /// Text either side of a call still streams as content, in order.
7381    #[test]
7382    fn text_around_a_streamed_call_is_still_content() {
7383        let opened = std::cell::Cell::new(0usize);
7384        let mut parser = crate::policy::parser::ToolCallParser::new(
7385            crate::policy::parser::ToolCallFormat::Qwen25,
7386            vec![crate::policy::parser::tool_call::ToolSchema::new(
7387                "get_weather",
7388            )],
7389        );
7390        let wire = "let me check. <tool_call>{\"name\": \"get_weather\", \
7391                    \"arguments\": {}}</tool_call> done";
7392        let mut text = String::new();
7393        for piece in wire.as_bytes().chunks(5) {
7394            let chunk = String::from_utf8_lossy(piece).into_owned();
7395            let (more, _) = tool_call_deltas(parser.push(&chunk), &opened);
7396            text.push_str(&more);
7397        }
7398        let (more, _) = tool_call_deltas(parser.finish(), &opened);
7399        text.push_str(&more);
7400
7401        assert_eq!(opened.get(), 1);
7402        assert!(text.starts_with("let me check. "), "{text:?}");
7403        assert!(text.ends_with(" done"), "{text:?}");
7404        assert!(!text.contains("<tool_call>"), "markers leaked: {text:?}");
7405    }
7406
7407    /// A reasoning model's thinking must not be returned as its
7408    /// answer.
7409    #[test]
7410    fn a_reasoning_block_is_split_out_of_the_answer() {
7411        let (message, finish) = build_response_message(
7412            "<think>weighing it up</think>The answer is 4.".to_string(),
7413            &[],
7414            output::OutputPosture::for_model("Qwen3-8B"),
7415            "stop",
7416        );
7417        assert_eq!(finish, "stop");
7418        assert_eq!(message.content.as_deref(), Some("The answer is 4."));
7419        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
7420    }
7421
7422    /// ... and a model with no reasoning format keeps its text intact,
7423    /// markers and all.
7424    #[test]
7425    fn a_non_reasoning_model_keeps_a_literal_marker_in_its_answer() {
7426        let (message, _) = build_response_message(
7427            "Use the <think> tag like this.".to_string(),
7428            &[],
7429            output::OutputPosture::for_model("llama-3.1-8b"),
7430            "stop",
7431        );
7432        assert_eq!(
7433            message.content.as_deref(),
7434            Some("Use the <think> tag like this.")
7435        );
7436        assert!(message.reasoning_content.is_none());
7437    }
7438
7439    /// Zero-regression proof: an ordinary request with no `tools`/
7440    /// `session_id` produces the plain response shape -- `content` a
7441    /// string, no `tool_calls` field -- with an honest finish reason:
7442    /// this 4-token greedy request truncates at `max_tokens`, so
7443    /// `finish_reason` must be "length" (an earlier version hardcoded
7444    /// "stop" for every non-streaming response), and `usage` counts
7445    /// exactly the generated tokens.
7446    #[tokio::test]
7447    async fn a_request_with_no_tools_or_session_behaves_exactly_as_before() {
7448        let app = test_app();
7449        let body = serde_json::json!({
7450            "model": "m",
7451            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7452            "max_tokens": 4,
7453            "temperature": 0,
7454        });
7455        let resp = post_json(&app, body).await;
7456        let message = &resp["choices"][0]["message"];
7457        assert!(message["content"].is_string());
7458        assert!(message.get("tool_calls").is_none());
7459        assert_eq!(resp["choices"][0]["finish_reason"], "length");
7460        assert_eq!(resp["usage"]["completion_tokens"], 4);
7461        assert_eq!(
7462            resp["usage"]["total_tokens"],
7463            resp["usage"]["prompt_tokens"].as_u64().unwrap() + 4
7464        );
7465    }
7466
7467    pub(crate) async fn get_json(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
7468        use http_body_util::BodyExt;
7469        use tower::ServiceExt;
7470
7471        let response = app
7472            .clone()
7473            .oneshot(
7474                axum::http::Request::builder()
7475                    .method("GET")
7476                    .uri(uri)
7477                    .body(axum::body::Body::empty())
7478                    .unwrap(),
7479            )
7480            .await
7481            .unwrap();
7482        let status = response.status();
7483        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7484        (status, serde_json::from_slice(&bytes).unwrap())
7485    }
7486
7487    #[tokio::test]
7488    async fn health_answers_a_capability_handshake_not_a_boolean() {
7489        let app = test_app();
7490        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
7491        assert_eq!(status, StatusCode::OK);
7492
7493        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
7494        assert_eq!(health.state, frink_api::HealthState::Ready);
7495        assert!(health.pid > 0);
7496        assert!(health.server_time_unix_ms > 0);
7497        // Nothing has been served yet: the field is absent rather than
7498        // claiming a request happened at time zero.
7499        assert_eq!(health.last_request_age_seconds, None);
7500
7501        // Every control the UI might grey out has a code it can switch
7502        // on and a sentence it can show.
7503        for id in [
7504            frink_api::health::capability::CPU,
7505            frink_api::health::capability::METAL,
7506            frink_api::health::capability::CUDA,
7507            frink_api::health::capability::REAL_WEIGHTS,
7508            frink_api::health::capability::CONTINUOUS_BATCHING,
7509        ] {
7510            let cap = health
7511                .capability(id)
7512                .unwrap_or_else(|| panic!("{id} missing"));
7513            assert!(!cap.reason.is_empty(), "{cap:?}");
7514            assert!(!cap.detail.is_empty(), "{cap:?}");
7515        }
7516        // The test app serves synthetic random weights, and health must
7517        // say so: a UI that presents noise as a model invites a bug
7518        // report about "quality".
7519        let weights = health
7520            .capability(frink_api::health::capability::REAL_WEIGHTS)
7521            .unwrap();
7522        assert!(!weights.available);
7523        assert_eq!(weights.reason, frink_api::health::reason::MODEL_NOT_LOADED);
7524        assert!(health.model.as_ref().unwrap().synthetic_weights);
7525    }
7526
7527    #[tokio::test]
7528    async fn health_vouches_for_liveness_after_a_request_has_been_served() {
7529        let app = test_app();
7530        let _ = post_json(
7531            &app,
7532            serde_json::json!({
7533                "model": "m",
7534                "messages": [{"role": "user", "content": "\u{1}"}],
7535                "max_tokens": 1,
7536                "temperature": 0,
7537            }),
7538        )
7539        .await;
7540        let (_status, body) = get_json(&app, frink_api::routes::HEALTH).await;
7541        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
7542        let age = health
7543            .last_request_age_seconds
7544            .expect("a served request is evidence of liveness");
7545        assert!((0.0..5.0).contains(&age), "implausible age {age}");
7546    }
7547
7548    /// Every `data:` payload of an SSE response body, `[DONE]` excluded.
7549    async fn post_sse_chunks(app: &Router, body: serde_json::Value) -> Vec<serde_json::Value> {
7550        use http_body_util::BodyExt;
7551        use tower::ServiceExt;
7552
7553        let response = app
7554            .clone()
7555            .oneshot(
7556                axum::http::Request::builder()
7557                    .method("POST")
7558                    .uri("/v1/chat/completions")
7559                    .header("content-type", "application/json")
7560                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7561                    .unwrap(),
7562            )
7563            .await
7564            .unwrap();
7565        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7566        String::from_utf8(bytes.to_vec())
7567            .unwrap()
7568            .lines()
7569            .filter_map(|line| line.strip_prefix("data: "))
7570            .filter(|payload| *payload != "[DONE]")
7571            .map(|payload| serde_json::from_str(payload).unwrap())
7572            .collect()
7573    }
7574
7575    #[tokio::test]
7576    async fn a_stream_states_its_request_id_once_in_the_first_chunk() {
7577        let app = test_app();
7578        let chunks = post_sse_chunks(
7579            &app,
7580            serde_json::json!({
7581                "model": "m",
7582                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7583                "max_tokens": 4,
7584                "temperature": 0,
7585                "stream": true,
7586            }),
7587        )
7588        .await;
7589
7590        assert!(!chunks.is_empty());
7591        let request_id = chunks[0]["request_id"]
7592            .as_str()
7593            .expect("the first chunk names the request")
7594            .to_string();
7595        assert!(request_id.starts_with("chatcmpl-"), "{request_id}");
7596        // Once, and before any content: a client that reads the id from
7597        // chunk zero never has to correlate by heuristic.
7598        for (i, chunk) in chunks.iter().enumerate().skip(1) {
7599            assert!(
7600                chunk.get("request_id").is_none(),
7601                "chunk {i} repeats request_id"
7602            );
7603        }
7604        // Every chunk of one stream carries the same `id`, and it is
7605        // that request id -- not a shared constant.
7606        for chunk in &chunks {
7607            assert_eq!(chunk["id"], serde_json::json!(request_id));
7608        }
7609
7610        let other = post_sse_chunks(
7611            &app,
7612            serde_json::json!({
7613                "model": "m",
7614                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7615                "max_tokens": 4,
7616                "temperature": 0,
7617                "stream": true,
7618            }),
7619        )
7620        .await;
7621        assert_ne!(
7622            other[0]["request_id"].as_str().unwrap(),
7623            request_id,
7624            "two concurrent chats must not share an id"
7625        );
7626    }
7627
7628    #[tokio::test]
7629    async fn a_non_streamed_response_names_the_same_request_id_as_its_completion_id() {
7630        let app = test_app();
7631        let resp = post_json(
7632            &app,
7633            serde_json::json!({
7634                "model": "m",
7635                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7636                "max_tokens": 2,
7637                "temperature": 0,
7638            }),
7639        )
7640        .await;
7641        assert_eq!(resp["id"], resp["request_id"]);
7642        assert!(resp["request_id"]
7643            .as_str()
7644            .unwrap()
7645            .starts_with("chatcmpl-"));
7646    }
7647
7648    /// The whole point of server-reported timings: a client can tell
7649    /// prefill from decode without a stopwatch (see `frink_api::usage`).
7650    #[tokio::test]
7651    async fn usage_carries_separate_prefill_and_decode_timings() {
7652        let app = test_app();
7653        let resp = post_json(
7654            &app,
7655            serde_json::json!({
7656                "model": "m",
7657                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7658                "max_tokens": 4,
7659                "temperature": 0,
7660            }),
7661        )
7662        .await;
7663        let usage = &resp["usage"];
7664        assert!(usage["prompt_eval_duration_ms"].is_number(), "{usage}");
7665        assert!(usage["generation_duration_ms"].is_number(), "{usage}");
7666        assert!(usage["time_to_first_token_ms"].is_number(), "{usage}");
7667        assert!(usage["predicted_per_second"].is_number(), "{usage}");
7668        // No prefix cache in this app: the field must be absent, not 0.
7669        assert!(usage.get("cached_tokens").is_none(), "{usage}");
7670    }
7671
7672    /// A real, deterministic small model with random weights will not
7673    /// spontaneously produce a `<tool_call>{...}</tool_call>` marker
7674    /// (whether a real deployed model does is a property of that
7675    /// model, not of frink's plumbing) -- so the real, testable
7676    /// end-to-end property here is that a `tools`-bearing request
7677    /// whose output does NOT contain the marker falls through cleanly
7678    /// to an ordinary text response instead of erroring or panicking.
7679    #[tokio::test]
7680    async fn a_tools_request_with_no_marker_in_the_output_falls_back_to_plain_content() {
7681        let app = test_app();
7682        let body = serde_json::json!({
7683            "model": "m",
7684            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7685            "max_tokens": 4,
7686            "temperature": 0,
7687            "tools": [weather_tool()],
7688        });
7689        let resp = post_json(&app, body).await;
7690        let message = &resp["choices"][0]["message"];
7691        assert!(
7692            message["content"].is_string(),
7693            "must fall back to plain content when no real tool-call marker is present: {resp:?}"
7694        );
7695        assert!(message.get("tool_calls").is_none());
7696        // Truncated at max_tokens, so the honest finish reason is
7697        // "length" -- the point here is only that it is NOT
7698        // "tool_calls".
7699        assert_eq!(resp["choices"][0]["finish_reason"], "length");
7700    }
7701
7702    /// A whole-response cache hit must be indistinguishable from
7703    /// recomputing: same content, same (honest) finish_reason, same
7704    /// usage counts -- only the `frink_cache` marker may differ.
7705    #[tokio::test]
7706    async fn a_cache_hit_reports_the_original_finish_reason_and_usage() {
7707        let app = test_app();
7708        let body = serde_json::json!({
7709            "model": "m",
7710            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
7711            "max_tokens": 3,
7712            "temperature": 0,
7713        });
7714        let first = post_json(&app, body.clone()).await;
7715        assert_eq!(first["frink_cache"], "miss");
7716        let second = post_json(&app, body).await;
7717        assert_eq!(second["frink_cache"], "hit");
7718        assert_eq!(
7719            first["choices"][0]["message"]["content"],
7720            second["choices"][0]["message"]["content"]
7721        );
7722        assert_eq!(
7723            first["choices"][0]["finish_reason"],
7724            second["choices"][0]["finish_reason"]
7725        );
7726        assert_eq!(first["usage"], second["usage"]);
7727        assert_eq!(second["usage"]["completion_tokens"], 3);
7728    }
7729
7730    /// The whole of #35 through the real router: a request that adds a
7731    /// GRAMMAR to a body already answered without one must be generated
7732    /// afresh, under that grammar.
7733    ///
7734    /// The cache used to be consulted before
7735    /// `generation_params_for_template` had even compiled the grammar,
7736    /// and the key held no trace of it, so the constrained request was
7737    /// handed the previous caller's unconstrained prose with a 200. The
7738    /// answer is asserted, not the key: a key that differs proves
7739    /// nothing if the lookup uses something else.
7740    #[tokio::test]
7741    async fn a_grammar_request_is_not_answered_from_an_unconstrained_cache_entry() {
7742        let app = test_app();
7743        let plain = serde_json::json!({
7744            "model": "m",
7745            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
7746            "max_tokens": 3,
7747            "temperature": 0,
7748        });
7749
7750        let first = post_json(&app, plain.clone()).await;
7751        assert_eq!(first["frink_cache"], "miss");
7752        let unconstrained = first["choices"][0]["message"]["content"]
7753            .as_str()
7754            .expect("content")
7755            .to_string();
7756
7757        let mut constrained = plain.clone();
7758        constrained["grammar"] = serde_json::json!("root ::= \"yes\"");
7759        let second = post_json(&app, constrained).await;
7760        assert_eq!(
7761            second["frink_cache"], "miss",
7762            "a grammar is part of the key, so this body has never been answered"
7763        );
7764        // The synthetic demo model wraps its decode in a banner, so the
7765        // assertion is on the decoded text inside it: `yes` is the only
7766        // string this grammar admits, and it is there.
7767        let constrained_answer = second["choices"][0]["message"]["content"]
7768            .as_str()
7769            .expect("content")
7770            .to_string();
7771        assert!(
7772            constrained_answer.contains("-> \"yes\"]"),
7773            "the grammar must have been compiled AND applied, not skipped \
7774             by a cache hit: {constrained_answer}"
7775        );
7776        assert_ne!(
7777            constrained_answer, unconstrained,
7778            "the constrained request was served the unconstrained answer"
7779        );
7780
7781        // And the entry the first request made is still the first
7782        // request's: the miss above is the grammar, not a key that
7783        // fails to repeat.
7784        let third = post_json(&app, plain).await;
7785        assert_eq!(third["frink_cache"], "hit");
7786        assert_eq!(third["choices"][0]["message"]["content"], unconstrained);
7787    }
7788
7789    /// The third of #35's fields, and the one whose old failure was
7790    /// LOUD: `validate_json_object_output` runs against whatever came
7791    /// back, so a `json_object` request answered from a cached prose
7792    /// entry got a hard 400 for a body that had never been generated
7793    /// under the JSON mask at all.
7794    ///
7795    /// The system message is what makes this reproducible, and it is the
7796    /// repo's own bug shape underneath. `inject_json_object_system_hint`
7797    /// usually leaves a fingerprint in the PROMPT, which happened to
7798    /// split the two keys apart -- a correctness property nothing stated
7799    /// or enforced, resting on a string edit made for a different
7800    /// reason. Its `!s.contains("JSON")` arm is the hole: a caller who
7801    /// already says "JSON" in their own system message gets NO hint
7802    /// appended, so the two requests render byte-identical prompts and
7803    /// the old key could not tell them apart.
7804    ///
7805    /// The synthetic model emits its demo banner under either mask, so
7806    /// the 400 is the same on both sides of this fix and cannot be the
7807    /// assertion; the cache-level twin in `response_cache` asserts the
7808    /// answer. What is asserted here is that the answer did not come
7809    /// from the other request's entry.
7810    #[tokio::test]
7811    async fn a_json_object_request_does_not_reuse_the_unconstrained_cache_entry() {
7812        let state = Arc::new(test_state(
7813            test_model_full_byte_vocab(),
7814            ResponseCache::new(1000, Duration::from_secs(3600)),
7815        ));
7816        let app = test_app_with_state(state.clone());
7817        let plain = serde_json::json!({
7818            "model": "m",
7819            "messages": [
7820                {"role": "system", "content": "Answer in JSON when it helps."},
7821                {"role": "user", "content": "\u{1}\u{2}"},
7822            ],
7823            "max_tokens": 3,
7824            "temperature": 0,
7825        });
7826
7827        let first = post_json(&app, plain.clone()).await;
7828        assert_eq!(first["frink_cache"], "miss");
7829        assert_eq!(state.cache_stats().entries, 1);
7830
7831        let mut as_json = plain.clone();
7832        as_json["response_format"] = serde_json::json!({"type": "json_object"});
7833        let (status, _) = post_json_uri(&app, "/v1/chat/completions", as_json).await;
7834        assert_eq!(
7835            status,
7836            StatusCode::BAD_REQUEST,
7837            "the demo banner is not a JSON object, whoever generated it"
7838        );
7839        assert_eq!(
7840            state.cache_stats().hits,
7841            0,
7842            "a json_object request must not be answered from an entry the \
7843             JSON mask never produced"
7844        );
7845        assert_eq!(
7846            state.cache_stats().entries,
7847            2,
7848            "json_object must key its own entry, not reuse the unconstrained \
7849             one it happens to render the same prompt as"
7850        );
7851    }
7852
7853    /// The same failure for `ignore_eos`, whose whole purpose is that a
7854    /// benchmarking run produces EXACTLY `max_tokens`. Answered from a
7855    /// cache entry the model's own EOS had cut short, it produced the
7856    /// short answer instead -- the one outcome the field exists to rule
7857    /// out (#35).
7858    ///
7859    /// `0x77` is the id this model greedily emits SECOND for the prompt
7860    /// below, so with it as the EOS the plain request stops after one
7861    /// token and the `ignore_eos` one runs the whole budget. Asserted on
7862    /// the token count and the finish reason, which is where a replayed
7863    /// answer shows.
7864    #[tokio::test]
7865    async fn an_ignore_eos_request_is_not_answered_from_a_cache_entry_that_stopped_at_eos() {
7866        let app = test_app_with_state(Arc::new(test_state(
7867            test_model_full_byte_vocab_with_eos(Some(0x77)),
7868            ResponseCache::new(1000, Duration::from_secs(3600)),
7869        )));
7870        let body = serde_json::json!({
7871            "model": "m",
7872            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
7873            "max_tokens": 6,
7874            "temperature": 0,
7875        });
7876
7877        let stopped = post_json(&app, body.clone()).await;
7878        assert_eq!(stopped["frink_cache"], "miss");
7879        assert_eq!(
7880            stopped["choices"][0]["finish_reason"], "stop",
7881            "the fixture is only meaningful if the model's EOS really fires here"
7882        );
7883        assert_eq!(stopped["usage"]["completion_tokens"], 1);
7884
7885        let mut ignoring = body.clone();
7886        ignoring["ignore_eos"] = serde_json::json!(true);
7887        let ran_on = post_json(&app, ignoring).await;
7888        assert_eq!(
7889            ran_on["frink_cache"], "miss",
7890            "ignore_eos is part of the key, so this body has never been answered"
7891        );
7892        assert_eq!(
7893            ran_on["usage"]["completion_tokens"], 6,
7894            "ignore_eos must run the full budget, not replay the EOS-terminated answer"
7895        );
7896        assert_eq!(ran_on["choices"][0]["finish_reason"], "length");
7897        assert_ne!(
7898            ran_on["choices"][0]["message"]["content"],
7899            stopped["choices"][0]["message"]["content"]
7900        );
7901    }
7902
7903    /// The real proof for session reuse:
7904    /// a two-request session where the second request sends only its
7905    /// new message must produce exactly the same output as manually
7906    /// resending the full history (built from the *real* first reply,
7907    /// not an assumed one) with no `session_id` at all.
7908    #[tokio::test]
7909    async fn session_reuse_produces_the_same_output_as_manually_resending_full_history() {
7910        let session_app = test_app();
7911        let manual_app = test_app();
7912
7913        // Turn 1, via session.
7914        let turn1 = post_json(
7915            &session_app,
7916            serde_json::json!({
7917                "model": "m",
7918                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7919                "session_id": "s1",
7920                "max_tokens": 5,
7921                "temperature": 0,
7922            }),
7923        )
7924        .await;
7925        let reply1 = turn1["choices"][0]["message"]["content"]
7926            .as_str()
7927            .unwrap()
7928            .to_string();
7929
7930        // Turn 1, manually, for comparison -- must match exactly
7931        // (trivially, since it's the literal same single-turn
7932        // request), confirming the session path's first turn isn't
7933        // doing anything different from a plain request.
7934        let manual_turn1 = post_json(
7935            &manual_app,
7936            serde_json::json!({
7937                "model": "m",
7938                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7939                "max_tokens": 5,
7940                "temperature": 0,
7941            }),
7942        )
7943        .await;
7944        assert_eq!(
7945            manual_turn1["choices"][0]["message"]["content"]
7946                .as_str()
7947                .unwrap(),
7948            reply1
7949        );
7950
7951        // Turn 2, via session: sends ONLY the new message.
7952        let turn2 = post_json(
7953            &session_app,
7954            serde_json::json!({
7955                "model": "m",
7956                "messages": [{"role": "user", "content": "\u{4}\u{5}"}],
7957                "session_id": "s1",
7958                "max_tokens": 5,
7959                "temperature": 0,
7960            }),
7961        )
7962        .await;
7963        let reply2 = turn2["choices"][0]["message"]["content"]
7964            .as_str()
7965            .unwrap()
7966            .to_string();
7967
7968        // Turn 2, manually: the full three-message history
7969        // reconstructed using the REAL reply1 text, with no
7970        // session_id -- must produce byte-identical output.
7971        let manual_turn2 = post_json(
7972            &manual_app,
7973            serde_json::json!({
7974                "model": "m",
7975                "messages": [
7976                    {"role": "user", "content": "\u{1}\u{2}\u{3}"},
7977                    {"role": "assistant", "content": reply1},
7978                    {"role": "user", "content": "\u{4}\u{5}"},
7979                ],
7980                "max_tokens": 5,
7981                "temperature": 0,
7982            }),
7983        )
7984        .await;
7985        assert_eq!(
7986            manual_turn2["choices"][0]["message"]["content"]
7987                .as_str()
7988                .unwrap(),
7989            reply2,
7990            "resuming a session must produce identical output to manually resending the full history"
7991        );
7992    }
7993
7994    /// `lock_cache` must return a usable guard even after the mutex was
7995    /// poisoned by a panic elsewhere.
7996    #[test]
7997    fn lock_cache_recovers_from_a_poisoned_mutex() {
7998        let cache = Arc::new(Mutex::new(ResponseCache::new(10, Duration::from_secs(60))));
7999
8000        let poison_cache = Arc::clone(&cache);
8001        let _ = std::thread::spawn(move || {
8002            let _guard = poison_cache.lock().unwrap();
8003            panic!("simulated panic while holding the lock");
8004        })
8005        .join();
8006
8007        // A plain `.lock().unwrap()` would panic here; lock_cache must not.
8008        let recovered = lock_cache(&cache);
8009        assert_eq!(recovered.stats().entries, 0);
8010    }
8011
8012    #[test]
8013    fn is_cacheable_true_for_greedy_or_seeded_requests() {
8014        let mut req_body = serde_json::json!({
8015            "model": "m",
8016            "messages": [{"role": "user", "content": "hi"}],
8017        });
8018        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8019        assert!(
8020            req.is_cacheable(),
8021            "default (temperature 0) must be cacheable"
8022        );
8023
8024        req_body["temperature"] = serde_json::json!(0.8);
8025        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8026        assert!(
8027            !req.is_cacheable(),
8028            "unseeded sampling must never be cacheable"
8029        );
8030
8031        req_body["seed"] = serde_json::json!(42);
8032        let req: ChatCompletionRequest = serde_json::from_value(req_body).unwrap();
8033        assert!(
8034            req.is_cacheable(),
8035            "sampling with an explicit seed is deterministic and must be cacheable"
8036        );
8037    }
8038
8039    /// A template that grades only the OpenAI triple. `raise_exception`
8040    /// is how a real one rejects a value it does not know, which is what
8041    /// makes the load-time probe able to learn the vocabulary at all.
8042    const GRADED: &str = "{% if reasoning_effort %}\
8043         {% if reasoning_effort not in ['low','medium','high'] %}\
8044           {{ raise_exception('unsupported effort') }}\
8045         {% endif %}E:{{ reasoning_effort }}|{% endif %}\
8046         {% if enable_thinking %}THINK|{% endif %}{{ messages[0].content }}";
8047
8048    fn graded_template() -> chat_template::PromptTemplate {
8049        chat_template::PromptTemplate::from_gguf_metadata(
8050            Some(GRADED),
8051            Some("qwen3"),
8052            false,
8053            true,
8054            None,
8055            None,
8056        )
8057    }
8058
8059    fn chat_request(value: serde_json::Value) -> ChatCompletionRequest {
8060        serde_json::from_value(value).expect("request")
8061    }
8062
8063    /// The wire field reaches the sampler, compiled.
8064    ///
8065    /// Serde is the failure mode here, not the grammar engine: an
8066    /// undeclared field is dropped silently and the caller is served
8067    /// unconstrained text with a 200, which is exactly why `logit_bias`
8068    /// is declared on this struct only to be refused by name.
8069    #[test]
8070    fn a_grammar_on_the_chat_wire_reaches_the_generation_params() {
8071        let req = chat_request(serde_json::json!({
8072            "model": "m",
8073            "messages": [{"role": "user", "content": "hi"}],
8074            "grammar": "root ::= \"a\"+",
8075        }));
8076        req.validate_supported_fields()
8077            .expect("a valid grammar is a valid request");
8078        let params = req
8079            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8080            .expect("a valid grammar compiles at params time too");
8081        assert!(
8082            params.grammar.is_some(),
8083            "the grammar was dropped between the wire and the sampler"
8084        );
8085        assert!(
8086            params.needs_vocab_logits(),
8087            "a grammar request that may fold lm_head into a GPU argmax is \
8088             a grammar request served unconstrained"
8089        );
8090
8091        let plain = chat_request(serde_json::json!({
8092            "model": "m",
8093            "messages": [{"role": "user", "content": "hi"}],
8094        }));
8095        assert!(plain
8096            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8097            .unwrap()
8098            .grammar
8099            .is_none());
8100    }
8101
8102    fn tool_request(tool_choice: serde_json::Value) -> ChatCompletionRequest {
8103        chat_request(serde_json::json!({
8104            "model": "m",
8105            "messages": [{"role": "user", "content": "weather in Rome?"}],
8106            "tools": [weather_tool()],
8107            "tool_choice": tool_choice,
8108        }))
8109    }
8110
8111    /// `tool_choice: "required"` used to be a 501. It now compiles the
8112    /// offered tools into a grammar that rides on the params, which is
8113    /// the only thing every decode path shares.
8114    #[test]
8115    fn a_forced_tool_choice_puts_a_grammar_on_the_generation_params() {
8116        for choice in [
8117            serde_json::json!("required"),
8118            serde_json::json!({"type": "function", "function": {"name": "get_weather"}}),
8119        ] {
8120            let req = tool_request(choice.clone());
8121            req.validate_supported_fields()
8122                .unwrap_or_else(|e| panic!("{choice} is a valid request: {e:?}"));
8123            let params = req
8124                .generation_params_for_template(
8125                    &graded_template(),
8126                    "Qwen3-8B",
8127                    crate::sampling_knobs::SamplerModel::absent(),
8128                )
8129                .unwrap_or_else(|e| panic!("{choice} compiles: {e:?}"));
8130            let grammar = params
8131                .grammar
8132                .as_ref()
8133                .unwrap_or_else(|| panic!("{choice} was accepted and then not enforced"));
8134            assert!(
8135                grammar.is_awaiting_trigger(),
8136                "the model must be free to think before it calls"
8137            );
8138            assert!(
8139                !grammar.allows_eog(),
8140                "{choice} must not be able to end the turn without a call"
8141            );
8142            // The bug that has been fixed three times: a constrained
8143            // request that lets a backend fold lm_head+argmax on device
8144            // is a constrained request served unconstrained. A LAZY
8145            // grammar needs the vocabulary from the FIRST token, because
8146            // its trigger can fire on any of them.
8147            assert!(
8148                params.needs_vocab_logits(),
8149                "{choice} would let a backend return a token id instead of logits"
8150            );
8151            assert!(
8152                !generate::greedy_gpu_fold_allowed(&params),
8153                "{choice} at temperature 0 must still refuse the greedy GPU fold"
8154            );
8155        }
8156    }
8157
8158    /// `auto` and `none` force nothing, and must not acquire a grammar.
8159    #[test]
8160    fn an_unforced_tool_choice_leaves_the_generation_unconstrained() {
8161        for choice in [serde_json::json!("auto"), serde_json::json!("none")] {
8162            let req = tool_request(choice.clone());
8163            req.validate_supported_fields().expect("still supported");
8164            let params = match req.generation_params_for_template(
8165                &graded_template(),
8166                "Qwen3-8B",
8167                crate::sampling_knobs::SamplerModel::absent(),
8168            ) {
8169                Ok(p) => p,
8170                Err((status, _)) => panic!("{choice} has no constraint to compile: {status}"),
8171            };
8172            assert!(
8173                params.grammar.is_none(),
8174                "{choice} does not force a call and must not be constrained"
8175            );
8176        }
8177    }
8178
8179    /// Every refusal a forced choice can produce names the field, and
8180    /// none of them is a silent downgrade to `auto`.
8181    #[test]
8182    fn a_forced_tool_choice_refuses_rather_than_quietly_not_forcing() {
8183        // No tools to choose between.
8184        let req = chat_request(serde_json::json!({
8185            "model": "m",
8186            "messages": [{"role": "user", "content": "hi"}],
8187            "tool_choice": "required",
8188        }));
8189        let (status, _) = req
8190            .validate_supported_fields()
8191            .expect_err("nothing to call");
8192        assert_eq!(status, StatusCode::BAD_REQUEST);
8193
8194        // A name that is not on offer.
8195        let req =
8196            tool_request(serde_json::json!({"type": "function", "function": {"name": "nope"}}));
8197        let (status, Json(body)) = req.validate_supported_fields().expect_err("no such tool");
8198        assert_eq!(status, StatusCode::BAD_REQUEST);
8199        assert_eq!(body["error"]["param"], "tool_choice");
8200
8201        // An object that names nothing at all.
8202        let req = tool_request(serde_json::json!({"type": "function"}));
8203        let (status, _) = req.validate_supported_fields().expect_err("names nothing");
8204        assert_eq!(status, StatusCode::BAD_REQUEST);
8205
8206        // Two constraints on one generation.
8207        let req = chat_request(serde_json::json!({
8208            "model": "m",
8209            "messages": [{"role": "user", "content": "hi"}],
8210            "tools": [weather_tool()],
8211            "tool_choice": "required",
8212            "grammar": "root ::= \"a\"+",
8213        }));
8214        let (status, _) = req
8215            .validate_supported_fields()
8216            .expect_err("a grammar and a forced call are two constraints");
8217        assert_eq!(status, StatusCode::BAD_REQUEST);
8218
8219        // A checkpoint whose wire format has no grammar is refused by
8220        // name at params time, when the served model is known. GLM and
8221        // gemma4 both used to stand here and are forced now;
8222        // muse_glimmer is the one `tool_grammar::wire::shape` still
8223        // refuses, and the refusal says which format and why.
8224        let req = tool_request(serde_json::json!("required"));
8225        let (status, Json(body)) = match req.generation_params_for_template(
8226            &graded_template(),
8227            "muse-glimmer-8b",
8228            crate::sampling_knobs::SamplerModel::absent(),
8229        ) {
8230            Err(e) => e,
8231            Ok(_) => panic!("a muse_glimmer call's boundary is a channel, not a marker"),
8232        };
8233        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
8234        assert!(
8235            body["error"]["message"]
8236                .as_str()
8237                .unwrap()
8238                .contains("muse_glimmer"),
8239            "{body}"
8240        );
8241
8242        // And the format this once refused is served: a served model
8243        // whose name resolves to gemma4 reaches a grammar rather than a
8244        // 501. `generation_params_for_template` is the only place a
8245        // forced choice becomes one, so this is the request-level
8246        // evidence that the wire work is wired.
8247        let req = tool_request(serde_json::json!("required"));
8248        let params = req
8249            .generation_params_for_template(
8250                &graded_template(),
8251                "gemma-4-E2B-it",
8252                crate::sampling_knobs::SamplerModel::absent(),
8253            )
8254            .expect("a gemma4 forced tool_choice is served");
8255        assert!(
8256            params.grammar.is_some(),
8257            "a forced tool_choice must arrive as the generation's grammar"
8258        );
8259    }
8260
8261    /// A grammar that does not parse is refused before any work, and
8262    /// the refusal names the field and the parser's own diagnostic.
8263    #[test]
8264    fn an_unparseable_grammar_on_the_chat_wire_is_a_400() {
8265        let req = chat_request(serde_json::json!({
8266            "model": "m",
8267            "messages": [{"role": "user", "content": "hi"}],
8268            "grammar": "root ::= \"a",
8269        }));
8270        let (status, Json(body)) = req
8271            .validate_supported_fields()
8272            .expect_err("this does not parse");
8273        assert_eq!(status, StatusCode::BAD_REQUEST);
8274        assert_eq!(body["error"]["param"], "grammar");
8275        assert!(
8276            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
8277                .is_err(),
8278            "and again at params time"
8279        );
8280    }
8281
8282    /// `response_format: json_schema` used to be a 501 naming the
8283    /// missing converter. It is served now, and the request-level
8284    /// evidence is that the schema reaches `generation_params` as a
8285    /// grammar -- there is exactly one place a `response_format` is
8286    /// decided, so a route that validated it and then forgot to apply
8287    /// it is the failure this asserts against.
8288    #[test]
8289    fn response_format_json_schema_becomes_the_requests_grammar() {
8290        let req = chat_request(serde_json::json!({
8291            "model": "m",
8292            "messages": [{"role": "user", "content": "hi"}],
8293            "response_format": {
8294                "type": "json_schema",
8295                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
8296            },
8297        }));
8298        req.validate_supported_fields()
8299            .expect("a boolean schema converts");
8300        let params = req
8301            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8302            .expect("and compiles");
8303        let grammar = params.grammar.expect("the schema is the grammar");
8304        let mut g = (*grammar).clone();
8305        g.accept_token(0, b"true").expect("a boolean is accepted");
8306        assert!(g.allows_eog(), "and completes the parse");
8307        assert!(
8308            !params.json_object,
8309            "a schema is not the json_object character-class mask"
8310        );
8311    }
8312
8313    /// A schema the converter will not compile is a 400 naming the
8314    /// keyword, at both the validation and the params seam -- never a
8315    /// 500, and never a grammar that is approximately the schema.
8316    #[test]
8317    fn an_unconvertible_response_format_schema_is_a_400_naming_the_keyword() {
8318        let req = chat_request(serde_json::json!({
8319            "model": "m",
8320            "messages": [{"role": "user", "content": "hi"}],
8321            "response_format": {
8322                "type": "json_schema",
8323                "json_schema": {"name": "x", "schema": {"type": "integer", "minimum": 3}},
8324            },
8325        }));
8326        let (status, Json(body)) = req
8327            .validate_supported_fields()
8328            .expect_err("minimum has no grammar in this port");
8329        assert_eq!(status, StatusCode::BAD_REQUEST);
8330        assert!(
8331            body["error"]["message"]
8332                .as_str()
8333                .expect("a message")
8334                .contains("minimum"),
8335            "the refusal must name the keyword: {body}"
8336        );
8337        assert!(
8338            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
8339                .is_err(),
8340            "and again at params time"
8341        );
8342    }
8343
8344    /// A forced `tool_choice` and a `response_format` schema are two
8345    /// constraints on one generation. The refusal used to be spelled
8346    /// against `self.grammar` alone, so the schema spelling walked past
8347    /// it and `generation_params_for_template` overwrote the schema's
8348    /// grammar with the tool-call one.
8349    #[test]
8350    fn a_forced_tool_choice_and_a_schema_are_two_constraints() {
8351        let req = chat_request(serde_json::json!({
8352            "model": "m",
8353            "messages": [{"role": "user", "content": "hi"}],
8354            "tool_choice": "required",
8355            "tools": [{
8356                "type": "function",
8357                "function": {"name": "f", "parameters": {"type": "object"}},
8358            }],
8359            "response_format": {
8360                "type": "json_schema",
8361                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
8362            },
8363        }));
8364        let (status, Json(body)) = req
8365            .validate_supported_fields()
8366            .expect_err("two constraints, one generation");
8367        assert_eq!(status, StatusCode::BAD_REQUEST);
8368        assert_eq!(body["error"]["param"], "tool_choice");
8369    }
8370
8371    /// A chat client that omits `max_tokens` wants an answer, not
8372    /// OpenAI's legacy 16-token completion fragment.
8373    #[test]
8374    fn an_omitted_output_budget_is_a_whole_answer_not_sixteen_tokens() {
8375        let req = chat_request(serde_json::json!({
8376            "model": "m",
8377            "messages": [{"role": "user", "content": "hi"}],
8378        }));
8379        assert_eq!(req.max_tokens, DEFAULT_CHAT_MAX_TOKENS);
8380    }
8381
8382    /// A knob the wire accepts must reach the sampler. Serde declaring
8383    /// `min_p` is only half of it: the field spent two commits resolved
8384    /// to a hardcoded `0.0` on both routes, which is exactly the
8385    /// silently-dropped-parameter bug, just one layer further in.
8386    #[test]
8387    fn min_p_reaches_the_sampler_from_the_chat_wire() {
8388        let asked = chat_request(serde_json::json!({
8389            "model": "m",
8390            "messages": [{"role": "user", "content": "hi"}],
8391            "min_p": 0.07,
8392        }));
8393        assert_eq!(
8394            asked
8395                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
8396                .expect("knobs")
8397                .min_p,
8398            0.07
8399        );
8400
8401        let silent = chat_request(serde_json::json!({
8402            "model": "m",
8403            "messages": [{"role": "user", "content": "hi"}],
8404        }));
8405        assert_eq!(
8406            silent
8407                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
8408                .expect("knobs")
8409                .min_p,
8410            0.0,
8411            "an unset min_p must be off, not llama.cpp's CLI default"
8412        );
8413    }
8414
8415    /// The whole-response cache is keyed on the sampler settings, and a
8416    /// setting left OUT of that key means two requests differing only in
8417    /// it share one answer: the second caller silently gets output
8418    /// computed under the first caller's parameters.
8419    ///
8420    /// Every knob the wire accepts is checked, not just the new one --
8421    /// this is the assertion that would have caught `min_p` being added
8422    /// to the sampler and forgotten here.
8423    #[test]
8424    fn no_sampler_knob_is_missing_from_the_cache_key() {
8425        let base = serde_json::json!({
8426            "model": "m",
8427            "messages": [{"role": "user", "content": "hi"}],
8428            "seed": 1,
8429        });
8430        let key_for = |body: serde_json::Value| {
8431            let req = chat_request(body);
8432            let params = req
8433                .generation_params(crate::sampling_knobs::SamplerModel::absent())
8434                .expect("params");
8435            req.cache_key("prompt", &params)
8436        };
8437        let baseline = key_for(base.clone());
8438        for (knob, value) in [
8439            ("temperature", serde_json::json!(0.5)),
8440            ("top_p", serde_json::json!(0.9)),
8441            ("min_p", serde_json::json!(0.05)),
8442            ("top_k", serde_json::json!(40)),
8443            ("repetition_penalty", serde_json::json!(1.1)),
8444            ("presence_penalty", serde_json::json!(0.3)),
8445            ("frequency_penalty", serde_json::json!(0.3)),
8446            (
8447                "samplers",
8448                serde_json::json!(["penalties", "top_p", "top_k", "min_p", "temperature"]),
8449            ),
8450        ] {
8451            let mut body = base.clone();
8452            body[knob] = value;
8453            assert_ne!(
8454                key_for(body),
8455                baseline,
8456                "`{knob}` is not in the cache key: two requests differing \
8457                 only in it would share one cached answer"
8458            );
8459        }
8460    }
8461
8462    /// The sampler half's twin, for the constraints. Each of these
8463    /// changes the answer and changes NOTHING about the rendered
8464    /// prompt, so an omission is invisible until a caller compares two
8465    /// answers it never sees side by side (#35).
8466    ///
8467    /// `grammar` here is the wire field; `response_format:
8468    /// {"type":"json_schema"}` and a forced `tool_choice` compile to a
8469    /// grammar through the same `GenerationParams::grammar`, so they are
8470    /// keyed by the same field being keyed at all.
8471    #[test]
8472    fn no_constraint_is_missing_from_the_cache_key() {
8473        let base = serde_json::json!({
8474            "model": "m",
8475            "messages": [{"role": "user", "content": "pick one"}],
8476        });
8477        let key_for = |body: serde_json::Value| {
8478            let req = chat_request(body);
8479            let params = req
8480                .generation_params(crate::sampling_knobs::SamplerModel::absent())
8481                .expect("params");
8482            req.cache_key("prompt", &params)
8483        };
8484        let baseline = key_for(base.clone());
8485        for (field, value) in [
8486            ("grammar", serde_json::json!("root ::= \"yes\" | \"no\"")),
8487            (
8488                "response_format",
8489                serde_json::json!({"type": "json_object"}),
8490            ),
8491            (
8492                "response_format",
8493                serde_json::json!({"type": "json_schema", "json_schema": {
8494                    "name": "answer",
8495                    "schema": {"type": "object", "properties": {"a": {"type": "string"}}}
8496                }}),
8497            ),
8498            ("ignore_eos", serde_json::json!(true)),
8499            ("stop", serde_json::json!(["\n"])),
8500            ("max_tokens", serde_json::json!(7)),
8501        ] {
8502            let mut body = base.clone();
8503            body[field] = value.clone();
8504            assert_ne!(
8505                key_for(body),
8506                baseline,
8507                "`{field}: {value}` is not in the cache key: two requests \
8508                 differing only in it would share one cached answer"
8509            );
8510        }
8511    }
8512
8513    /// Serde already tells absent from zero -- an absent field became
8514    /// the default -- so a 0 here is one the caller wrote, and a
8515    /// zero-token budget is a request that can never become decodable.
8516    #[test]
8517    fn an_explicit_zero_output_budget_is_a_client_error() {
8518        let req = chat_request(serde_json::json!({
8519            "model": "m",
8520            "messages": [{"role": "user", "content": "hi"}],
8521            "max_tokens": 0,
8522        }));
8523        let (status, body) = req.validate_supported_fields().expect_err("rejected");
8524        assert_eq!(status, StatusCode::BAD_REQUEST);
8525        assert_eq!(body["error"]["param"], serde_json::json!("max_tokens"));
8526    }
8527
8528    /// The direction that had no wire path at all before: every request
8529    /// rendered in thinking mode because only the ON branch existed.
8530    #[test]
8531    fn a_request_can_turn_thinking_off() {
8532        let template = graded_template();
8533        for body in [
8534            serde_json::json!({
8535                "model": "m",
8536                "messages": [{"role": "user", "content": "hi"}],
8537                "reasoning_effort": "none",
8538            }),
8539            serde_json::json!({
8540                "model": "m",
8541                "messages": [{"role": "user", "content": "hi"}],
8542                "thinking": {"type": "disabled"},
8543            }),
8544        ] {
8545            let kwargs = chat_request(body).resolve_template_kwargs(&template);
8546            assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
8547            assert_eq!(kwargs["thinking_mode"], serde_json::json!("disabled"));
8548            // And `none` must not have been rounded onto a real gear on
8549            // the way: "do not think" is not "think a little".
8550            assert!(!kwargs.contains_key("reasoning_effort"));
8551        }
8552    }
8553
8554    /// The switch is what the caller reached for last; the gear is what
8555    /// they would have used had thinking been on.
8556    #[test]
8557    fn a_disabled_switch_beats_an_effort_in_the_same_request() {
8558        let template = graded_template();
8559        let kwargs = chat_request(serde_json::json!({
8560            "model": "m",
8561            "messages": [{"role": "user", "content": "hi"}],
8562            "reasoning_effort": "high",
8563            "thinking": {"type": "disabled"},
8564        }))
8565        .resolve_template_kwargs(&template);
8566        assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
8567        assert!(!kwargs.contains_key("reasoning_effort"));
8568    }
8569
8570    /// Read as "on", a misspelled switch silently serves the opposite
8571    /// of what was asked for.
8572    #[test]
8573    fn an_unrecognized_thinking_switch_is_refused_rather_than_read_as_on() {
8574        let req = chat_request(serde_json::json!({
8575            "model": "m",
8576            "messages": [{"role": "user", "content": "hi"}],
8577            "thinking": {"type": "disable"},
8578        }));
8579        let (status, _) = req.validate_supported_fields().expect_err("rejected");
8580        assert_eq!(status, StatusCode::BAD_REQUEST);
8581    }
8582
8583    /// A caller who steered the template themselves has said what they
8584    /// want; merging a protocol default in would let it contradict them.
8585    #[test]
8586    fn an_explicit_template_kwarg_stands_the_protocol_knobs_down() {
8587        let template = graded_template();
8588        let kwargs = chat_request(serde_json::json!({
8589            "model": "m",
8590            "messages": [{"role": "user", "content": "hi"}],
8591            "reasoning_effort": "none",
8592            "chat_template_kwargs": {"enable_thinking": true},
8593        }))
8594        .resolve_template_kwargs(&template);
8595        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
8596    }
8597
8598    /// The acceptance criterion for effort plumbing: an off-vocabulary
8599    /// value is quantized onto the nearest gear the checkpoint really
8600    /// grades, and the request renders instead of failing.
8601    #[test]
8602    fn an_off_vocabulary_reasoning_effort_is_quantized_rather_than_interpolated() {
8603        let template = graded_template();
8604        let req = chat_request(serde_json::json!({
8605            "model": "m",
8606            "messages": [{"role": "user", "content": "hi"}],
8607            "reasoning_effort": "minimal",
8608        }));
8609        let kwargs = req.resolve_template_kwargs(&template);
8610        assert_eq!(kwargs["reasoning_effort"], serde_json::json!("low"));
8611        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
8612        assert!(prompt.starts_with("E:low|"), "{prompt}");
8613    }
8614
8615    /// The other half of the same rule: a value no gear is close enough
8616    /// to is dropped, so the checkpoint's own default applies rather
8617    /// than an unknown string reaching the prompt.
8618    #[test]
8619    fn an_effort_with_no_near_gear_is_dropped_so_the_template_default_applies() {
8620        let template = graded_template();
8621        let req = chat_request(serde_json::json!({
8622            "model": "m",
8623            "messages": [{"role": "user", "content": "hi"}],
8624            "chat_template_kwargs": {"reasoning_effort": "none"},
8625        }));
8626        let kwargs = req.resolve_template_kwargs(&template);
8627        assert!(!kwargs.contains_key("reasoning_effort"));
8628        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
8629        assert_eq!(prompt, "hi");
8630    }
8631
8632    /// `chat_template_kwargs` is the specific spelling and wins over the
8633    /// top-level one, which is what a caller who wrote both meant.
8634    #[test]
8635    fn chat_template_kwargs_wins_over_the_top_level_reasoning_effort() {
8636        let template = graded_template();
8637        let req = chat_request(serde_json::json!({
8638            "model": "m",
8639            "messages": [{"role": "user", "content": "hi"}],
8640            "reasoning_effort": "low",
8641            "chat_template_kwargs": {"reasoning_effort": "high"},
8642        }));
8643        assert_eq!(
8644            req.resolve_template_kwargs(&template)["reasoning_effort"],
8645            serde_json::json!("high")
8646        );
8647    }
8648
8649    /// Offering tools turns thinking on even when the caller asked for
8650    /// nothing: some encoders emit well-formed calls only in thinking
8651    /// mode.
8652    #[test]
8653    fn offering_tools_turns_thinking_on_by_itself() {
8654        let template = graded_template();
8655        let quiet = chat_request(serde_json::json!({
8656            "model": "m",
8657            "messages": [{"role": "user", "content": "hi"}],
8658        }));
8659        assert!(!quiet
8660            .resolve_template_kwargs(&template)
8661            .contains_key("enable_thinking"));
8662
8663        let with_tools = chat_request(serde_json::json!({
8664            "model": "m",
8665            "messages": [{"role": "user", "content": "hi"}],
8666            "tools": [{"type": "function", "function": {"name": "get_weather"}}],
8667        }));
8668        let kwargs = with_tools.resolve_template_kwargs(&template);
8669        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
8670        let prompt =
8671            prompt_from_messages(&with_tools.messages, &template, &[], kwargs).expect("renders");
8672        assert!(prompt.starts_with("THINK|"), "{prompt}");
8673    }
8674
8675    /// The reason `force_reasoning` could only ever be `false` before:
8676    /// no template could open a block in the prompt, because no kwargs
8677    /// reached one. Now that they do, the parser has to start inside it
8678    /// -- and the evidence is the rendered prompt, not the model name.
8679    #[test]
8680    fn a_prompt_that_opens_the_reasoning_block_makes_the_first_token_reasoning() {
8681        let opener = chat_template::PromptTemplate::from_gguf_metadata(
8682            Some("{{ messages[0].content }}{% if enable_thinking %}<think>{% endif %}"),
8683            Some("qwen3"),
8684            false,
8685            true,
8686            None,
8687            None,
8688        );
8689        let req = chat_request(serde_json::json!({
8690            "model": "m",
8691            "messages": [{"role": "user", "content": "hi"}],
8692            "chat_template_kwargs": {"enable_thinking": true},
8693        }));
8694        let kwargs = req.resolve_template_kwargs(&opener);
8695        let prompt = prompt_from_messages(&req.messages, &opener, &[], kwargs).expect("renders");
8696        assert!(prompt.ends_with("<think>"), "{prompt}");
8697
8698        // No opening marker will ever arrive, so unparsed this whole
8699        // deliberation would have been served as the answer.
8700        let posture = output::OutputPosture::resolve("Qwen3-8B", &prompt);
8701        let (message, _) = build_response_message(
8702            "weighing it up</think>Paris.".to_string(),
8703            &[],
8704            posture,
8705            "stop",
8706        );
8707        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
8708        assert_eq!(message.content.as_deref(), Some("Paris."));
8709
8710        // Same text, a prompt that did not open the block: the model
8711        // wrote a stray closer and it stays content.
8712        let closed = output::OutputPosture::resolve("Qwen3-8B", "<|im_start|>assistant\n");
8713        let (message, _) = build_response_message(
8714            "weighing it up</think>Paris.".to_string(),
8715            &[],
8716            closed,
8717            "stop",
8718        );
8719        assert_eq!(message.reasoning_content, None);
8720    }
8721
8722    #[test]
8723    fn stop_param_accepts_both_single_string_and_array() {
8724        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
8725            "model": "m",
8726            "messages": [{"role": "user", "content": "hi"}],
8727            "stop": "END",
8728        }))
8729        .unwrap();
8730        assert_eq!(req.stop_sequences(), vec!["END".to_string()]);
8731
8732        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
8733            "model": "m",
8734            "messages": [{"role": "user", "content": "hi"}],
8735            "stop": ["A", "B"],
8736        }))
8737        .unwrap();
8738        assert_eq!(req.stop_sequences(), vec!["A".to_string(), "B".to_string()]);
8739    }
8740
8741    #[test]
8742    fn run_generation_rejects_out_of_vocab_tokens_instead_of_panicking() {
8743        let model = test_model();
8744        let result = run_generation(
8745            &model,
8746            "hello",
8747            &greedy_params(4),
8748            None,
8749            None,
8750            None,
8751            None,
8752            None,
8753            None,
8754        );
8755        assert!(matches!(
8756            result,
8757            Err(generate::DecodeError::TokenOutOfVocab { .. })
8758        ));
8759    }
8760
8761    /// A pool that *could* serve this request but is momentarily fully
8762    /// held is the server being behind: 503, and retrying is honest
8763    /// advice because the blocks really do come back.
8764    #[test]
8765    fn run_generation_honors_an_exhausted_kv_pool_and_maps_it_to_a_503() {
8766        let model = test_model(); // 2 layers -> 2 blocks
8767        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
8768        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
8769
8770        let holder_pool = Arc::clone(&pool);
8771        let holder = std::thread::spawn(move || {
8772            let mut held = frink_core::cache::KvCache::with_pool(1, 1, holder_pool, 0).unwrap();
8773            held.push(&[0.0], &[0.0]).unwrap(); // crosses into the second block
8774            std::thread::sleep(Duration::from_millis(200));
8775            drop(held);
8776        });
8777        std::thread::sleep(Duration::from_millis(15));
8778
8779        let config = generate::KvPoolConfig {
8780            pool,
8781            queue_wait: Duration::ZERO,
8782        };
8783        let result = run_generation(
8784            &model,
8785            &prompt,
8786            &greedy_params(4),
8787            Some(&config),
8788            None,
8789            None,
8790            None,
8791            None,
8792            None,
8793        );
8794        assert!(matches!(
8795            result,
8796            Err(generate::DecodeError::KvPoolExhausted)
8797        ));
8798
8799        let (status, _body) = decode_error_response(result.unwrap_err());
8800        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
8801        holder.join().unwrap();
8802    }
8803
8804    /// The same endpoint, the same pool size, a request too big for the
8805    /// *whole* pool: a 400 rather than a 503, because an idle server
8806    /// refuses it identically and `Retry-After` would be a promise
8807    /// nothing can keep.
8808    ///
8809    /// Confirmed to FAIL when `generate`'s `pool_immovable_refusal`
8810    /// check is removed: the status comes back 503.
8811    #[test]
8812    fn a_request_too_big_for_the_whole_pool_is_a_400_not_a_retryable_503() {
8813        let model = test_model(); // 2 layers
8814        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
8815        // One block, two layers: no schedule ever serves this.
8816        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 1)));
8817        let config = generate::KvPoolConfig {
8818            pool,
8819            queue_wait: Duration::ZERO,
8820        };
8821
8822        let result = run_generation(
8823            &model,
8824            &prompt,
8825            &greedy_params(4),
8826            Some(&config),
8827            None,
8828            None,
8829            None,
8830            None,
8831            None,
8832        );
8833        let err = result.expect_err("one block cannot hold two layers' caches");
8834        assert!(
8835            matches!(
8836                &err,
8837                generate::DecodeError::KvBudgetExceeded { binding, .. }
8838                    if *binding == frink_models::Ceiling::DeviceMemory.code()
8839            ),
8840            "expected an immovable device-memory refusal, got {err:?}"
8841        );
8842        let (status, _body) = decode_error_response(err);
8843        assert_eq!(status, StatusCode::BAD_REQUEST);
8844    }
8845
8846    /// A full admission queue is the server being behind, not the
8847    /// client being wrong: 503, with the wait hint in the body (and the
8848    /// `Retry-After` header stamped by `limits::retry_after`) and the
8849    /// depth and cap named so an operator can tell a retry storm from a
8850    /// single oversized request.
8851    #[test]
8852    fn decode_error_response_maps_a_full_queue_to_a_retryable_503() {
8853        let (status, Json(body)) = decode_error_response(generate::DecodeError::QueueFull {
8854            queued: 512,
8855            cap: 512,
8856        });
8857        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
8858        assert_eq!(body["error"]["retry_after_seconds"], 1);
8859        let message = body["error"]["message"].as_str().expect("message");
8860        assert!(message.contains("512"), "{message}");
8861    }
8862
8863    #[test]
8864    fn decode_error_response_omits_a_retry_hint_for_an_unretryable_error() {
8865        let (_status, Json(body)) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
8866            token: 99,
8867            vocab_size: 32,
8868        });
8869        assert!(
8870            body["error"]["retry_after_seconds"].is_null(),
8871            "retrying a prompt this model cannot tokenize never helps"
8872        );
8873    }
8874
8875    #[test]
8876    fn decode_error_response_maps_token_out_of_vocab_to_bad_request() {
8877        let (status, _body) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
8878            token: 99,
8879            vocab_size: 32,
8880        });
8881        assert_eq!(status, StatusCode::BAD_REQUEST);
8882    }
8883
8884    #[test]
8885    fn run_generation_succeeds_and_releases_blocks_when_the_pool_has_room() {
8886        let model = test_model(); // 2 layers
8887        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
8888        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
8889        let config = generate::KvPoolConfig {
8890            pool: pool.clone(),
8891            queue_wait: Duration::ZERO,
8892        };
8893
8894        let (choices, _usage) = run_generation(
8895            &model,
8896            &prompt,
8897            &greedy_params(4),
8898            Some(&config),
8899            None,
8900            None,
8901            None,
8902            None,
8903            None,
8904        )
8905        .unwrap();
8906        assert_eq!(choices[0].finish, FinishReason::Length);
8907        assert_eq!(
8908            pool.lock().unwrap().free_blocks(),
8909            2,
8910            "a completed request must return its blocks to the pool"
8911        );
8912    }
8913
8914    /// The core concurrency claim: two requests using the *same* `Arc<Model>`
8915    /// must be able to run their (independent, per-call) KV caches
8916    /// concurrently without interfering with each other or needing any
8917    /// shared lock around the model itself.
8918    #[tokio::test]
8919    async fn concurrent_requests_against_the_same_model_do_not_interfere() {
8920        let model = Arc::new(test_model());
8921        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
8922
8923        let mut handles = Vec::new();
8924        for _ in 0..8 {
8925            let model = Arc::clone(&model);
8926            let prompt = prompt.clone();
8927            handles.push(tokio::task::spawn_blocking(move || {
8928                run_generation(
8929                    &model,
8930                    &prompt,
8931                    &greedy_params(6),
8932                    None,
8933                    None,
8934                    None,
8935                    None,
8936                    None,
8937                    None,
8938                )
8939                .unwrap()
8940            }));
8941        }
8942
8943        let mut results = Vec::new();
8944        for h in handles {
8945            results.push(h.await.unwrap());
8946        }
8947        // Same prompt, same seed, same (greedy) sampling, same
8948        // immutable model -> every concurrent run must produce
8949        // identical output, proving no request's KV cache leaked into
8950        // another's.
8951        for r in &results[1..] {
8952            // `.0` is the per-choice `(finish_reason, text)` list and
8953            // `.1` the usage, so this one comparison covers both the
8954            // text and the reason it stopped.
8955            assert_eq!(r.0, results[0].0, "choices must match");
8956            assert_eq!(
8957                r.1.prompt_tokens, results[0].1.prompt_tokens,
8958                "prompt token count must match"
8959            );
8960            assert_eq!(
8961                r.1.completion_tokens, results[0].1.completion_tokens,
8962                "completion token count must match"
8963            );
8964        }
8965    }
8966
8967    /// A real, minimal safetensors shard: JSON header (name -> real
8968    /// dtype/shape/`data_offsets`) followed by the concatenated raw
8969    /// F32 bytes -- exactly the format `ShardedSafetensors::open_index`
8970    /// parses, hand-built here rather than depending on
8971    /// `frink-models::kimi_loader`'s own private test helpers (not
8972    /// visible across the crate boundary).
8973    fn write_safetensors_shard(tensors: &[(String, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
8974        let mut header_entries = Vec::new();
8975        let mut data = Vec::new();
8976        for (name, shape, values) in tensors {
8977            let start = data.len();
8978            for v in values {
8979                data.extend_from_slice(&v.to_le_bytes());
8980            }
8981            let end = data.len();
8982            let shape_str = shape
8983                .iter()
8984                .map(|d| d.to_string())
8985                .collect::<Vec<_>>()
8986                .join(",");
8987            header_entries.push(format!(
8988                "\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{shape_str}],\"data_offsets\":[{start},{end}]}}"
8989            ));
8990        }
8991        let header = format!("{{{}}}", header_entries.join(","));
8992        let header_bytes = header.as_bytes();
8993        let mut out = Vec::with_capacity(8 + header_bytes.len() + data.len());
8994        out.extend_from_slice(&(header_bytes.len() as u64).to_le_bytes());
8995        out.extend_from_slice(header_bytes);
8996        out.extend_from_slice(&data);
8997        out
8998    }
8999
9000    /// Builds a small but completely real Kimi K3 checkpoint directory
9001    /// on disk (real `model.safetensors.index.json` + shard bytes +
9002    /// `tiktoken.model`, the exact file layout `frink-cli`'s
9003    /// `run-kimi` command expects) and loads it through
9004    /// `model::load_kimi_checkpoint_with_config` (the same real loading
9005    /// logic `model::load()` uses for `FRINK_MODEL_PATH` pointing at a
9006    /// directory, parametrized here only so the checkpoint can be small
9007    /// -- see that function's doc comment). Shared by every test that
9008    /// needs a real, loaded `KimiLoaded` rather than duplicating this
9009    /// setup per test.
9010    fn build_synthetic_kimi_loaded() -> model::KimiLoaded {
9011        use frink_models::config::{AttentionKind, KdaConfig, KimiHybridAttention, MlaConfig};
9012        use frink_models::kimi_loader::KimiRealHparams;
9013        use frink_moe::{GatingFunction, MoeLayerConfig};
9014
9015        let hidden_dim = 8;
9016        let kda_num_heads = 2;
9017        let kda_head_dim = 3;
9018        let kda_proj = kda_num_heads * kda_head_dim;
9019        let conv_kernel = 4;
9020        let dense_intermediate = 5;
9021        // One token per byte value -- enough to round-trip a simple
9022        // ASCII prompt through the real tiktoken-format vocab below,
9023        // matching `kimi_generate`'s own test convention.
9024        let vocab_size = 256;
9025        let mla_num_heads = 1;
9026        let mla_q_lora_rank = 2;
9027        let mla_kv_lora_rank = 2;
9028        let mla_qk_nope_head_dim = 2;
9029        let mla_qk_rope_head_dim = 2;
9030        let mla_v_head_dim = 2;
9031
9032        let model_cfg = frink_models::ModelConfig {
9033            rope_layers: frink_models::rope_layers::RopeLayers::All,
9034            layer_shapes: frink_models::layer_shapes::LayerShapes::Uniform,
9035            name: "synthetic-kimi-server-test",
9036            n_layers: 1,
9037            n_mtp_blocks: 0,
9038            hidden_dim,
9039            n_heads: 1,
9040            n_kv_heads: 1,
9041            head_dim: 4,
9042            v_head_dim: None,
9043            vocab_size,
9044            rope_theta: 10000.0,
9045            rms_norm_eps: 1e-5,
9046            post_norm_eps: 1e-5,
9047            sliding_window: None,
9048            moe: MoeLayerConfig {
9049                expert_weights_scale: 1.0,
9050                routed_weight_before_ffn: false,
9051                n_experts: 1,
9052                n_experts_active: 1,
9053                n_shared_experts: 0,
9054                hidden_dim,
9055                expert_ffn_dim: 4,
9056                gating: GatingFunction::Sigmoid,
9057                norm_topk_prob: true,
9058                expert_group_count: None,
9059                expert_group_used_count: None,
9060            },
9061            // Layer 0 is the sole dense leading layer, using KDA
9062            // attention (real Kimi K3's own layer-0 shape) -- the
9063            // 1-indexed `kda_layers`/`full_attn_layers` convention is
9064            // `ModelConfig::layer_attention_kind`'s, not this test's.
9065            n_dense_leading_layers: 1,
9066            moe_interleave_step: None,
9067            norm_function: frink_models::norm::NormFunction::Rms,
9068            attention: AttentionKind::KimiHybrid(KimiHybridAttention {
9069                kda_layers: vec![1],
9070                full_attn_layers: vec![],
9071                mla: MlaConfig {
9072                    num_heads: mla_num_heads,
9073                    q_lora_rank: mla_q_lora_rank,
9074                    kv_lora_rank: mla_kv_lora_rank,
9075                    qk_nope_head_dim: mla_qk_nope_head_dim,
9076                    qk_rope_head_dim: mla_qk_rope_head_dim,
9077                    v_head_dim: mla_v_head_dim,
9078                    use_output_gate: true,
9079                    rope: None,
9080                },
9081                kda: KdaConfig {
9082                    num_heads: kda_num_heads,
9083                    head_dim: kda_head_dim,
9084                    short_conv_kernel_size: conv_kernel,
9085                    gate_lower_bound: -5.0,
9086                    use_full_rank_gate: true,
9087                },
9088            }),
9089            rope_freqs: None,
9090            rope_attn_factor: 1.0,
9091            rope_dim: None,
9092            rope_dim_swa: None,
9093            rope_freqs_long: None,
9094            rope_freqs_short: None,
9095            rope_orig_ctx: None,
9096            rope_layout: frink_models::config::RopeLayout::Neox,
9097            qk_norm_style: frink_models::capability::QkNormStyle::WholeVector,
9098            swa_layers: frink_models::swa_layers::SwaLayers::All,
9099            attn_logit_softcap: None,
9100            final_logit_softcap: None,
9101            embedding_scale: None,
9102            residual_scale: None,
9103            normed_residual_scale: None,
9104            clamp_kqv: None,
9105            attn_temperature: None,
9106            router_input: frink_models::router_input::RouterInput::NormedFfnInput,
9107            block_sub_norms: false,
9108            parallel_residual: false,
9109            learned_positions: false,
9110            attn_value_scale: None,
9111            alibi_max_bias: None,
9112            layer_loops: None,
9113            skip_stream: false,
9114            parallel_ssm: false,
9115            swa_chunked: false,
9116            weightless_qk_norm: false,
9117            logit_multiplier: None,
9118            attention_scale: None,
9119            rope_theta_swa: None,
9120            ffn_activation: frink_models::config::FfnActivation::Swiglu,
9121            best_effort_fields: &["synthetic test config, not a real preset"],
9122        };
9123        let hp = KimiRealHparams {
9124            hidden_dim,
9125            kda_num_heads,
9126            kda_head_dim,
9127            mla_num_heads,
9128            mla_q_lora_rank,
9129            mla_kv_lora_rank,
9130            mla_qk_nope_head_dim,
9131            mla_qk_rope_head_dim,
9132            mla_v_head_dim,
9133            dense_intermediate_dim: dense_intermediate,
9134            moe_hidden_dim: hidden_dim,
9135            moe_intermediate_dim: 4,
9136            n_experts: 1,
9137            num_shared_experts: 0,
9138        };
9139
9140        // Every real tensor name `kimi_loader::load_kimi_layer` (dense
9141        // FFN + KDA attention + block residual) and
9142        // `load_kimi_checkpoint` (top-level) actually read.
9143        let prefix = "language_model.model.layers.0";
9144        let mut tensors: Vec<(String, Vec<usize>, Vec<f32>)> = Vec::new();
9145        let push = |tensors: &mut Vec<(String, Vec<usize>, Vec<f32>)>,
9146                    name: String,
9147                    shape: Vec<usize>,
9148                    n: usize| {
9149            tensors.push((name, shape, vec![0.01f32; n]));
9150        };
9151        push(
9152            &mut tensors,
9153            format!("{prefix}.input_layernorm.weight"),
9154            vec![hidden_dim],
9155            hidden_dim,
9156        );
9157        push(
9158            &mut tensors,
9159            format!("{prefix}.post_attention_layernorm.weight"),
9160            vec![hidden_dim],
9161            hidden_dim,
9162        );
9163        push(
9164            &mut tensors,
9165            format!("{prefix}.self_attention_res_norm.weight"),
9166            vec![hidden_dim],
9167            hidden_dim,
9168        );
9169        push(
9170            &mut tensors,
9171            format!("{prefix}.self_attention_res_proj.weight"),
9172            vec![1, hidden_dim],
9173            hidden_dim,
9174        );
9175        push(
9176            &mut tensors,
9177            format!("{prefix}.mlp_res_norm.weight"),
9178            vec![hidden_dim],
9179            hidden_dim,
9180        );
9181        push(
9182            &mut tensors,
9183            format!("{prefix}.mlp_res_proj.weight"),
9184            vec![1, hidden_dim],
9185            hidden_dim,
9186        );
9187        push(
9188            &mut tensors,
9189            format!("{prefix}.self_attn.q_proj.weight"),
9190            vec![kda_proj, hidden_dim],
9191            kda_proj * hidden_dim,
9192        );
9193        push(
9194            &mut tensors,
9195            format!("{prefix}.self_attn.k_proj.weight"),
9196            vec![kda_proj, hidden_dim],
9197            kda_proj * hidden_dim,
9198        );
9199        push(
9200            &mut tensors,
9201            format!("{prefix}.self_attn.v_proj.weight"),
9202            vec![kda_proj, hidden_dim],
9203            kda_proj * hidden_dim,
9204        );
9205        push(
9206            &mut tensors,
9207            format!("{prefix}.self_attn.q_conv1d.weight"),
9208            vec![kda_proj, 1, conv_kernel],
9209            kda_proj * conv_kernel,
9210        );
9211        push(
9212            &mut tensors,
9213            format!("{prefix}.self_attn.k_conv1d.weight"),
9214            vec![kda_proj, 1, conv_kernel],
9215            kda_proj * conv_kernel,
9216        );
9217        push(
9218            &mut tensors,
9219            format!("{prefix}.self_attn.v_conv1d.weight"),
9220            vec![kda_proj, 1, conv_kernel],
9221            kda_proj * conv_kernel,
9222        );
9223        push(
9224            &mut tensors,
9225            format!("{prefix}.self_attn.A_log"),
9226            vec![kda_num_heads],
9227            kda_num_heads,
9228        );
9229        push(
9230            &mut tensors,
9231            format!("{prefix}.self_attn.f_a_proj.weight"),
9232            vec![kda_head_dim, hidden_dim],
9233            kda_head_dim * hidden_dim,
9234        );
9235        push(
9236            &mut tensors,
9237            format!("{prefix}.self_attn.f_b_proj.weight"),
9238            vec![kda_proj, kda_head_dim],
9239            kda_proj * kda_head_dim,
9240        );
9241        push(
9242            &mut tensors,
9243            format!("{prefix}.self_attn.dt_bias"),
9244            vec![kda_proj],
9245            kda_proj,
9246        );
9247        push(
9248            &mut tensors,
9249            format!("{prefix}.self_attn.b_proj.weight"),
9250            vec![kda_num_heads, hidden_dim],
9251            kda_num_heads * hidden_dim,
9252        );
9253        push(
9254            &mut tensors,
9255            format!("{prefix}.self_attn.g_proj.weight"),
9256            vec![kda_proj, hidden_dim],
9257            kda_proj * hidden_dim,
9258        );
9259        push(
9260            &mut tensors,
9261            format!("{prefix}.self_attn.o_norm.weight"),
9262            vec![kda_head_dim],
9263            kda_head_dim,
9264        );
9265        push(
9266            &mut tensors,
9267            format!("{prefix}.self_attn.o_proj.weight"),
9268            vec![hidden_dim, kda_proj],
9269            hidden_dim * kda_proj,
9270        );
9271        push(
9272            &mut tensors,
9273            format!("{prefix}.mlp.gate_proj.weight"),
9274            vec![dense_intermediate, hidden_dim],
9275            dense_intermediate * hidden_dim,
9276        );
9277        push(
9278            &mut tensors,
9279            format!("{prefix}.mlp.up_proj.weight"),
9280            vec![dense_intermediate, hidden_dim],
9281            dense_intermediate * hidden_dim,
9282        );
9283        push(
9284            &mut tensors,
9285            format!("{prefix}.mlp.down_proj.weight"),
9286            vec![hidden_dim, dense_intermediate],
9287            hidden_dim * dense_intermediate,
9288        );
9289        push(
9290            &mut tensors,
9291            "language_model.model.embed_tokens.weight".to_string(),
9292            vec![vocab_size, hidden_dim],
9293            vocab_size * hidden_dim,
9294        );
9295        push(
9296            &mut tensors,
9297            "language_model.lm_head.weight".to_string(),
9298            vec![vocab_size, hidden_dim],
9299            vocab_size * hidden_dim,
9300        );
9301        push(
9302            &mut tensors,
9303            "language_model.model.norm.weight".to_string(),
9304            vec![hidden_dim],
9305            hidden_dim,
9306        );
9307        push(
9308            &mut tensors,
9309            "language_model.model.output_attn_res_norm.weight".to_string(),
9310            vec![hidden_dim],
9311            hidden_dim,
9312        );
9313        push(
9314            &mut tensors,
9315            "language_model.model.output_attn_res_proj.weight".to_string(),
9316            vec![1, hidden_dim],
9317            hidden_dim,
9318        );
9319
9320        // Unique per CALL, not per (pid, vocab_size). Both callers of
9321        // this helper use the same `vocab_size`, so keying on it gave
9322        // the two tests one directory -- and `fs::write` opens with
9323        // `O_TRUNC`, so one test rewriting the shard truncated it to
9324        // zero while the other's `frink-safetensors` MMAP of that
9325        // exact file was live. Touching a mapping past the end of its
9326        // file is SIGBUS, which kills the whole test binary rather than
9327        // failing one test, and only when the two happen to overlap --
9328        // so it showed up as an occasional unexplained CI crash.
9329        //
9330        // A counter and not a thread id: the harness reuses threads
9331        // across tests, so two sequential tests can share one.
9332        static FIXTURE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
9333        let dir = std::env::temp_dir().join(format!(
9334            "frink_server_kimi_e2e_test_{}_{}",
9335            std::process::id(),
9336            FIXTURE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
9337        ));
9338        std::fs::create_dir_all(&dir).unwrap();
9339        let shard_bytes = write_safetensors_shard(&tensors);
9340        std::fs::write(dir.join("shard0.safetensors"), &shard_bytes).unwrap();
9341        let map_entries: Vec<String> = tensors
9342            .iter()
9343            .map(|(name, ..)| format!("\"{name}\":\"shard0.safetensors\""))
9344            .collect();
9345        let index = format!("{{\"weight_map\":{{{}}}}}", map_entries.join(","));
9346        std::fs::write(dir.join("model.safetensors.index.json"), &index).unwrap();
9347
9348        // A real tiktoken-format vocab file: one base64-encoded byte
9349        // plus its rank per line -- enough to round-trip an ASCII
9350        // prompt without needing the real 163584-entry Kimi K3 vocab.
9351        use base64::Engine;
9352        let vocab_lines: Vec<String> = (0..vocab_size as u32)
9353            .map(|b| {
9354                let b64 = base64::engine::general_purpose::STANDARD.encode([b as u8]);
9355                format!("{b64} {b}")
9356            })
9357            .collect();
9358        std::fs::write(dir.join("tiktoken.model"), vocab_lines.join("\n")).unwrap();
9359
9360        let loaded = model::load_kimi_checkpoint_with_config(dir.to_str().unwrap(), model_cfg, hp)
9361            .expect("must load the synthetic Kimi checkpoint end to end");
9362        std::fs::remove_dir_all(&dir).ok();
9363        loaded
9364    }
9365
9366    /// The real end-to-end proof for Kimi-through-the-server: a real
9367    /// synthetic Kimi K3 checkpoint served through the exact same
9368    /// `run_generation` entry point the HTTP handlers call for the
9369    /// GGUF path. Proves the whole new plumbing end to end: directory-
9370    /// shaped checkpoint loading, `KimiEngine`/`KimiTokenizer` wired
9371    /// through the `Model` enum, and `generate::generate_engine`
9372    /// producing real, bounded generated text.
9373    #[test]
9374    fn kimi_model_serves_real_text_end_to_end_via_run_generation() {
9375        let loaded = build_synthetic_kimi_loaded();
9376        let state = build_app_state(
9377            StartupModels {
9378                loaded: model::LoadedModel::Kimi(loaded),
9379                embedding: None,
9380            },
9381            None,
9382            None,
9383            None,
9384            false,
9385            None,
9386            Arc::new(health::Detection::ready(health::probe_backends())),
9387        );
9388        let active = state.active().expect("a freshly built state has a model");
9389        assert_eq!(active.tokenizer_kind(), "kimi-tiktoken-bpe");
9390        assert!(!active.is_synthetic());
9391
9392        let (choices, _usage) = run_generation(
9393            active.generative().unwrap(),
9394            "hi",
9395            &greedy_params(5),
9396            None,
9397            None,
9398            None,
9399            None,
9400            None,
9401            None,
9402        )
9403        .expect("a real Kimi checkpoint must generate without error");
9404        assert!(matches!(
9405            choices[0].finish,
9406            FinishReason::Length | FinishReason::Stop
9407        ));
9408    }
9409
9410    /// The THIRD decode path: `generate_engine`, which serves every
9411    /// model that is not a `Decoder`.
9412    ///
9413    /// This is where a constraint gets dropped without anyone noticing.
9414    /// JSON mode was honoured on the `Decoder` path and silently not on
9415    /// this one, because this path had no tokenizer to hand the mask.
9416    /// A grammar must reach it too, and this checkpoint's vocabulary is
9417    /// one token per byte value, so `root ::= "a"+` has exactly one
9418    /// legal token (97) and the answer is decidable: all `a`, however
9419    /// the random weights would otherwise have decoded.
9420    ///
9421    /// The unconstrained run beside it is the vacuity check.
9422    #[test]
9423    fn a_grammar_constrains_the_engine_decode_path() {
9424        let loaded = build_synthetic_kimi_loaded();
9425        let state = build_app_state(
9426            StartupModels {
9427                loaded: model::LoadedModel::Kimi(loaded),
9428                embedding: None,
9429            },
9430            None,
9431            None,
9432            None,
9433            false,
9434            None,
9435            Arc::new(health::Detection::ready(health::probe_backends())),
9436        );
9437        let active = state.active().expect("a freshly built state has a model");
9438
9439        let run = |grammar: Option<&str>| {
9440            let mut params = greedy_params(6);
9441            params.grammar = grammar.map(|src| {
9442                Arc::new(
9443                    frink_models::grammar::Grammar::from_str_with_root(src, "root")
9444                        .expect("test grammar parses"),
9445                )
9446            });
9447            run_generation(
9448                active.generative().unwrap(),
9449                "hi",
9450                &params,
9451                None,
9452                None,
9453                None,
9454                None,
9455                None,
9456                None,
9457            )
9458        };
9459
9460        let (choices, _) = run(None).expect("the unconstrained run must serve");
9461        let unconstrained = choices[0].text.clone();
9462        assert!(
9463            unconstrained.chars().any(|c| c != 'a'),
9464            "the unconstrained run produced only `a` ({unconstrained:?}), so the \
9465             constrained run below would prove nothing"
9466        );
9467
9468        let (choices, _) =
9469            run(Some(r#"root ::= "a"+"#)).expect("a grammar this vocabulary can spell must serve");
9470        let one = choices.into_iter().next().unwrap();
9471        let (finish, constrained) = (one.finish, one.text);
9472        assert!(
9473            !constrained.is_empty() && constrained.chars().all(|c| c == 'a'),
9474            "the engine decode path served text its grammar forbids ({constrained:?}): \
9475             the constraint was dropped between `generate_engine` and the sampler"
9476        );
9477        assert!(matches!(finish, FinishReason::Length | FinishReason::Stop));
9478    }
9479
9480    /// Explicit proof of the "gate, don't paper over" design decision
9481    /// (see `frink_models::engine`'s module docs): even when an operator configures
9482    /// a KV block pool and/or prefix cache, a Kimi request must never
9483    /// consult either -- `generate_engine`'s signature has no
9484    /// parameter for them at all, so this isn't just an unexercised
9485    /// code path, it's structurally impossible for a Kimi request to
9486    /// touch them. Confirmed here by observing both are completely
9487    /// untouched (pool blocks unchanged, cache stats unchanged) after a
9488    /// real Kimi generation runs alongside both.
9489    #[test]
9490    fn kv_pool_and_prefix_cache_are_never_consulted_for_a_kimi_model() {
9491        let loaded = build_synthetic_kimi_loaded();
9492        let state = build_app_state(
9493            StartupModels {
9494                loaded: model::LoadedModel::Kimi(loaded),
9495                embedding: None,
9496            },
9497            None,
9498            None,
9499            None,
9500            false,
9501            None,
9502            Arc::new(health::Detection::ready(health::probe_backends())),
9503        );
9504
9505        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 4)));
9506        let kv_pool_config = generate::KvPoolConfig {
9507            pool: pool.clone(),
9508            queue_wait: Duration::ZERO,
9509        };
9510        let pc = Mutex::new(PrefixCache::new(4));
9511
9512        run_generation(
9513            state
9514                .active()
9515                .expect("a freshly built state has a model")
9516                .generative()
9517                .unwrap(),
9518            "hi",
9519            &greedy_params(5),
9520            Some(&kv_pool_config),
9521            None,
9522            Some(&pc),
9523            None,
9524            None,
9525            None,
9526        )
9527        .expect("a real Kimi checkpoint must generate without error");
9528
9529        assert_eq!(
9530            pool.lock().unwrap().free_blocks(),
9531            4,
9532            "the KV pool must be completely untouched by a Kimi request"
9533        );
9534        let stats = pc.lock().unwrap().stats();
9535        assert_eq!(
9536            stats.hits + stats.misses,
9537            0,
9538            "the prefix cache must never be consulted for a Kimi request"
9539        );
9540    }
9541}