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