Skip to main content

frink_server/
lib.rs

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