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