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