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