Skip to main content

frink_server/
lib.rs

1//! frink-server: OpenAI-compatible HTTP surface (`/health`,
2//! `/v1/models`, `/v1/chat/completions`, `/v1/completions`,
3//! `/v1/tokenize`, `/v1/detokenize`, `/v1/embeddings`) over the
4//! frink-models decoder, plus a whole-response cache for exact-repeat
5//! requests (see `cache` module). Loads a real GGUF checkpoint and its
6//! own real tokenizer when `-m`/`--model` or `FRINK_MODEL_PATH` is set
7//! (see `model` module). Supports sampling
8//! (temperature/top_p/top_k/repetition_penalty), stop sequences, and SSE
9//! streaming (see `generate` module).
10//!
11//! Concurrency: the loaded model
12//! (`Model`) is immutable once loaded and shared via `Arc`, not locked
13//! behind a `Mutex` -- there is no shared mutable decoder state for
14//! concurrent requests to contend on or for one panicking request to
15//! poison. The *pointer* to it is swappable (`AppState::active`, behind
16//! an `RwLock` held only long enough to clone one `Arc`), which is what
17//! `/admin/models/load` swaps; a request that has already cloned its
18//! handle finishes against the exact weights it started on, and the old
19//! model is freed when the last such request lets go.
20//! Each request builds its own KV cache (see `generate::generate`)
21//! and runs its decode loop on tokio's blocking-thread pool via
22//! `spawn_blocking`, so CPU-bound generation no longer blocks the async
23//! reactor threads -- multiple requests can decode genuinely
24//! concurrently, bounded by that pool rather than serialized through one
25//! lock. Only the small whole-response cache is still mutable shared
26//! state, and it's locked only for the brief get/put around it, never
27//! across a decode.
28//!
29//! Streaming scope: when `stream: true` and tools are inactive, each
30//! decoded chunk is pushed through a bounded `mpsc` channel from the
31//! blocking generate task into the SSE writer so time-to-first-byte
32//! overlaps with ongoing decode. Under continuous batching the batch
33//! worker emits the same incremental chunks as the private decode loop.
34
35mod admin;
36mod anthropic;
37mod attribution;
38mod best_of;
39mod budget;
40mod cache_admin;
41mod cache_salt;
42mod cancel;
43mod chat_params;
44mod chat_stream_choice;
45mod chat_template;
46mod choice_stream;
47mod cli;
48mod completion;
49mod continuation;
50mod conversations;
51mod decode_task;
52mod embeddings;
53mod generate;
54mod grammar_request;
55mod health;
56mod journal;
57mod json_mode;
58mod limits;
59mod loaded;
60mod logprobs;
61mod lora;
62mod mcp;
63mod model;
64mod openai_extra;
65mod output;
66mod policy;
67mod prefill_batch;
68mod reasoning_budget;
69mod reasoning_tokens;
70mod request_tail;
71mod rerank;
72mod response_cache;
73pub(crate) mod responses;
74mod resume;
75mod round_robin;
76mod sample_step;
77mod sampling_knobs;
78mod sampling_loop;
79mod security;
80mod serving;
81mod session;
82mod slots;
83mod sse;
84mod stats;
85mod stop;
86mod stream_events;
87mod tasks;
88mod token_mask;
89mod tool_grammar;
90mod unimplemented_fields;
91mod unsupported_sampling;
92mod utf8_stream;
93
94use std::cell::RefCell;
95use std::convert::Infallible;
96use std::net::SocketAddr;
97use std::path::PathBuf;
98use std::rc::Rc;
99use std::sync::{Arc, Mutex, MutexGuard};
100use std::time::Duration;
101
102use axum::{
103    extract::State,
104    http::StatusCode,
105    response::sse::{Event, Sse},
106    response::{IntoResponse, Response},
107    routing::{get, post},
108    Json, Router,
109};
110use serde::{Deserialize, Serialize};
111
112use cli::apply_cli_overrides;
113pub use cli::{ServerArgs, BUILT_WITH_CUDA, BUILT_WITH_METAL};
114
115use frink_core::cache::KvBlockPool;
116use frink_models::kimi_tokenizer::KimiTokenizer;
117use frink_models::sampling::SamplingParams;
118use frink_models::tokenizer::{SpecialTokens, StopTokens};
119use frink_models::{Decoder, Gemma4Engine, KimiEngine, MlaEngine, PrefixCache};
120#[cfg(test)]
121use generate::FinishReason;
122use generate::GenerationParams;
123pub(crate) use loaded::{ActiveModel, Loaded, SleptModel};
124use model::ServerTokenizer;
125use rerank::encoder_endpoints;
126use response_cache::ResponseCache;
127use sampling_knobs::SamplingKnobs;
128
129/// The loaded model: immutable once built, so it needs no lock at all --
130/// just cheap `Arc` sharing across concurrent request tasks. Two real
131/// checkpoint shapes exist (see `model::LoadedModel`'s doc comment for
132/// why `FRINK_MODEL_PATH` picks between them); everything that isn't
133/// engine-specific (chat template, tokenizer kind reporting, whether
134/// this is the synthetic demo) goes through the small inherent methods
135/// below rather than being matched on ad hoc at every call site.
136#[allow(clippy::large_enum_variant)] // KimiEngine/MlaEngine dwarf Arc<Decoder>; boxing would churn call sites
137pub(crate) enum Model {
138    Gguf(GgufModel),
139    Kimi(KimiModel),
140    Mla(MlaModel),
141    Gemma4(Gemma4Model),
142    Glm52(Glm52Model),
143}
144
145pub(crate) struct GgufModel {
146    decoder: Arc<Decoder>,
147    tokenizer: Arc<ServerTokenizer>,
148    stop_tokens: StopTokens,
149    bos_id: Option<usize>,
150    is_synthetic: bool,
151    chat_template: chat_template::PromptTemplate,
152}
153
154pub(crate) struct KimiModel {
155    engine: KimiEngine,
156    tokenizer: KimiTokenizer,
157    stop_tokens: StopTokens,
158    chat_template: chat_template::PromptTemplate,
159}
160
161pub(crate) struct MlaModel {
162    engine: MlaEngine,
163    tokenizer: ServerTokenizer,
164    stop_tokens: StopTokens,
165    bos_id: Option<usize>,
166    name: String,
167    chat_template: chat_template::PromptTemplate,
168}
169
170pub(crate) struct Gemma4Model {
171    engine: Gemma4Engine,
172    tokenizer: ServerTokenizer,
173    stop_tokens: StopTokens,
174    bos_id: Option<usize>,
175    name: String,
176    chat_template: chat_template::PromptTemplate,
177}
178
179pub(crate) struct Glm52Model {
180    engine: frink_models::Glm52Engine,
181    tokenizer: ServerTokenizer,
182    stop_tokens: StopTokens,
183    bos_id: Option<usize>,
184    name: String,
185    chat_template: chat_template::PromptTemplate,
186}
187
188impl Model {
189    pub(crate) fn chat_template(&self) -> chat_template::PromptTemplate {
190        match self {
191            Model::Gguf(m) => m.chat_template.clone(),
192            Model::Kimi(m) => m.chat_template.clone(),
193            Model::Mla(m) => m.chat_template.clone(),
194            Model::Gemma4(m) => m.chat_template.clone(),
195            Model::Glm52(m) => m.chat_template.clone(),
196        }
197    }
198
199    /// Kimi K3 / MLA / GLM-5.2 have no synthetic-weight demo path through this
200    /// server (unlike GGUF, which falls back to one when
201    /// `FRINK_MODEL_PATH` is unset) -- a loaded `Model::Kimi` /
202    /// `Model::Mla` / `Model::Glm52` is always a real checkpoint.
203    fn is_synthetic(&self) -> bool {
204        match self {
205            Model::Gguf(m) => m.is_synthetic,
206            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => false,
207        }
208    }
209
210    fn tokenizer_kind(&self) -> &'static str {
211        match self {
212            Model::Gguf(m) => m.tokenizer.kind(),
213            Model::Kimi(_) => "kimi-tiktoken-bpe",
214            Model::Mla(m) => m.tokenizer.kind(),
215            Model::Gemma4(m) => m.tokenizer.kind(),
216            Model::Glm52(m) => m.tokenizer.kind(),
217        }
218    }
219
220    /// Live counters of the bounded expert cache, when the model
221    /// streams routed experts (`FRINK_EXPERT_CACHE_BYTES`); `None`
222    /// for fully resident models.
223    fn expert_store_stats(&self) -> Option<frink_core::expert_store::ExpertStoreStats> {
224        match self {
225            Model::Gguf(m) => m.decoder.expert_store_stats(),
226            Model::Kimi(m) => m.engine.weights.expert_store_stats(),
227            Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
228        }
229    }
230
231    pub(crate) fn name(&self) -> &str {
232        match self {
233            Model::Gguf(m) => m.decoder.config.name,
234            Model::Kimi(_) => "kimi-k3",
235            Model::Mla(m) => m.name.as_str(),
236            Model::Gemma4(m) => m.name.as_str(),
237            Model::Glm52(m) => m.name.as_str(),
238        }
239    }
240
241    /// `specials` is llama.cpp's `parse_special`, and each caller is
242    /// matched to the llama.cpp server site it mirrors
243    /// (`tools/server/server-context.cpp` unless said otherwise):
244    ///
245    /// * a prompt, rendered from a chat template or given raw --
246    ///   `/v1/chat/completions`, `/v1/completions`, `/v1/messages`,
247    ///   `count_tokens`, slot save: `Parse`, as
248    ///   `tokenize_input_prompts(..., true, true)` does for both
249    ///   completion routes. llama.cpp's server does NOT tokenize a
250    ///   message's content separately from the template around it, so
251    ///   neither does this one; a document that mentions `<|im_end|>`
252    ///   inside a chat message is parsed on both engines. Doing better
253    ///   would need the template renderer to hand back which spans are
254    ///   content, and is deliberately not done here so the two engines
255    ///   agree about the prompt.
256    /// * pooled decoder embeddings: `Parse` (`handle_embeddings_impl`).
257    /// * `/v1/tokenize`: the request's own `parse_special`, default
258    ///   `true` (`json_value(body, "parse_special", true)`).
259    /// * DRY sequence breakers: `AsText`
260    ///   (`llama-sampler.cpp`: `vocab.tokenize(str, false, false)`).
261    /// * a stop string that is one token: `Parse`. This is frink's own
262    ///   mechanism (llama.cpp matches stop strings on decoded text and
263    ///   tokenizes them only to trim `n_probs`), and a caller who names
264    ///   `<|eot_id|>` as a stop means the token.
265    /// * a tool-call opener that anchors the paged KV window: `Parse`,
266    ///   because the opener is a special token where the family has one.
267    pub(crate) fn encode(&self, text: &str, specials: SpecialTokens) -> Vec<usize> {
268        match self {
269            Model::Gguf(m) => m.tokenizer.encode(text, specials),
270            Model::Kimi(m) => m
271                .tokenizer
272                .encode(text, specials)
273                .into_iter()
274                .map(|id| id as usize)
275                .collect(),
276            Model::Mla(m) => m.tokenizer.encode(text, specials),
277            Model::Gemma4(m) => m.tokenizer.encode(text, specials),
278            Model::Glm52(m) => m.tokenizer.encode(text, specials),
279        }
280    }
281
282    /// The BOS id the generation path would prepend, or `None` when
283    /// this checkpoint's own metadata says not to prepend one.
284    ///
285    /// Read by `/tokenize`'s `add_special`, so that endpoint reports
286    /// the prompt the model would actually be given rather than a
287    /// second opinion about it. Kimi has no BOS id plumbed through the
288    /// server -- `run_generation` passes `None` for it -- and this
289    /// agrees with that rather than inventing one.
290    pub(crate) fn bos_id(&self) -> Option<usize> {
291        match self {
292            Model::Gguf(m) => m.bos_id,
293            Model::Kimi(_) => None,
294            Model::Mla(m) => m.bos_id,
295            Model::Gemma4(m) => m.bos_id,
296            Model::Glm52(m) => m.bos_id,
297        }
298    }
299
300    pub(crate) fn decode(&self, ids: &[usize]) -> String {
301        match self {
302            Model::Gguf(m) => m.tokenizer.decode(ids),
303            Model::Kimi(m) => {
304                let ids32: Vec<u32> = ids.iter().map(|&id| id as u32).collect();
305                m.tokenizer.decode(&ids32)
306            }
307            Model::Mla(m) => m.tokenizer.decode(ids),
308            Model::Gemma4(m) => m.tokenizer.decode(ids),
309            Model::Glm52(m) => m.tokenizer.decode(ids),
310        }
311    }
312
313    /// Final-normed last-layer hidden states for GGUF Decoder only.
314    /// Returns `None` for engines without a hidden-state hook (e.g. Kimi/MLA/GLM).
315    pub(crate) fn embed_tokens(&self, tokens: &[usize]) -> Option<Vec<Vec<f32>>> {
316        match self {
317            Model::Gguf(m) => {
318                let mut caches: Vec<_> = m.decoder.config.new_kv_caches();
319                Some(m.decoder.forward_hidden_batch(tokens, 0, &mut caches))
320            }
321            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
322        }
323    }
324
325    /// The generic GGUF decoder, when that is what is loaded.
326    ///
327    /// `None` for the dedicated engines (Kimi, MLA, Gemma-4, GLM-5.2):
328    /// they hold their own KV in their own shape, and
329    /// [`crate::slots`]'s file format describes the generic one.
330    pub(crate) fn gguf_decoder(&self) -> Option<&Arc<Decoder>> {
331        match self {
332            Model::Gguf(m) => Some(&m.decoder),
333            Model::Kimi(_) | Model::Mla(_) | Model::Gemma4(_) | Model::Glm52(_) => None,
334        }
335    }
336
337    pub(crate) fn vocab_size(&self) -> Option<usize> {
338        match self {
339            Model::Gguf(m) => Some(m.decoder.config.vocab_size),
340            Model::Kimi(m) => Some(m.tokenizer.vocab_size()),
341            Model::Mla(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
342            Model::Gemma4(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
343            Model::Glm52(m) => Some(frink_models::Engine::vocab_size(&m.engine)),
344        }
345    }
346
347    /// True when this checkpoint carries a real vocabulary rather than
348    /// the byte-level fallback the synthetic-weight demo model uses.
349    ///
350    /// Read by the DRY sampler, whose sequence breakers are strings that
351    /// only mean something against a real tokenizer; see
352    /// [`frink_models::dry::DryVocabMissing`].
353    fn has_real_vocabulary(&self) -> bool {
354        match self {
355            Model::Gguf(m) => !matches!(*m.tokenizer, model::ServerTokenizer::Byte),
356            Model::Kimi(_) => true,
357            Model::Mla(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
358            Model::Gemma4(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
359            Model::Glm52(m) => !matches!(m.tokenizer, model::ServerTokenizer::Byte),
360        }
361    }
362}
363
364/// What the DRY sampler needs to tokenise its sequence breakers.
365///
366/// One trait, two implementations (`frink_cli`'s `CliTokenizer` has the
367/// other), so `--dry-sequence-breaker` and the `dry_sequence_breakers`
368/// request field cannot come to mean different things.
369impl frink_models::dry::DryVocab for Model {
370    fn n_tokens(&self) -> usize {
371        self.vocab_size().unwrap_or(0)
372    }
373
374    fn detokenize(&self, token: usize) -> String {
375        self.decode(&[token])
376    }
377
378    fn tokenize(&self, text: &str) -> Vec<usize> {
379        self.encode(text, SpecialTokens::AsText)
380    }
381}
382
383pub(crate) struct AppState {
384    /// A **side-car** embedding model (`FRINK_EMBEDDING_MODEL_PATH`),
385    /// served by `/v1/embeddings` in preference to pooling a decoder's
386    /// hidden states.
387    ///
388    /// This is now the *second* way an encoder gets here. The first is
389    /// [`AppState::active`]: an encoder-only checkpoint at
390    /// `FRINK_MODEL_PATH` (or swapped in through
391    /// `/admin/models/load`) is the loaded model, as
392    /// [`crate::loaded::Loaded::Encoder`]. This field is what a
393    /// deployment uses when it wants a generative model active *and*
394    /// embeddings from a real encoder at the same time -- one process,
395    /// two checkpoints, which the active-model slot alone cannot
396    /// express. See [`AppState::embedding_model`] for which wins.
397    pub(crate) embedding: Option<Arc<frink_models::EmbeddingModel>>,
398    /// The swappable active model.
399    ///
400    /// **A reader clones the `Arc` under the read lock and then runs;
401    /// the lock is never held across a decode.** That is the whole
402    /// design: `RwLock` guards the *pointer*, not the model, so
403    /// `/admin/models/load` swapping in a new `Arc` cannot stall a
404    /// request that is already generating, and a request that started
405    /// against the old model keeps decoding against the exact weights
406    /// it began with until it finishes -- the old `ActiveModel` (and
407    /// its batcher thread) is dropped only when the last in-flight
408    /// holder releases it, not when the swap happens. Requests that
409    /// arrive after the swap see the new model. There is deliberately
410    /// no attempt to migrate an in-flight request: half a completion
411    /// from one checkpoint and half from another is worse than either.
412    ///
413    /// `None` means nothing is loaded (after `/admin/models/unload`, or
414    /// a failed startup load): generation endpoints answer 503 rather
415    /// than pretending, and `/health` reports `unavailable`.
416    active: std::sync::RwLock<Option<Arc<ActiveModel>>>,
417    /// Set while a load task is in flight, so a second load request is
418    /// rejected instead of racing the first. A load is not cheap and
419    /// two concurrent ones would fight for the same memory.
420    pub(crate) load_in_progress: std::sync::atomic::AtomicBool,
421    /// The model a `POST /sleep` put away, so `POST /wake_up` can put
422    /// it back.
423    ///
424    /// Sleep is an UNLOAD THAT REMEMBERS. That is the whole difference
425    /// from `/admin/models/unload`, which leaves the server with
426    /// nothing to serve and no idea what it used to serve, so only a
427    /// client that already knows the id can recover. A sleeping server
428    /// can wake itself, which is what makes the pair usable from a
429    /// scheduler that does not know the deployment.
430    pub(crate) slept: Mutex<Option<SleptModel>>,
431    /// Long-running jobs (download, load) -- see the `tasks` module.
432    pub(crate) tasks: Arc<tasks::TaskRegistry>,
433    /// Generations that can currently be stopped by `POST /v1/cancel`
434    /// -- see the `cancel` module for why a dropped socket alone is not
435    /// enough.
436    pub(crate) cancels: Arc<cancel::CancelRegistry>,
437    /// Recent-request ring buffer and the counters behind
438    /// `/admin/stats` -- see the `stats` module.
439    pub(crate) stats: stats::Stats,
440    /// Replay buffers for streams started with `stream_resumable`.
441    /// See the `resume` module.
442    pub(crate) streams: resume::StreamRegistry,
443    /// The directory `/admin/models` scans, when one is configured.
444    pub(crate) model_dir: Option<PathBuf>,
445    /// The only shared *mutable* state in the server. Locked only for
446    /// the brief get/put around a cache lookup, never held across a
447    /// decode -- see the module doc comment.
448    response_cache: Mutex<ResponseCache>,
449    /// `Some` when `FRINK_KV_POOL_BLOCKS`/`FRINK_KV_POOL_BLOCK_SIZE`
450    /// are set: every request's per-layer KV caches then draw from
451    /// this one shared, bounded pool instead of each growing
452    /// unboundedly. A request whose caches can't get their first block
453    /// retries for up to `FRINK_KV_POOL_QUEUE_TIMEOUT_MS` (zero by
454    /// default -- reject immediately) before being rejected with 503,
455    /// rather than being admitted regardless of how many other
456    /// requests are already decoding -- see
457    /// `frink_core::cache::KvBlockPool` and `generate::KvPoolConfig`.
458    /// `None` (the default) preserves the
459    /// original unbounded-per-request behavior exactly.
460    pub(crate) kv_pool: Option<generate::KvPoolConfig>,
461    /// `Some` when `FRINK_PAGED_KV_BLOCKS` is set: per-layer paged KV
462    /// storage every request draws pages from, rather than each request
463    /// owning a private contiguous buffer.
464    ///
465    /// Mutually exclusive with BOTH `kv_pool` and `prefix_cache`, and
466    /// refused at startup rather than silently preferred. Against
467    /// `kv_pool` because they are two answers to the same question.
468    /// Against `prefix_cache` because `PrefixCache` stores
469    /// `Vec<KvCache>` snapshots, which a paged request has none of, so
470    /// enabling both would give a cache that can never hit -- see
471    /// `wire-radix-prefix-cache` in the plan, which is what removes
472    /// that restriction.
473    pub(crate) paged_kv: Option<generate::PagedKvConfig>,
474    /// `Some` when `FRINK_PREFIX_CACHE_ENTRIES` is set: a shared,
475    /// LRU-bounded store of previously processed prompt+KV-state
476    /// snapshots (see `frink_models::PrefixCache`), consulted so a
477    /// request that *extends* an earlier one -- the common multi-turn-
478    /// chat case -- can skip recomputing the shared part. Mutually
479    /// exclusive with `kv_pool` (see `generate::generate`'s doc
480    /// comment for why); `None` (the default) means every request
481    /// processes its full prompt from scratch, exactly as before this
482    /// existed.
483    pub(crate) prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
484    /// Server-side per-session conversation history -- see
485    /// `session::SessionStore`'s doc comment.
486    /// Always present (unlike `kv_pool`/`prefix_cache`, it's not
487    /// opt-in): a request that never sends `session_id` simply never
488    /// touches it, at negligible cost (one empty `HashMap`).
489    sessions: session::SessionStore,
490    requests_total: std::sync::atomic::AtomicU64,
491    request_errors_total: std::sync::atomic::AtomicU64,
492    started_at: std::time::Instant,
493    /// Milliseconds after `started_at` at which the last request
494    /// finished; 0 means none has. Reported by `/health` as an age, so a
495    /// client that sees a slow health poll from a GPU-saturated server
496    /// has positive evidence of liveness instead of declaring it dead.
497    last_request_ms: std::sync::atomic::AtomicU64,
498    /// Backend capability probe behind `/health` (see `health` module).
499    detection: Arc<health::Detection>,
500    /// Loaded MCP config (`--mcp-config`); tool invocation not wired yet.
501    mcp: Option<mcp::LoadedMcpConfig>,
502    /// Whether a swapped-in GGUF model should get a continuous-batching
503    /// worker, decided once at startup from the same env var and
504    /// exclusions as the initial load.
505    pub(crate) continuous_batching_enabled: bool,
506    /// Serializes private-loop Metal decodes when continuous batching is
507    /// off. Shared `metal_attn_kv` is not safe across concurrent
508    /// `forward_token` calls yet; see `docs/plans/metal-parallel-concurrency.md`.
509    pub(crate) metal_private_decode_gate: Option<Arc<std::sync::Mutex<()>>>,
510    /// The model id a load task is currently working on, so
511    /// `/admin/models` can report `loading` for it. Separate from
512    /// `load_in_progress` because that is a gate and this is a label.
513    loading_model: Mutex<Option<String>>,
514    /// The last failed load, as `(model id, message)`. Sticky until the
515    /// next successful load so `/admin/models` can say *why* an entry
516    /// is in `error` without the user retrying to find out.
517    last_load_error: Mutex<Option<(String, String)>>,
518    /// Live serving counters and the two sliding-window rates behind
519    /// `/v1/stats` -- see `crate::stats::ServingStats`. Distinct from
520    /// `stats`, which is the historical ring: this is what is happening
521    /// *now*, and it decays to zero when nothing is.
522    pub(crate) serving: Mutex<crate::stats::ServingStats>,
523    /// The gate every request, cache rebuild and shutdown passes
524    /// through -- see `crate::policy::maintenance::MaintenanceGate`. Held across none
525    /// of them: each operation takes it, reads or moves the state, and
526    /// releases before doing any work.
527    pub(crate) maintenance: Mutex<crate::policy::maintenance::MaintenanceGate>,
528    /// The live memory reading behind `/v1/stats`, re-probed at most
529    /// once per [`FOOTPRINT_TTL_MS`] -- see
530    /// `cache_admin::footprint_json`. A `Mutex` and not an atomic
531    /// because holding it across the probe is what collapses concurrent
532    /// pollers onto ONE VMA walk.
533    pub(crate) footprint:
534        Mutex<crate::policy::footprint::ProbeCache<crate::policy::footprint::Footprint>>,
535    /// Wall-clock second this process started serving.
536    ///
537    /// Distinct from `started_at`, which is an `Instant` and has no
538    /// wall clock at all. This exists so an accounting receipt's id can
539    /// be derived from something stable for the life of THIS process
540    /// and different in the next one: a pid alone is reused across
541    /// restarts, and a restarted engine reusing a previous
542    /// generation's receipt id would have its own receipt silently
543    /// skipped as already written.
544    pub(crate) started_unix: u64,
545}
546
547/// How long a memory reading is served before it is taken again.
548///
549/// Two seconds: long enough that a dashboard polling once a second
550/// costs one probe rather than one per poll, short enough that an
551/// operator watching a load ramp sees it move.
552pub(crate) const FOOTPRINT_TTL_MS: u64 = 2_000;
553
554impl AppState {
555    /// Clones the active model's `Arc` and releases the lock before
556    /// returning. Every caller then runs against its own handle, so no
557    /// decode ever holds this lock -- see [`AppState::active`].
558    pub(crate) fn active(&self) -> Option<Arc<ActiveModel>> {
559        self.active
560            .read()
561            .unwrap_or_else(|p| p.into_inner())
562            .clone()
563    }
564
565    /// [`AppState::active`] for a request that cannot proceed without a
566    /// model. 503 with a `Retry-After`-shaped explanation is the honest
567    /// answer while nothing is loaded; the alternative -- keeping a
568    /// stale model around so the endpoint never fails -- would serve
569    /// tokens from a checkpoint the operator explicitly unloaded.
570    /// True while a `POST /sleep` is in effect.
571    pub(crate) fn is_sleeping(&self) -> bool {
572        self.slept
573            .lock()
574            .unwrap_or_else(|p| p.into_inner())
575            .is_some()
576    }
577
578    pub(crate) fn require_active(&self) -> Result<Arc<ActiveModel>, ApiError> {
579        if let Some(active) = self.active() {
580            return Ok(active);
581        }
582        // Asleep is not the same as empty, and telling a caller to
583        // load a model they never chose would send them to the wrong
584        // knob. Distinct `type` so a client can branch on it.
585        if self.is_sleeping() {
586            return Err((
587                StatusCode::SERVICE_UNAVAILABLE,
588                Json(serde_json::json!({"error": {
589                    "message": "this server is asleep; POST /wake_up to reload the model it put \
590                                away",
591                    "type": "server_sleeping"
592                }})),
593            ));
594        }
595        Err((
596            StatusCode::SERVICE_UNAVAILABLE,
597            Json(serde_json::json!({"error": {
598                "message": "no model is loaded; POST /admin/models/load with an id from \
599                            GET /admin/models",
600                "type": "model_not_loaded"
601            }})),
602        ))
603    }
604
605    /// [`AppState::active`]'s *generation* model only, for the many
606    /// call sites that do not care about the batcher.
607    ///
608    /// Two refusals live behind this one `?`: nothing loaded (503, from
609    /// [`AppState::require_active`]) and an encoder loaded (501, from
610    /// [`ActiveModel::generative`]). They are different answers to
611    /// different questions and neither may be given for the other.
612    pub(crate) fn require_model(&self) -> Result<Arc<Model>, ApiError> {
613        Ok(Arc::clone(self.require_active()?.generative()?))
614    }
615
616    /// Publishes a new active model (or `None` to unload) and returns
617    /// the previous one.
618    ///
619    /// The write lock is held only for the pointer swap. The returned
620    /// value is the caller's to drop *outside* the lock: dropping a
621    /// multi-gigabyte model can take a moment, and doing it under the
622    /// lock would block every reader for exactly as long.
623    pub(crate) fn swap_active(&self, next: Option<Arc<ActiveModel>>) -> Option<Arc<ActiveModel>> {
624        let mut guard = self.active.write().unwrap_or_else(|p| p.into_inner());
625        std::mem::replace(&mut *guard, next)
626    }
627
628    /// Stamps "a request just finished" for `/health`'s liveness
629    /// vouching. Relaxed: this is a freshness hint, not a
630    /// synchronization point.
631    fn mark_request_finished(&self) {
632        let ms = self.started_at.elapsed().as_millis().min(u64::MAX as u128) as u64;
633        self.last_request_ms
634            .store(ms, std::sync::atomic::Ordering::Relaxed);
635    }
636
637    pub(crate) fn uptime(&self) -> Duration {
638        self.started_at.elapsed()
639    }
640
641    pub(crate) fn requests_total(&self) -> u64 {
642        self.requests_total
643            .load(std::sync::atomic::Ordering::Relaxed)
644    }
645
646    pub(crate) fn errors_total(&self) -> u64 {
647        self.request_errors_total
648            .load(std::sync::atomic::Ordering::Relaxed)
649    }
650
651    pub(crate) fn cache_stats(&self) -> response_cache::CacheStats {
652        lock_cache(&self.response_cache).stats()
653    }
654
655    /// Seconds since the last request finished, or `None` when none
656    /// has. Same derivation `/health` uses, so the two agree.
657    pub(crate) fn last_request_age_seconds(&self) -> Option<f64> {
658        let last = self
659            .last_request_ms
660            .load(std::sync::atomic::Ordering::Relaxed);
661        (last > 0)
662            .then(|| self.uptime().as_secs_f64() - (last as f64 / 1000.0))
663            .map(|age| age.max(0.0))
664    }
665
666    pub(crate) fn loading_model_id(&self) -> Option<String> {
667        self.loading_model
668            .lock()
669            .unwrap_or_else(|p| p.into_inner())
670            .clone()
671    }
672
673    pub(crate) fn set_loading_model(&self, id: Option<String>) {
674        *self.loading_model.lock().unwrap_or_else(|p| p.into_inner()) = id;
675    }
676
677    pub(crate) fn last_load_error(&self) -> Option<(String, String)> {
678        self.last_load_error
679            .lock()
680            .unwrap_or_else(|p| p.into_inner())
681            .clone()
682    }
683
684    pub(crate) fn set_last_load_error(&self, error: Option<(String, String)>) {
685        *self
686            .last_load_error
687            .lock()
688            .unwrap_or_else(|p| p.into_inner()) = error;
689    }
690
691    /// Records one finished request in the `/admin/stats` ring buffer.
692    ///
693    /// `attribution` is threaded from the request's own headers rather
694    /// than looked up here: by the time a generation task finishes, the
695    /// request parts are long gone, and reconstructing "who was that"
696    /// afterwards is exactly the guessing the monitor exists to avoid.
697    /// The model that would serve a request right now, as `/v1/models`
698    /// names it. `None` when nothing is loaded.
699    pub(crate) fn active_model_name(&self) -> Option<String> {
700        self.active().map(|a| a.name().to_string())
701    }
702
703    /// The encoder `/v1/embeddings` should use, from either of the two
704    /// ways one gets here.
705    ///
706    /// `FRINK_EMBEDDING_MODEL_PATH` wins over an encoder loaded as the
707    /// active model, and it has to: a deployment that names both has
708    /// asked for the side-car explicitly, while the active model may
709    /// have been swapped in by `/admin/models/load` since. Only one of
710    /// the two is ever set in practice -- the side-car exists so a
711    /// *generative* model can be active at the same time.
712    pub(crate) fn embedding_model(&self) -> Option<Arc<frink_models::EmbeddingModel>> {
713        self.embedding
714            .clone()
715            .or_else(|| self.active().and_then(|a| a.encoder().map(Arc::clone)))
716    }
717
718    /// What `/v1/embeddings` is actually charging against, for the
719    /// `/admin/stats` ring: the embedding model when one is serving,
720    /// otherwise whichever decoder is active.
721    pub(crate) fn embedding_model_name(&self) -> Option<String> {
722        match self.embedding_model() {
723            Some(e) => Some(e.name().to_string()),
724            None => self.active_model_name(),
725        }
726    }
727
728    pub(crate) fn record_request(&self, record: stats::Record<'_>) {
729        self.stats.record(stats::entry(record));
730    }
731}
732
733/// Defense in depth: if a panic ever happened while this lock was held
734/// (none of the CPU-bound decode work runs under it, so this should be
735/// very unlikely), recovering the inner state on poison rather than
736/// `.unwrap()`ing keeps the cache from permanently bricking the server.
737fn lock_cache(cache: &Mutex<ResponseCache>) -> MutexGuard<'_, ResponseCache> {
738    cache
739        .lock()
740        .unwrap_or_else(|poisoned| poisoned.into_inner())
741}
742
743#[derive(Debug, Clone, Deserialize)]
744#[serde(untagged)]
745pub(crate) enum MessageContent {
746    Text(String),
747    Parts(Vec<ContentPart>),
748}
749
750#[derive(Debug, Clone, Deserialize)]
751struct ContentPart {
752    #[serde(rename = "type")]
753    kind: String,
754    #[serde(default)]
755    text: Option<String>,
756    #[serde(default)]
757    image_url: Option<serde_json::Value>,
758}
759
760impl MessageContent {
761    fn as_text(&self) -> String {
762        match self {
763            Self::Text(s) => s.clone(),
764            Self::Parts(parts) => parts
765                .iter()
766                .filter_map(|p| p.text.as_deref())
767                .collect::<Vec<_>>()
768                .join(""),
769        }
770    }
771
772    fn has_image(&self) -> bool {
773        match self {
774            Self::Text(_) => false,
775            Self::Parts(parts) => parts
776                .iter()
777                .any(|p| p.kind == "image_url" || p.image_url.is_some()),
778        }
779    }
780}
781
782#[derive(Debug, Clone, Deserialize)]
783pub(crate) struct ChatMessage {
784    pub(crate) role: String,
785    /// `None` for an assistant message that made tool calls instead of
786    /// replying with text (the real OpenAI convention: `content` and
787    /// `tool_calls` are mutually exclusive on an assistant message).
788    #[serde(default)]
789    pub(crate) content: Option<MessageContent>,
790    /// Present on a replayed assistant message that previously made
791    /// one or more tool calls (conversation history a client sends
792    /// back on a follow-up request).
793    #[serde(default)]
794    pub(crate) tool_calls: Option<Vec<ToolCallIn>>,
795    /// Present on a `"tool"`-role message carrying a call's result
796    /// (unused by rendering today -- `role` alone already
797    /// distinguishes it -- but accepted so real OpenAI-shaped tool-
798    /// result messages deserialize without error).
799    #[serde(default)]
800    #[allow(dead_code)]
801    pub(crate) tool_call_id: Option<String>,
802    /// A replayed assistant turn's chain of thought, kept out of
803    /// `content` on the way in and handed back to the template on the
804    /// way out.
805    ///
806    /// It has to be a field of its own rather than prose folded into
807    /// `content`, because a template that knows about reasoning wraps
808    /// it in the family's own markers -- and a template that does not
809    /// must be able to drop it. Concatenating it into `content` would
810    /// show a model its own scratchpad as if it had said it out loud,
811    /// which is exactly what the markers exist to prevent.
812    ///
813    /// Accepted under both spellings clients use: `reasoning_content`
814    /// (the DeepSeek convention frink emits) and `reasoning`
815    /// (what the OpenAI Responses and Anthropic surfaces call it), so a
816    /// client can replay a turn shaped the way it received it.
817    #[serde(default, alias = "reasoning")]
818    pub(crate) reasoning_content: Option<String>,
819}
820
821impl ChatMessage {
822    /// The text this message actually contributes to a rendered
823    /// prompt: `content` verbatim for an ordinary message, or (for a
824    /// replayed assistant message carrying `tool_calls`) each call
825    /// re-rendered as the same `<tool_call>{...}</tool_call>` marker
826    /// text a model is asked to produce for a *new* call -- see
827    /// `chat_template`'s module doc comment for why.
828    fn rendered_content(&self) -> String {
829        let mut out = self
830            .content
831            .as_ref()
832            .map(MessageContent::as_text)
833            .unwrap_or_default();
834        if let Some(calls) = &self.tool_calls {
835            for call in calls {
836                out.push_str(&format!(
837                    "<tool_call>{{\"name\": \"{}\", \"arguments\": {}}}</tool_call>",
838                    call.function.name, call.function.arguments
839                ));
840            }
841        }
842        out
843    }
844}
845
846#[derive(Debug, Clone, Deserialize)]
847pub(crate) struct ToolCallIn {
848    #[serde(default)]
849    #[allow(dead_code)]
850    id: String,
851    #[serde(rename = "type", default)]
852    #[allow(dead_code)]
853    kind: String,
854    function: ToolCallFunctionIn,
855}
856
857#[derive(Debug, Clone, Deserialize)]
858struct ToolCallFunctionIn {
859    name: String,
860    /// A JSON-encoded string (the real OpenAI convention for
861    /// `tool_calls[].function.arguments`), not a nested object --
862    /// spliced directly into the re-rendered `<tool_call>{...}` marker
863    /// text since it's already valid JSON.
864    arguments: String,
865}
866
867/// A tool definition in the real OpenAI request shape:
868/// `{"type": "function", "function": {"name", "description", "parameters"}}`.
869#[derive(Debug, Clone, Deserialize)]
870struct ToolDef {
871    #[serde(rename = "type", default)]
872    #[allow(dead_code)]
873    kind: String,
874    function: ToolFunctionDef,
875}
876
877#[derive(Debug, Clone, Deserialize)]
878struct ToolFunctionDef {
879    name: String,
880    #[serde(default)]
881    description: Option<String>,
882    #[serde(default)]
883    parameters: Option<serde_json::Value>,
884}
885
886/// OpenAI's `tool_choice`: `"auto"`/`"none"`/`"required"`, or an object
887/// pinning one specific function.
888///
889/// All four are honoured now. `"none"` hides the tools from the prompt;
890/// `"auto"` offers them; `"required"` and a named function FORCE a call,
891/// by compiling the offered tools into a grammar the decode loop must
892/// keep parseable (`crate::tool_grammar`). Before that grammar existed
893/// the last two were a 501, because a server that is asked to force a
894/// call and can only ask for one in the prompt has not done what it was
895/// told.
896#[derive(Debug, Clone, Deserialize)]
897#[serde(untagged)]
898enum ToolChoice {
899    Mode(String),
900    Specific(serde_json::Value),
901}
902
903/// OpenAI's `stop` field accepts either a single string or an array of
904/// strings.
905#[derive(Deserialize)]
906#[serde(untagged)]
907enum StopParam {
908    One(String),
909    Many(Vec<String>),
910}
911
912#[derive(Deserialize)]
913struct ChatCompletionRequest {
914    model: String,
915    messages: Vec<ChatMessage>,
916    #[serde(default = "default_max_tokens")]
917    max_tokens: usize,
918    #[serde(default)]
919    temperature: Option<f32>,
920    #[serde(default)]
921    top_p: Option<f32>,
922    /// llama.cpp's `--min-p`. Not an OpenAI field; accepted under the
923    /// same spelling llama.cpp's server uses, because a client
924    /// that sends it and is silently served an unfiltered distribution
925    /// cannot tell that apart from having had it honoured.
926    #[serde(default)]
927    min_p: Option<f32>,
928    #[serde(default)]
929    top_k: Option<usize>,
930    #[serde(default)]
931    repetition_penalty: Option<f32>,
932    /// llama.cpp's `typ_p`, `top_n_sigma`, `xtc_*` and `dry_*`, in ONE
933    /// struct shared with the other two routes that take them. See
934    /// `sampling_knobs::ExtraSamplerFields`.
935    #[serde(flatten)]
936    extra_samplers: crate::sampling_knobs::ExtraSamplerFields,
937    /// Fields that change what comes back and that this server does not
938    /// implement, in ONE struct shared with the other two generation
939    /// routes. See `crate::unimplemented_fields`.
940    #[serde(flatten)]
941    unimplemented: crate::unimplemented_fields::UnimplementedFields,
942    #[serde(default)]
943    seed: Option<u64>,
944    #[serde(default)]
945    stop: Option<StopParam>,
946    #[serde(default)]
947    stream: Option<bool>,
948    /// Frink extension. `true` asks the server to keep a replay buffer
949    /// for this stream so a dropped connection can be resumed from the
950    /// last `id:` seen, or drained over the JSON polling fallback.
951    ///
952    /// It also changes what a dropped socket *means*. Without it, the
953    /// connection closing cancels the generation (see the `cancel`
954    /// module). With it, the generation keeps running into the replay
955    /// buffer -- which is the entire point, and the reason this is the
956    /// caller's decision rather than the server's: a tab that navigated
957    /// away wants the CPU back, and a tab whose proxy dropped a
958    /// 90-second answer wants the answer. `POST /v1/cancel` stops a
959    /// resumable stream either way.
960    #[serde(default)]
961    stream_resumable: Option<bool>,
962    /// Run past the model's own end-of-generation tokens, so this
963    /// request produces exactly `max_tokens`.
964    ///
965    /// A serving-benchmark knob, under the spelling the other
966    /// OpenAI-compatible servers use. It
967    /// exists because a benchmark whose requests stop at their own EOS
968    /// finishes them at different lengths, and the slowest percentile
969    /// is then whichever request happened to be asked for the most
970    /// tokens -- a fact about the prompts, reported as a fact about the
971    /// server. It does NOT withdraw the caller's own `stop` strings.
972    #[serde(default)]
973    ignore_eos: Option<bool>,
974    #[serde(default)]
975    tools: Vec<ToolDef>,
976    #[serde(default)]
977    tool_choice: Option<ToolChoice>,
978    /// The OpenAI extension every reasoning-model deployment actually
979    /// uses: whatever is in here becomes a top-level variable in the
980    /// checkpoint's own chat template, which is how `enable_thinking`
981    /// (Qwen3, gemma-4), `thinking` (DeepSeek) and `reasoning_effort`
982    /// are really driven. Values here can never shadow the structural
983    /// variables (`messages`, `tools`, `add_generation_prompt`) -- see
984    /// `frink_models::chat_template::RenderOptions`.
985    #[serde(default)]
986    chat_template_kwargs: Option<serde_json::Map<String, serde_json::Value>>,
987    /// OpenAI's own spelling of the same knob. It is folded into
988    /// `chat_template_kwargs` before rendering, and loses to an explicit
989    /// entry there: a caller who wrote both meant the specific one.
990    ///
991    /// `"none"` and `"off"` are not gears -- they mean *do not think*,
992    /// and are handled by [`ChatCompletionRequest::thinking_direction`]
993    /// before any quantization can round them onto a real one.
994    #[serde(default)]
995    reasoning_effort: Option<String>,
996    /// The DeepSeek wire's thinking switch: `{"type": "enabled"}` or
997    /// `{"type": "disabled"}`. It decides the direction outright, and
998    /// `disabled` beats any effort the same request also carries.
999    #[serde(default)]
1000    thinking: Option<ThinkingSwitch>,
1001    /// Server-side conversation history key (see the `session`
1002    /// module): when set, `messages` is treated as
1003    /// *only the new turn(s)* to append to this session's stored
1004    /// history, not the whole conversation.
1005    #[serde(default)]
1006    session_id: Option<String>,
1007    /// llama.cpp's `continue_final_message`: render the LAST message,
1008    /// which must be an assistant turn, as a turn still being written
1009    /// rather than a closed one, so the model carries on from where
1010    /// it stopped. `true`, `"reasoning_content"`, `"content"`, or
1011    /// `false`; unset, a trailing assistant message is continued by
1012    /// default, as llama.cpp's server does. The whole rule, its
1013    /// refusals included, is [`continuation`].
1014    #[serde(default, deserialize_with = "continuation::deserialize")]
1015    continue_final_message: continuation::ContinueFinalMessage,
1016    /// llama.cpp's `reasoning_budget_tokens` (alias
1017    /// `thinking_budget_tokens`): a token budget for the chain of
1018    /// thought, enforced in the sampler. `-1` or absent takes the
1019    /// server's `--reasoning-budget`; `0` closes the block the moment it
1020    /// opens; `N` allows N tokens of thought and then forces the closer.
1021    /// The range is checked at deserialization, so an out-of-range
1022    /// value is a 400 naming the field. See [`crate::reasoning_budget`].
1023    #[serde(default, alias = "thinking_budget_tokens")]
1024    reasoning_budget_tokens: Option<reasoning_budget::BudgetTokens>,
1025    /// OpenAI fields we explicitly reject rather than silently ignore.
1026    #[serde(default)]
1027    logprobs: Option<bool>,
1028    #[serde(default)]
1029    top_logprobs: Option<u32>,
1030    #[serde(default)]
1031    presence_penalty: Option<f32>,
1032    #[serde(default)]
1033    frequency_penalty: Option<f32>,
1034    #[serde(default)]
1035    response_format: Option<serde_json::Value>,
1036    /// Declared ONLY so it can be refused by name -- see
1037    /// [`crate::unsupported_sampling::refuse_logit_bias`], which
1038    /// `/v1/completions` calls with the same rules. Undeclared, serde
1039    /// dropped it and the caller got a 200 whose answer was sampled
1040    /// from unbiased logits, which is indistinguishable from having had
1041    /// the bias honoured.
1042    #[serde(default)]
1043    logit_bias: Option<serde_json::Value>,
1044    /// llama.cpp's per-request `lora: [{id, scale}]`: the scale of every
1045    /// loaded adapter for THIS request, unnamed adapters at 0. Resolved
1046    /// against the loaded adapters by `crate::lora::resolve_request`.
1047    #[serde(default)]
1048    lora: Option<Vec<frink_api::LoraScaleRequest>>,
1049    /// llama.cpp's `samplers`: the ORDER the sampler chain runs in,
1050    /// either a list of names or the one `;`-separated string
1051    /// `--samplers` takes.
1052    ///
1053    /// Read as `Value` and decided by
1054    /// [`crate::unsupported_sampling::parse_sampler_order`], shared with
1055    /// `/v1/completions` and `/completion`, so the three routes cannot
1056    /// disagree about which samplers exist. A sampler frink does not
1057    /// implement is refused BY NAME rather than dropped from the chain.
1058    #[serde(default)]
1059    samplers: Option<serde_json::Value>,
1060    /// A GBNF grammar every sampled token must keep parseable.
1061    ///
1062    /// llama.cpp's field, spelled the same way, because a client that
1063    /// already builds a grammar for `llama-server` should not have to
1064    /// build a second one. Not an OpenAI field: OpenAI states the same
1065    /// constraint as `response_format: {"type": "json_schema"}`, which
1066    /// is now compiled through the same grammar engine. Sending BOTH is
1067    /// two constraints on one generation and is refused -- see
1068    /// [`crate::grammar_request`], where every spelling is resolved.
1069    #[serde(default)]
1070    grammar: Option<String>,
1071}
1072
1073/// The output budget a chat request gets when it names none.
1074///
1075/// Not OpenAI's legacy 16 -- that floor belongs to `/v1/completions`,
1076/// where a caller asking for a completion of a fragment usually wants a
1077/// fragment back. A chat client that omits `max_tokens` wants an
1078/// answer, and 16 tokens of one reads as a truncated server.
1079///
1080/// It is safe to be this large only because the context ceiling CLAMPS
1081/// rather than refuses (see `generate`): a request whose prompt leaves
1082/// less than this much room is served with what remains, not rejected
1083/// over a number the caller never set.
1084const DEFAULT_CHAT_MAX_TOKENS: usize = 32_768;
1085
1086/// The DeepSeek-wire thinking switch.
1087#[derive(Debug, Clone, Deserialize)]
1088pub(crate) struct ThinkingSwitch {
1089    #[serde(rename = "type")]
1090    pub(crate) kind: String,
1091}
1092
1093/// Every spelling a caller can use to steer the template's thinking
1094/// themselves. If any of these is already present in
1095/// `chat_template_kwargs`, the protocol-level knobs stand down.
1096const THINKING_KWARG_KEYS: [&str; 4] = [
1097    "enable_thinking",
1098    "thinking",
1099    "thinking_mode",
1100    "reasoning_effort",
1101];
1102
1103/// The efforts that mean "do not think" rather than naming a gear.
1104/// Compared after trimming and lowercasing, because a client that sends
1105/// `"None"` means the same thing.
1106const DISABLE_EFFORTS: [&str; 2] = ["none", "off"];
1107
1108fn default_max_tokens() -> usize {
1109    DEFAULT_CHAT_MAX_TOKENS
1110}
1111
1112impl ChatCompletionRequest {
1113    /// This request's sampler knobs. Resolved to `SamplingParams` by
1114    /// `sampling_knobs`, shared with `/v1/completions`, so the two
1115    /// routes cannot disagree about what a knob means or which ones
1116    /// exist.
1117    ///
1118    /// Fallible because `samplers` is parsed here: a chain naming a
1119    /// sampler this engine does not have is a refusal, never a chain
1120    /// built without it.
1121    fn sampling_knobs(&self) -> Result<SamplingKnobs, ApiError> {
1122        let mut knobs = SamplingKnobs {
1123            temperature: self.temperature,
1124            top_p: self.top_p,
1125            min_p: self.min_p,
1126            top_k: self.top_k,
1127            repetition_penalty: self.repetition_penalty,
1128            presence_penalty: self.presence_penalty,
1129            frequency_penalty: self.frequency_penalty,
1130            // The OpenAI wire has no field for the penalty window; only
1131            // llama.cpp's native `/completion` does. See
1132            // `SamplingKnobs::penalty_last_n`.
1133            penalty_last_n: None,
1134            sampler_order: unsupported_sampling::parse_sampler_order(
1135                self.samplers.as_ref(),
1136                "/v1/chat/completions",
1137            )?,
1138            ..SamplingKnobs::default()
1139        };
1140        self.extra_samplers.apply(&mut knobs);
1141        Ok(knobs)
1142    }
1143
1144    fn sampling_params(
1145        &self,
1146        model: crate::sampling_knobs::SamplerModel<'_>,
1147    ) -> Result<SamplingParams, ApiError> {
1148        self.sampling_knobs()?.resolve(model).map_err(|e| {
1149            unsupported_feature(&format!("`dry_multiplier` on /v1/chat/completions: {e}"))
1150        })
1151    }
1152
1153    fn stop_sequences(&self) -> Vec<String> {
1154        self.stop
1155            .as_ref()
1156            .map(|s| match s {
1157                StopParam::One(v) => vec![v.clone()],
1158                StopParam::Many(v) => v.clone(),
1159            })
1160            .unwrap_or_default()
1161    }
1162
1163    /// Real tool-calling is only offered when `tools` is non-empty AND
1164    /// the client hasn't explicitly disabled it via `tool_choice:
1165    /// "none"` -- see `ToolChoice`'s doc comment for what the other
1166    /// values do (nothing different from `"auto"`).
1167    /// How many alternatives to report per position, or `None` when
1168    /// this request did not ask for logprobs at all.
1169    ///
1170    /// OpenAI's chat wire splits the question in two: `logprobs: true`
1171    /// turns the object on, and `top_logprobs: N` says how many
1172    /// alternatives to list. `top_logprobs` without `logprobs` is not
1173    /// a valid request upstream and is refused here rather than read
1174    /// as an implied `true`, because guessing which of two fields the
1175    /// caller meant is how a server answers a question nobody asked.
1176    fn n_logprobs(&self) -> Result<Option<usize>, ApiError> {
1177        const MAX: u32 = 20;
1178        match (self.logprobs, self.top_logprobs) {
1179            (Some(true), Some(n)) if n > MAX => Err(invalid_request(
1180                &format!(
1181                    "`top_logprobs` is {n}; this server reports at most {MAX} alternatives per \
1182                     position, as upstream does"
1183                ),
1184                "top_logprobs",
1185            )),
1186            (Some(true), Some(n)) => Ok(Some(n as usize)),
1187            // `logprobs: true` alone is the chosen token's logprob and
1188            // no alternatives, which is what upstream's default `0`
1189            // means.
1190            (Some(true), None) => Ok(Some(0)),
1191            (_, Some(_)) => Err(invalid_request(
1192                "`top_logprobs` requires `logprobs: true`",
1193                "top_logprobs",
1194            )),
1195            _ => Ok(None),
1196        }
1197    }
1198
1199    fn tools_active(&self) -> bool {
1200        !self.tools.is_empty()
1201            && !matches!(&self.tool_choice, Some(ToolChoice::Mode(m)) if m == "none")
1202    }
1203
1204    /// Whether this request FORCES a tool call, and which tools it may
1205    /// choose between.
1206    ///
1207    /// `"required"` and a named function are the same question with a
1208    /// different answer set, so they are one function here and one
1209    /// grammar builder downstream. Everything else -- absent, `"auto"`,
1210    /// `"none"` -- forces nothing and returns `None`.
1211    ///
1212    /// An object `tool_choice` that names nothing is a 400 rather than a
1213    /// silent `None`: a client that sent `{"type": "function"}` and got
1214    /// an unforced answer cannot tell that apart from a served one.
1215    fn forced_tool_choice(&self) -> Result<Option<tool_grammar::Forced<'_>>, ApiError> {
1216        match &self.tool_choice {
1217            Some(ToolChoice::Mode(m)) if m == "required" => Ok(Some(tool_grammar::Forced::Any)),
1218            Some(ToolChoice::Specific(value)) => {
1219                // OpenAI's shape is `{"type":"function","function":{"name":…}}`;
1220                // several clients send `{"name":…}` flat, and both name
1221                // the same thing.
1222                let name = value
1223                    .get("function")
1224                    .and_then(|f| f.get("name"))
1225                    .or_else(|| value.get("name"))
1226                    .and_then(|n| n.as_str());
1227                match name {
1228                    Some(name) => Ok(Some(tool_grammar::Forced::Named(name))),
1229                    None => Err(invalid_request(
1230                        "tool_choice must be \"auto\", \"none\", \"required\", or an object with \
1231                         function.name",
1232                        "tool_choice",
1233                    )),
1234                }
1235            }
1236            _ => Ok(None),
1237        }
1238    }
1239
1240    /// The offered tools, reduced to what [`tool_grammar`] needs.
1241    fn tool_specs(&self) -> Vec<tool_grammar::ToolSpec<'_>> {
1242        self.tools
1243            .iter()
1244            .map(|t| tool_grammar::ToolSpec {
1245                name: &t.function.name,
1246                parameters: t.function.parameters.as_ref(),
1247            })
1248            .collect()
1249    }
1250
1251    /// The `chat_template_kwargs` this request actually renders with.
1252    ///
1253    /// Five rules, all of them from `frink-edge`:
1254    ///
1255    /// * **An explicit knob wins wholesale.** A caller who already set
1256    ///   any of `enable_thinking` / `thinking` / `thinking_mode` /
1257    ///   `reasoning_effort` inside `chat_template_kwargs` has said what
1258    ///   they want; the protocol-level knobs are then ignored entirely
1259    ///   rather than merged, because a merge would let a default
1260    ///   contradict an explicit request.
1261    /// * **`none` and `off` are not gears.** `reasoning_effort: "none"`
1262    ///   means *turn thinking off* and broadcasts the off pair; it must
1263    ///   not be quantized onto the nearest gear, which would turn "do
1264    ///   not think" into "think a little". Same for the DeepSeek-wire
1265    ///   `thinking: {"type": "disabled"}`, which beats any effort.
1266    ///
1267    /// * **Thinking follows the tools.** Offering tools turns thinking
1268    ///   on even when the caller said nothing, because some encoders
1269    ///   emit well-formed tool calls only in thinking mode
1270    ///   ([`crate::policy::effort::resolve_thinking_mode`]).
1271    /// * **Effort is quantized onto what this checkpoint grades.** A
1272    ///   template that accepts only the OpenAI triple must not be sent
1273    ///   `minimal`; it is mapped to the nearest gear, or dropped when no
1274    ///   gear is close enough, rather than interpolated verbatim into
1275    ///   the prompt ([`crate::policy::effort::sanitize_effort`], against the
1276    ///   profile probed at load).
1277    /// * **One value, every spelling.** The graded-strength dialect
1278    ///   reads `reasoning_strength`; a Jinja template ignores variables
1279    ///   it does not declare, so broadcasting costs nothing and removes
1280    ///   a per-family routing table
1281    ///   ([`crate::policy::effort::broadcast_effort_spellings`]).
1282    ///
1283    /// Every render path has to do this identically -- a request that
1284    /// validates against one prompt and generates from another is the
1285    /// failure this returns a single value to prevent.
1286    /// Which way this request steers thinking, before any template is
1287    /// consulted: `Some(false)` off, `Some(true)` on, `None` unstated.
1288    ///
1289    /// `thinking: {"type": …}` decides outright and `disabled` wins over
1290    /// any effort, because a client that sent both a switch and a gear
1291    /// meant the switch -- the gear is what it would use *if* thinking
1292    /// were on.
1293    fn thinking_direction(&self) -> Option<bool> {
1294        if let Some(switch) = &self.thinking {
1295            return match switch.kind.trim().to_ascii_lowercase().as_str() {
1296                "disabled" => Some(false),
1297                "enabled" => Some(true),
1298                // An unrecognized type is not a silent default -- see
1299                // `validate_supported_fields`, which rejects it.
1300                _ => None,
1301            };
1302        }
1303        let effort = self.reasoning_effort.as_ref()?;
1304        DISABLE_EFFORTS
1305            .contains(&effort.trim().to_ascii_lowercase().as_str())
1306            .then_some(false)
1307    }
1308
1309    fn resolve_template_kwargs(
1310        &self,
1311        template: &chat_template::PromptTemplate,
1312    ) -> serde_json::Map<String, serde_json::Value> {
1313        let mut kwargs = self.chat_template_kwargs.clone().unwrap_or_default();
1314        // Whether the caller steered the template themselves. Read
1315        // BEFORE anything is added, or every request looks explicit
1316        // from the second statement on.
1317        let caller_steered = THINKING_KWARG_KEYS.iter().any(|k| kwargs.contains_key(*k));
1318
1319        if !caller_steered {
1320            match self.thinking_direction() {
1321                Some(false) => {
1322                    for (k, v) in crate::policy::effort::thinking_off_kwargs() {
1323                        kwargs.insert(k, v);
1324                    }
1325                    // Nothing below applies: an effort would re-enter a
1326                    // block this request just closed.
1327                    return kwargs;
1328                }
1329                Some(true) => {
1330                    for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1331                        kwargs.insert(k, v);
1332                    }
1333                }
1334                None => {}
1335            }
1336            if let Some(effort) = &self.reasoning_effort {
1337                kwargs
1338                    .entry("reasoning_effort".to_string())
1339                    .or_insert_with(|| serde_json::json!(effort));
1340            }
1341        }
1342
1343        let offered: Vec<serde_json::Value> = if self.tools_active() {
1344            self.tools.iter().map(chat_template::tool_json).collect()
1345        } else {
1346            Vec::new()
1347        };
1348        let thinking = crate::policy::effort::resolve_thinking_mode(Some(&kwargs), Some(&offered));
1349        if thinking == crate::policy::effort::ThinkingMode::Thinking {
1350            for (k, v) in crate::policy::effort::thinking_on_kwargs() {
1351                kwargs.entry(k).or_insert(v);
1352            }
1353        }
1354        match crate::policy::effort::sanitize_effort(&mut kwargs, template.efforts()) {
1355            crate::policy::effort::EffortMapping::Mapped(to) => {
1356                tracing::debug!("reasoning_effort quantized to {}", to.as_str());
1357            }
1358            crate::policy::effort::EffortMapping::Dropped => {
1359                tracing::debug!(
1360                    "reasoning_effort dropped: this checkpoint's template grades no gear close \
1361                     enough, so its own default applies"
1362                );
1363            }
1364            crate::policy::effort::EffortMapping::Unchanged => {}
1365        }
1366        crate::policy::effort::broadcast_effort_spellings(&mut kwargs);
1367        kwargs
1368    }
1369
1370    /// Reject OpenAI fields we do not implement, and `tool_choice`
1371    /// values that would silently lie (required / named function).
1372    fn validate_supported_fields(&self) -> Result<(), ApiError> {
1373        // An explicit zero is a client error, not "unset". Serde already
1374        // told them apart -- an absent field became
1375        // `DEFAULT_CHAT_MAX_TOKENS` -- so a 0 here is one the caller
1376        // wrote, and the engine cannot serve a zero-token budget: the
1377        // request would never become decodable and the client would wait
1378        // for an answer that cannot arrive.
1379        if self.max_tokens == 0 {
1380            return Err(invalid_request(
1381                "max_tokens must be at least 1",
1382                "max_tokens",
1383            ));
1384        }
1385        // An unrecognized switch is refused rather than read as "on":
1386        // a client that misspells `disabled` and is served a thinking
1387        // model anyway has been silently given the opposite of what it
1388        // asked for.
1389        if let Some(switch) = &self.thinking {
1390            let kind = switch.kind.trim().to_ascii_lowercase();
1391            if kind != "enabled" && kind != "disabled" {
1392                return Err(invalid_request(
1393                    "thinking.type must be \"enabled\" or \"disabled\"",
1394                    "thinking.type",
1395                ));
1396            }
1397        }
1398        for msg in &self.messages {
1399            if msg.content.as_ref().is_some_and(MessageContent::has_image) {
1400                return Err(unsupported_feature(
1401                    "image_url content parts are not implemented (multimodal/VL deferred, see docs/API.md)",
1402                ));
1403            }
1404        }
1405        // Served (`crate::logprobs::render_chat`); what is refused is
1406        // a `top_logprobs` above upstream's cap, which is a 400 on the
1407        // value rather than a 501 on the field.
1408        self.n_logprobs()?;
1409        // `n` moved into `crate::unimplemented_fields` with the rest of
1410        // the surface: it was refused HERE and dropped on
1411        // `/v1/completions`, which is the split that module exists for.
1412        self.unimplemented.refuse("/v1/chat/completions")?;
1413        unsupported_sampling::refuse_logit_bias(self.logit_bias.as_ref(), "/v1/chat/completions")?;
1414        // Parsed here as well as in `sampling_knobs` so a bad chain is
1415        // a 400/501 before any prompt is rendered. The same function
1416        // both times, so there is no second opinion to drift from.
1417        unsupported_sampling::parse_sampler_order(self.samplers.as_ref(), "/v1/chat/completions")?;
1418        // Every spelling of "constrain the output", resolved by the one
1419        // function that knows the rule: `grammar` is compiled and a
1420        // `response_format` is decided in full -- its schema converted,
1421        // its unhonoured members refused by name, its unknown types
1422        // refused by the type they named. Done here so all of that is a
1423        // 400 before any prompt is rendered. The result is recompiled in
1424        // `generation_params`, which is the only other caller: a grammar
1425        // is a small parse, and one rule in two places would be two
1426        // rules soon enough.
1427        //
1428        // Kept as ONE call rather than a second `match` on
1429        // `response_format` beside it. The one that used to be here
1430        // answered `json_schema` with "only json_object is supported"
1431        // and had to be kept in step with the module by hand.
1432        let stated_grammar =
1433            grammar_request::for_request(self.grammar.as_deref(), self.response_format.as_ref())?;
1434        // A forced `tool_choice` is served by compiling the offered tools
1435        // into a grammar (`tool_grammar`). What can be checked without
1436        // knowing which checkpoint is loaded is checked here, so the
1437        // caller's own mistakes are refused before a prompt is rendered;
1438        // the rest -- whether the served family's wire format has a
1439        // grammar at all -- needs the model and is refused in
1440        // `generation_params_for_template`.
1441        if let Some(forced) = self.forced_tool_choice()? {
1442            if self.tools.is_empty() {
1443                return Err(invalid_request(
1444                    "tool_choice forces a tool call, but no tools were offered",
1445                    "tool_choice",
1446                ));
1447            }
1448            if let tool_grammar::Forced::Named(name) = forced {
1449                if !self.tools.iter().any(|t| t.function.name == name) {
1450                    return Err(invalid_request(
1451                        &format!(
1452                            "tool_choice names {name:?}, which is not one of the tools offered"
1453                        ),
1454                        "tool_choice",
1455                    ));
1456                }
1457            }
1458            // Two different constraints on one generation. Serving the
1459            // one we happen to compile last is not answering either.
1460            //
1461            // Asked of the RESOLVED grammar rather than of
1462            // `self.grammar`: a `response_format` json_schema states one
1463            // too, and a check spelled against one field would have let
1464            // the other through -- `generation_params_for_template`
1465            // overwrites `params.grammar` with the tool-call grammar on
1466            // the strength of this refusal having happened.
1467            if stated_grammar.is_some() {
1468                return Err(invalid_request(
1469                    "a forced tool_choice and a \"grammar\" or response_format \"json_schema\" \
1470                     are two different constraints on the same generation; send one",
1471                    "tool_choice",
1472                ));
1473            }
1474            if self.json_object_mode() {
1475                return Err(invalid_request(
1476                    "a forced tool_choice cannot be combined with response_format json_object: \
1477                     the tool-call markers are not JSON",
1478                    "tool_choice",
1479                ));
1480            }
1481        }
1482        Ok(())
1483    }
1484
1485    /// `stop_sequences()` plus `</tool_call>` when tool-calling is
1486    /// active -- reusing the existing stop-sequence machinery
1487    /// (`generate::generate`'s `earliest_stop_match`) to end generation
1488    /// right after a tool call's JSON body, rather than adding any new
1489    /// decode-time logic. See `tool_preamble`'s doc comment for the
1490    /// full real, disclosed approach.
1491    fn effective_stop_sequences(&self) -> Vec<String> {
1492        let mut stop = self.stop_sequences();
1493        if self.tools_active() {
1494            stop.push("</tool_call>".to_string());
1495        }
1496        stop
1497    }
1498
1499    fn json_object_mode(&self) -> bool {
1500        self.response_format
1501            .as_ref()
1502            .and_then(|v| v.get("type"))
1503            .and_then(|v| v.as_str())
1504            == Some("json_object")
1505    }
1506}
1507
1508#[derive(Serialize)]
1509struct ChatCompletionChoice {
1510    index: usize,
1511    message: ChatCompletionResponseMessage,
1512    finish_reason: &'static str,
1513    /// OpenAI's chat `logprobs` object, absent unless the request
1514    /// asked (`crate::logprobs::render_chat`). `null` and absent mean
1515    /// the same thing to a client here, and absent is the smaller
1516    /// answer.
1517    #[serde(skip_serializing_if = "Option::is_none")]
1518    logprobs: Option<serde_json::Value>,
1519}
1520
1521#[derive(Serialize)]
1522struct ChatCompletionResponseMessage {
1523    role: &'static str,
1524    #[serde(skip_serializing_if = "Option::is_none")]
1525    content: Option<String>,
1526    /// A reasoning model's chain of thought, split out of `content`.
1527    /// Absent for a model that emitted none, which is also what a
1528    /// client that does not know the field sees.
1529    #[serde(skip_serializing_if = "Option::is_none")]
1530    reasoning_content: Option<String>,
1531    #[serde(skip_serializing_if = "Option::is_none")]
1532    tool_calls: Option<Vec<ToolCallOut>>,
1533}
1534
1535#[derive(Serialize, Clone)]
1536struct ToolCallOut {
1537    id: String,
1538    #[serde(rename = "type")]
1539    kind: &'static str,
1540    function: ToolCallFunctionOut,
1541}
1542
1543/// One tool call as a **streamed delta**.
1544///
1545/// OpenAI's incremental shape: `index` correlates the pieces, and every
1546/// other field is optional because the first delta of a call carries
1547/// its identity and the ones after it carry only more argument text. A
1548/// buffered path expresses a whole call as a delta with every field
1549/// set, so there is one type on the wire rather than two.
1550#[derive(Serialize, Clone)]
1551struct ToolCallDelta {
1552    index: usize,
1553    #[serde(skip_serializing_if = "Option::is_none")]
1554    id: Option<String>,
1555    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1556    kind: Option<&'static str>,
1557    function: ToolCallFunctionDelta,
1558}
1559
1560#[derive(Serialize, Clone, Default)]
1561struct ToolCallFunctionDelta {
1562    #[serde(skip_serializing_if = "Option::is_none")]
1563    name: Option<String>,
1564    /// A literal continuation of this call's arguments JSON. A client
1565    /// concatenates them in `index` order and parses the result.
1566    #[serde(skip_serializing_if = "Option::is_none")]
1567    arguments: Option<String>,
1568}
1569
1570impl ToolCallDelta {
1571    /// The whole call in one delta, for a path that had it all along.
1572    fn whole(index: usize, name: String, arguments: String) -> Self {
1573        ToolCallDelta {
1574            index,
1575            id: Some(format!("call_{index}")),
1576            kind: Some("function"),
1577            function: ToolCallFunctionDelta {
1578                name: Some(name),
1579                arguments: Some(arguments),
1580            },
1581        }
1582    }
1583
1584    /// The opening delta: identity, and no arguments yet.
1585    fn opening(index: usize, name: String) -> Self {
1586        ToolCallDelta {
1587            index,
1588            id: Some(format!("call_{index}")),
1589            kind: Some("function"),
1590            function: ToolCallFunctionDelta {
1591                name: Some(name),
1592                arguments: Some(String::new()),
1593            },
1594        }
1595    }
1596
1597    /// A continuation: more argument text for a call already opened.
1598    fn arguments(index: usize, fragment: String) -> Self {
1599        ToolCallDelta {
1600            index,
1601            id: None,
1602            kind: None,
1603            function: ToolCallFunctionDelta {
1604                name: None,
1605                arguments: Some(fragment),
1606            },
1607        }
1608    }
1609}
1610
1611#[derive(Serialize, Clone)]
1612struct ToolCallFunctionOut {
1613    name: String,
1614    /// A JSON-encoded string, matching the real OpenAI
1615    /// `tool_calls[].function.arguments` convention (see
1616    /// `ToolCallFunctionIn::arguments`'s doc comment).
1617    arguments: String,
1618}
1619
1620#[derive(Serialize)]
1621struct ChatCompletionResponse {
1622    id: String,
1623    /// Non-standard extension: the same value as `id`, stated under the
1624    /// name the rest of frink keys by (metrics, logs, `POST /cancel`
1625    /// once it exists). `id` is OpenAI's completion id and a client has
1626    /// no way to know frink also uses it as the request key -- saying
1627    /// so costs one field and removes the guess.
1628    request_id: String,
1629    object: &'static str,
1630    model: String,
1631    choices: Vec<ChatCompletionChoice>,
1632    /// OpenAI-convention token accounting (prompt/completion/total),
1633    /// counted from the exact ids the generation loop processed. On a
1634    /// whole-response cache hit, this is the original computation's
1635    /// accounting (same prompt, same deterministic outcome).
1636    usage: generate::Usage,
1637    /// Non-standard extension field (not part of the OpenAI API
1638    /// contract, but additive and harmless to OpenAI-compatible
1639    /// clients that ignore unknown fields): "hit" if this exact
1640    /// cacheable request was already computed, "miss" if this request
1641    /// just computed and cached a fresh completion, or "skip" if
1642    /// nothing was stored -- either the request wasn't cacheable at all
1643    /// (sampling without a seed -- see
1644    /// `ChatCompletionRequest::is_cacheable`) or the answer was not a
1645    /// complete one and may not be replayed to anybody (a cancelled
1646    /// generation -- see `response_cache::CachedCompletion::cacheable`).
1647    frink_cache: &'static str,
1648}
1649
1650#[derive(Serialize)]
1651struct ChatCompletionChunkDelta {
1652    #[serde(skip_serializing_if = "Option::is_none")]
1653    role: Option<&'static str>,
1654    #[serde(skip_serializing_if = "Option::is_none")]
1655    content: Option<String>,
1656    /// See `ChatCompletionResponseMessage::reasoning_content`.
1657    #[serde(skip_serializing_if = "Option::is_none")]
1658    reasoning_content: Option<String>,
1659    #[serde(skip_serializing_if = "Option::is_none")]
1660    tool_calls: Option<Vec<ToolCallDelta>>,
1661}
1662
1663#[derive(Serialize)]
1664struct ChatCompletionChunkChoice {
1665    index: usize,
1666    delta: ChatCompletionChunkDelta,
1667    finish_reason: Option<&'static str>,
1668}
1669
1670#[derive(Serialize)]
1671struct ChatCompletionChunk {
1672    id: String,
1673    /// Present on the **first** chunk of a stream (see
1674    /// `ChatCompletionResponse::request_id`). A client learns the key
1675    /// for this generation before any content arrives, so a live view
1676    /// can correlate metrics with the stream it is rendering instead of
1677    /// guessing which in-flight request is "probably mine" -- a guess
1678    /// that mis-attributes the moment two chats run at once.
1679    #[serde(skip_serializing_if = "Option::is_none")]
1680    request_id: Option<String>,
1681    object: &'static str,
1682    model: String,
1683    choices: Vec<ChatCompletionChunkChoice>,
1684    /// Present only on the final chunk (the one carrying
1685    /// `finish_reason`), mirroring OpenAI's stream `usage` shape.
1686    #[serde(skip_serializing_if = "Option::is_none")]
1687    usage: Option<generate::Usage>,
1688}
1689
1690/// Liveness, readiness and capabilities in one cheap answer (see the
1691/// `health` module for why detection is a visible state rather than a
1692/// gap). Never behind auth or rate limiting, and never blocking: this is
1693/// the endpoint a supervisor asks when it is deciding whether to kill
1694/// the process.
1695async fn health(State(state): State<Arc<AppState>>) -> Response {
1696    let snapshot = state.detection.snapshot();
1697    let mut capabilities = snapshot.capabilities;
1698    let active = state.active();
1699
1700    // Model-derived capabilities need no probing, so they are answered
1701    // even while backend detection is still running.
1702    capabilities.push(match active.as_deref() {
1703        // `unavailable` was defined in Phase 1 but unreachable, because
1704        // the server only bound the port after a successful load. With
1705        // `/admin/models/unload` it is a state a client can actually
1706        // observe, and it must not read as "loaded but synthetic".
1707        None => frink_api::Capability::unavailable(
1708            frink_api::health::capability::REAL_WEIGHTS,
1709            frink_api::health::reason::MODEL_NOT_LOADED,
1710            "No model is loaded. POST /admin/models/load with an id from GET /admin/models.",
1711        ),
1712        Some(active) if active.is_synthetic() => frink_api::Capability::unavailable(
1713            frink_api::health::capability::REAL_WEIGHTS,
1714            frink_api::health::reason::MODEL_NOT_LOADED,
1715            "Serving synthetic random weights: set FRINK_MODEL_PATH (or -m) to a real \
1716             checkpoint. Output from this model is noise.",
1717        ),
1718        // An encoder is real weights and is genuinely serving, so this
1719        // is `available` -- but a supervisor reading "serving X" and
1720        // then getting 501 from /v1/chat/completions learned nothing.
1721        // The detail says which endpoint this checkpoint is for.
1722        // NOT a hard-coded /v1/embeddings any more: a reranker is an
1723        // encoder too, and its pooling_type is RANK, which
1724        // /v1/embeddings refuses and /v1/rerank is for. See
1725        // `rerank::encoder_endpoints`, which `/v1/models` reads as well
1726        // so the two cannot disagree.
1727        Some(active) if active.encoder().is_some() => {
1728            let endpoints = active
1729                .encoder()
1730                .map(|e| encoder_endpoints(e))
1731                .unwrap_or_default();
1732            let served_by = match endpoints.is_empty() {
1733                true => "no endpoint in this build serves it".to_string(),
1734                false => format!("served by {}", endpoints.join(" and ")),
1735            };
1736            frink_api::Capability::available(
1737                frink_api::health::capability::REAL_WEIGHTS,
1738                format!(
1739                    "Serving the real embedding checkpoint '{}'. This is an ENCODER, \
1740                     {served_by}; generation endpoints refuse it.",
1741                    active.name(),
1742                ),
1743            )
1744        }
1745        Some(active) => frink_api::Capability::available(
1746            frink_api::health::capability::REAL_WEIGHTS,
1747            format!("Serving the real checkpoint '{}'.", active.name()),
1748        ),
1749    });
1750    capabilities.push(if active.as_ref().is_some_and(|a| a.batcher.is_some()) {
1751        frink_api::Capability::available(
1752            frink_api::health::capability::CONTINUOUS_BATCHING,
1753            if state.continuous_batching_enabled && continuous_batching_env().is_none() {
1754                "On by default on Metal. Concurrent requests share one batched decode worker."
1755            } else {
1756                "Concurrent requests share one batched decode step."
1757            },
1758        )
1759    } else if state.metal_private_decode_gate.is_some() {
1760        frink_api::Capability::unavailable(
1761            frink_api::health::capability::CONTINUOUS_BATCHING,
1762            frink_api::health::reason::DISABLED,
1763            "Off; private Metal decodes serialize (one at a time). Set FRINK_CONTINUOUS_BATCHING=1 or --cont-batching for parallel serving.",
1764        )
1765    } else {
1766        frink_api::Capability::unavailable(
1767            frink_api::health::capability::CONTINUOUS_BATCHING,
1768            frink_api::health::reason::DISABLED,
1769            "Off; set FRINK_CONTINUOUS_BATCHING=1 (incompatible with a KV pool or prefix cache).",
1770        )
1771    });
1772
1773    let last_request_ms = state
1774        .last_request_ms
1775        .load(std::sync::atomic::Ordering::Relaxed);
1776    let uptime = state.started_at.elapsed();
1777    // Readiness is "can this server generate", and with nothing loaded
1778    // it cannot -- so `unavailable` (503) wins over whatever the backend
1779    // probe concluded. Phase 1 defined this state but nothing could
1780    // reach it, because the process only bound the port after a
1781    // successful load; `/admin/models/unload` makes it reachable, and a
1782    // 200 `ready` here would tell a supervisor to send traffic that is
1783    // guaranteed to 503.
1784    let health_state = if active.is_none() {
1785        frink_api::HealthState::Unavailable
1786    } else {
1787        snapshot.state
1788    };
1789    let body = frink_api::HealthResponse {
1790        state: health_state,
1791        reason: match health_state {
1792            frink_api::HealthState::Ready => None,
1793            frink_api::HealthState::Unavailable => {
1794                Some(frink_api::health::reason::MODEL_NOT_LOADED.to_string())
1795            }
1796            frink_api::HealthState::Detecting => {
1797                Some(frink_api::health::reason::DETECTING.to_string())
1798            }
1799        },
1800        detail: match health_state {
1801            frink_api::HealthState::Ready => None,
1802            frink_api::HealthState::Unavailable => Some(
1803                "No model is loaded. POST /admin/models/load with an id from GET /admin/models."
1804                    .to_string(),
1805            ),
1806            frink_api::HealthState::Detecting => {
1807                Some("Probing available compute backends.".to_string())
1808            }
1809        },
1810        model: active
1811            .as_deref()
1812            .map(|active| frink_api::health::ModelSummary {
1813                id: active.name().to_string(),
1814                tokenizer: active.tokenizer_kind().to_string(),
1815                synthetic_weights: active.is_synthetic(),
1816            }),
1817        capabilities,
1818        version: env!("CARGO_PKG_VERSION").to_string(),
1819        pid: std::process::id(),
1820        uptime_seconds: uptime.as_secs_f64(),
1821        server_time_unix_ms: std::time::SystemTime::now()
1822            .duration_since(std::time::UNIX_EPOCH)
1823            .map(|d| d.as_millis().min(u64::MAX as u128) as u64)
1824            .unwrap_or(0),
1825        last_request_age_seconds: (last_request_ms > 0)
1826            .then(|| uptime.as_secs_f64() - (last_request_ms as f64 / 1000.0))
1827            .map(|age| age.max(0.0)),
1828    };
1829
1830    let status =
1831        StatusCode::from_u16(body.state.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1832    (status, Json(body)).into_response()
1833}
1834
1835async fn list_models(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1836    // OpenAI's `/v1/models` lists what can be *used* right now, which
1837    // after an unload is nothing. The inventory of what is on disk is a
1838    // different question and lives at `/admin/models`.
1839    let Some(active) = state.active() else {
1840        return Json(serde_json::json!({ "object": "list", "data": [] }));
1841    };
1842    let mut model_entry = serde_json::json!({
1843        "id": active.name(),
1844        "object": "model",
1845        "frink_synthetic_weights": active.is_synthetic(),
1846        "frink_tokenizer": active.tokenizer_kind(),
1847    });
1848    // An encoder is listed -- it IS what is loaded, and a client asking
1849    // "what can I use" must be told about it -- but it is listed as
1850    // what it is. `frink_endpoints` is the machine-readable half of
1851    // the 501 a generation route would answer with: a client that reads
1852    // it never has to send the request to find out.
1853    if let Some(encoder) = active.encoder() {
1854        model_entry["frink_model_kind"] = serde_json::json!("embedding");
1855        model_entry["frink_endpoints"] = serde_json::json!(encoder_endpoints(encoder));
1856        model_entry["frink_n_embd"] = serde_json::json!(encoder.n_embd());
1857        model_entry["frink_pooling"] = serde_json::json!(encoder.pooling_type().name());
1858        model_entry["frink_context_length"] = serde_json::json!(encoder.n_ctx_train());
1859    }
1860    // Which reasoning gears this checkpoint really has, learned by
1861    // probing its own template at load. A checkpoint that says nothing
1862    // about thinking carries NEITHER field rather than an empty list:
1863    // an empty list reads as "asked, and it has no gears", which is a
1864    // different claim from "this is not a reasoning model". An encoder
1865    // is not asked at all, for the same reason -- it has no template to
1866    // probe, and `ThinkGears::default()` would be an invented answer.
1867    if let Some(model) = active.generative_opt() {
1868        let parser_configured = active.reasoning_format().is_some();
1869        let gears = model.chat_template().think_gears(parser_configured);
1870        if !gears.is_empty() {
1871            model_entry["supported_reasoning_efforts"] = serde_json::json!(gears.supported);
1872            if let Some(default) = &gears.default {
1873                model_entry["default_reasoning_effort"] = serde_json::json!(default);
1874            }
1875            // What to SEND for each gear, so a client selects one without
1876            // knowing that "off" is two booleans and "high" is a string.
1877            model_entry["reasoning_effort_kwargs"] = serde_json::json!(gears.kwargs);
1878        }
1879    }
1880    if let Some(mcp) = &state.mcp {
1881        model_entry["frink_mcp"] = mcp.models_metadata();
1882    }
1883    Json(serde_json::json!({
1884        "object": "list",
1885        "data": [model_entry]
1886    }))
1887}
1888
1889/// `GET /v1/stats`: what is happening *now*.
1890///
1891/// Distinct from `/admin/stats`, which is the historical ring. The two
1892/// throughput figures come from sliding windows, so an idle server
1893/// reports 0 rather than the rate it managed while it was busy -- a
1894/// cumulative average never comes back down, and a status bar showing
1895/// one is reporting the past as the present.
1896///
1897/// Latency is the ring's p95, nearest-rank, so it names a request that
1898/// really took that long. Both it and the mean time-to-first-token are
1899/// `null` rather than `0` when nothing can be said: a non-streamed
1900/// request has no TTFT, and averaging those in as zero would make the
1901/// server look faster the fewer clients stream.
1902async fn serving_stats(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
1903    let now_ms = state.uptime().as_millis().min(u64::MAX as u128) as u64;
1904    let mut serving = state.serving.lock().unwrap_or_else(|p| p.into_inner());
1905    let active = state.active();
1906    Json(serde_json::json!({
1907        "model": active.as_ref().map(|a| a.name()),
1908        "state": state
1909            .maintenance
1910            .lock()
1911            .unwrap_or_else(|p| p.into_inner())
1912            .state()
1913            .as_str(),
1914        "uptime_s": state.uptime().as_secs(),
1915        "throughput": {
1916            "decode_tps": (serving.decode_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1917            "prefill_tps": (serving.prefill_tokens_per_second(now_ms) * 10.0).round() / 10.0,
1918        },
1919        "requests": {
1920            "active": state.cancels.live_count(),
1921            "completed": state.stats.recorded_total(),
1922            "p95_ms": state.stats.p95_duration_ms(),
1923            "ttft_mean_ms": state.stats.ttft_mean_ms(),
1924            "prompt_tokens_total": state.stats.tokens_prompt_total(),
1925            "completion_tokens_total": state.stats.tokens_generated_total(),
1926        },
1927        // Served here so a status bar tracking throughput and pressure
1928        // makes ONE request rather than two. Upstream stamps the same
1929        // gauges on every reply of the batch; frink does not, because
1930        // the reply shapes here are OpenAI's and Anthropic's and a pool
1931        // gauge on a `chat.completion` is a field no client asked for.
1932        "pools": cache_admin::pool_gauges(&state),
1933        // What the engine is REALLY using, beside the budget it was
1934        // sized against. `null` when no live figure can be read.
1935        "memory": cache_admin::footprint_json(&state),
1936    }))
1937}
1938
1939#[derive(Deserialize)]
1940struct RequestsQuery {
1941    #[serde(default)]
1942    since: u64,
1943    #[serde(default = "default_requests_limit")]
1944    limit: usize,
1945}
1946
1947fn default_requests_limit() -> usize {
1948    stats::MAX_PAGE
1949}
1950
1951/// `GET /v1/requests?since=&limit=`: an incremental page of the ring.
1952///
1953/// The cursor is all-time, so a poller that keeps up reads each row
1954/// exactly once and never re-reads. `missed` is the honest half: rows
1955/// that existed and were evicted before this poll could see them. A
1956/// client polling slower than the server finishes requests needs to
1957/// know that, rather than have it hidden by a shorter page.
1958async fn recent_requests(
1959    State(state): State<Arc<AppState>>,
1960    axum::extract::Query(q): axum::extract::Query<RequestsQuery>,
1961) -> Json<serde_json::Value> {
1962    let (rows, cursor, missed) = state.stats.page(q.since, q.limit);
1963    Json(serde_json::json!({
1964        "requests": rows,
1965        "next_cursor": cursor,
1966        "missed": missed,
1967        "total": state.stats.recorded_total(),
1968    }))
1969}
1970
1971#[derive(Serialize)]
1972struct CombinedCacheStats {
1973    response_cache: response_cache::CacheStats,
1974    /// `None` when `FRINK_PREFIX_CACHE_ENTRIES` isn't set.
1975    prefix_cache: Option<frink_models::PrefixCacheStats>,
1976}
1977
1978async fn cache_stats(State(state): State<Arc<AppState>>) -> Json<CombinedCacheStats> {
1979    Json(CombinedCacheStats {
1980        response_cache: lock_cache(&state.response_cache).stats(),
1981        prefix_cache: state
1982            .prefix_cache
1983            .as_ref()
1984            .map(|pc| pc.lock().unwrap_or_else(|p| p.into_inner()).stats()),
1985    })
1986}
1987
1988/// Prometheus text-exposition format (`# HELP`/`# TYPE` plus
1989/// `name value` lines), so this endpoint can be scraped directly by a
1990/// Prometheus server or anything compatible with that format without
1991/// frink needing to speak any particular metrics client library.
1992async fn metrics(State(state): State<Arc<AppState>>) -> Response {
1993    use std::sync::atomic::Ordering;
1994
1995    let cache_stats = lock_cache(&state.response_cache).stats();
1996    let active = state.active();
1997    let requests_total = state.requests_total.load(Ordering::Relaxed);
1998    let errors_total = state.request_errors_total.load(Ordering::Relaxed);
1999    let uptime = state.started_at.elapsed().as_secs_f64();
2000
2001    let body = format!(
2002        "# HELP frink_requests_total Total chat completion requests received.\n\
2003         # TYPE frink_requests_total counter\n\
2004         frink_requests_total {requests_total}\n\
2005         # HELP frink_request_errors_total Total chat completion requests that returned an error.\n\
2006         # TYPE frink_request_errors_total counter\n\
2007         frink_request_errors_total {errors_total}\n\
2008         # HELP frink_cache_hits_total Whole-response cache hits.\n\
2009         # TYPE frink_cache_hits_total counter\n\
2010         frink_cache_hits_total {}\n\
2011         # HELP frink_cache_misses_total Whole-response cache misses.\n\
2012         # TYPE frink_cache_misses_total counter\n\
2013         frink_cache_misses_total {}\n\
2014         # HELP frink_cache_entries Current whole-response cache entry count.\n\
2015         # TYPE frink_cache_entries gauge\n\
2016         frink_cache_entries {}\n\
2017         # HELP frink_synthetic_weights 1 if serving synthetic random weights instead of a real checkpoint.\n\
2018         # TYPE frink_synthetic_weights gauge\n\
2019         frink_synthetic_weights {}\n\
2020         # HELP frink_uptime_seconds Seconds since this server process started.\n\
2021         # TYPE frink_uptime_seconds gauge\n\
2022         frink_uptime_seconds {uptime}\n",
2023        cache_stats.hits,
2024        cache_stats.misses,
2025        cache_stats.entries,
2026        // With nothing loaded there are no weights at all, synthetic or
2027        // otherwise; 0 is the reading that keeps the gauge meaning
2028        // "serving noise" rather than "serving nothing".
2029        active
2030            .as_ref()
2031            .map(|a| a.is_synthetic() as u8)
2032            .unwrap_or(0),
2033    );
2034
2035    // Expert-store counters, present only when the model streams
2036    // routed experts through the bounded cache
2037    // (FRINK_EXPERT_CACHE_BYTES).
2038    let body = match active
2039        .as_ref()
2040        .and_then(|a| a.expert_store_stats())
2041    {
2042        Some(es) => format!(
2043            "{body}\
2044             # HELP frink_expert_cache_hits_total Expert-store cache hits.\n\
2045             # TYPE frink_expert_cache_hits_total counter\n\
2046             frink_expert_cache_hits_total {}\n\
2047             # HELP frink_expert_cache_misses_total Expert-store cache misses (source reads).\n\
2048             # TYPE frink_expert_cache_misses_total counter\n\
2049             frink_expert_cache_misses_total {}\n\
2050             # HELP frink_expert_cache_evictions_total Expert-store LRU evictions.\n\
2051             # TYPE frink_expert_cache_evictions_total counter\n\
2052             frink_expert_cache_evictions_total {}\n\
2053             # HELP frink_expert_cache_pass_throughs_total Acquires served uncached (entry could not fit the budget).\n\
2054             # TYPE frink_expert_cache_pass_throughs_total counter\n\
2055             frink_expert_cache_pass_throughs_total {}\n\
2056             # HELP frink_expert_cache_bytes_read_total Bytes read from the checkpoint for expert misses.\n\
2057             # TYPE frink_expert_cache_bytes_read_total counter\n\
2058             frink_expert_cache_bytes_read_total {}\n\
2059             # HELP frink_expert_cache_resident_bytes Current expert-cache footprint in bytes.\n\
2060             # TYPE frink_expert_cache_resident_bytes gauge\n\
2061             frink_expert_cache_resident_bytes {}\n",
2062            es.hits, es.misses, es.evictions, es.pass_throughs, es.bytes_read, es.resident_bytes,
2063        ),
2064        None => body,
2065    };
2066
2067    // Scheduler counters, present only under continuous batching
2068    // (FRINK_CONTINUOUS_BATCHING=1). `prefill_chunks` next to
2069    // `prefill_tokens` is what makes chunked prefill observable: their
2070    // ratio is the effective chunk size the worker actually ran.
2071    let body = match active.as_ref().and_then(|a| a.batcher.as_ref()) {
2072        Some(batcher) => {
2073            let sched = batcher.stats();
2074            format!(
2075                "{body}\
2076                 # HELP frink_prefill_chunks_total Bounded prefill chunks the batch scheduler has run.\n\
2077                 # TYPE frink_prefill_chunks_total counter\n\
2078                 frink_prefill_chunks_total {}\n\
2079                 # HELP frink_prefill_tokens_total Prompt tokens run through chunked prefill.\n\
2080                 # TYPE frink_prefill_tokens_total counter\n\
2081                 frink_prefill_tokens_total {}\n\
2082                 # HELP frink_decode_steps_total Batched decode steps the batch scheduler has run.\n\
2083                 # TYPE frink_decode_steps_total counter\n\
2084                 frink_decode_steps_total {}\n\
2085                 # HELP frink_scheduler_queue_depth Requests waiting for admission to the batch scheduler.\n\
2086                 # TYPE frink_scheduler_queue_depth gauge\n\
2087                 frink_scheduler_queue_depth {}\n\
2088                 # HELP frink_scheduler_queue_rejected_total Requests refused with 503 because the admission queue was full.\n\
2089                 # TYPE frink_scheduler_queue_rejected_total counter\n\
2090                 frink_scheduler_queue_rejected_total {}\n\
2091                 # HELP frink_kv_blocks_total KV blocks in the scheduler's admission budget (0 when unconfigured).\n\
2092                 # TYPE frink_kv_blocks_total gauge\n\
2093                 frink_kv_blocks_total {}\n\
2094                 # HELP frink_kv_blocks_free KV blocks not reserved by an in-flight request.\n\
2095                 # TYPE frink_kv_blocks_free gauge\n\
2096                 frink_kv_blocks_free {}\n\
2097                 # HELP frink_kv_block_size Token positions per KV block.\n\
2098                 # TYPE frink_kv_block_size gauge\n\
2099                 frink_kv_block_size {}\n\
2100                 # HELP frink_kv_rejected_too_large_total Requests refused with 400 because they exceed the whole KV block budget.\n\
2101                 # TYPE frink_kv_rejected_too_large_total counter\n\
2102                 frink_kv_rejected_too_large_total {}\n\
2103                 # HELP frink_kv_rejected_context_length_total Requests refused with 400 for exceeding the per-request context ceiling.\n\
2104                 # TYPE frink_kv_rejected_context_length_total counter\n\
2105                 frink_kv_rejected_context_length_total {}\n\
2106                 # HELP frink_scheduler_aborted_total Requests the batch scheduler stopped because they were cancelled.\n\
2107                 # TYPE frink_scheduler_aborted_total counter\n\
2108                 frink_scheduler_aborted_total {}\n\
2109                 # HELP frink_scheduler_max_seqs Cap on in-flight sequences (-np / FRINK_CB_MAX_SEQS); 0 when unlimited.\n\
2110                 # TYPE frink_scheduler_max_seqs gauge\n\
2111                 frink_scheduler_max_seqs {}\n\
2112                 # HELP frink_scheduler_prefill_chunk Prompt tokens per prefill chunk (-b / -ub / FRINK_CB_PREFILL_CHUNK).\n\
2113                 # TYPE frink_scheduler_prefill_chunk gauge\n\
2114                 frink_scheduler_prefill_chunk {}\n",
2115                sched.prefill_chunks,
2116                sched.prefill_tokens,
2117                sched.decode_steps,
2118                sched.queue_depth,
2119                sched.queue_rejected,
2120                sched.kv_blocks_total,
2121                sched.kv_blocks_free,
2122                sched.kv_block_size,
2123                sched.kv_rejected_too_large,
2124                sched.kv_rejected_context_length,
2125                sched.aborted,
2126                sched.max_seqs,
2127                sched.prefill_chunk,
2128            )
2129        }
2130        None => body,
2131    };
2132
2133    (
2134        [(
2135            axum::http::header::CONTENT_TYPE,
2136            "text/plain; version=0.0.4",
2137        )],
2138        body,
2139    )
2140        .into_response()
2141}
2142
2143pub(crate) type ApiError = (StatusCode, Json<serde_json::Value>);
2144
2145/// A field the server understands but this value of which it cannot
2146/// serve. Distinct from [`unsupported_feature`] (501, "frink does not
2147/// implement this") -- a 400 says the request itself is wrong, which is
2148/// the difference between a client retrying elsewhere and a client
2149/// fixing its own body.
2150pub(crate) fn invalid_request(message: &str, param: &str) -> ApiError {
2151    (
2152        StatusCode::BAD_REQUEST,
2153        Json(serde_json::json!({"error": {
2154            "message": message,
2155            "type": "invalid_request_error",
2156            "param": param,
2157            "code": null,
2158        }})),
2159    )
2160}
2161
2162pub(crate) fn unsupported_feature(message: &str) -> ApiError {
2163    (
2164        StatusCode::NOT_IMPLEMENTED,
2165        Json(serde_json::json!({"error": {"message": message, "type": "unsupported"}})),
2166    )
2167}
2168
2169pub(crate) fn decode_error_response(e: generate::DecodeError) -> ApiError {
2170    let status = match e {
2171        generate::DecodeError::TokenOutOfVocab { .. } => StatusCode::BAD_REQUEST,
2172        // Well-formed, and this deployment cannot serve it: 501, the
2173        // same answer `crate::unimplemented_fields` gives a field this
2174        // server does not implement.
2175        generate::DecodeError::Unsupported(_) => StatusCode::NOT_IMPLEMENTED,
2176        // The request is bigger than the server can ever serve. That
2177        // is a property of the request, so it is the client's 400 --
2178        // answering 503 would send it into a retry loop that cannot
2179        // succeed.
2180        generate::DecodeError::KvBudgetExceeded { .. } => StatusCode::BAD_REQUEST,
2181        // Not the client's fault, and true of the exact same request a
2182        // moment later once capacity frees up -- 503, not 400. The
2183        // `Retry-After` header these need is stamped centrally by
2184        // `limits::retry_after`; see that function for why it lives in a
2185        // layer rather than here.
2186        generate::DecodeError::KvPoolExhausted | generate::DecodeError::QueueFull { .. } => {
2187            StatusCode::SERVICE_UNAVAILABLE
2188        }
2189        // The caller's grammar against this model's vocabulary, and
2190        // nothing about the server's load: the same body fails the same
2191        // way on an idle box, so 400 rather than 503.
2192        generate::DecodeError::GrammarConstraint { .. } => StatusCode::BAD_REQUEST,
2193        // Meant to be unreachable -- the route refuses the family with
2194        // a 501 before rendering -- and a 500 when it is not, because
2195        // then it is this server's decode path that skipped a seam.
2196        generate::DecodeError::ReasoningBudget { .. } => StatusCode::INTERNAL_SERVER_ERROR,
2197    };
2198    tracing::warn!("decode error: {e}");
2199    let mut body = serde_json::json!({"error": {"message": e.to_string()}});
2200    // A refusal against a ceiling names the ceiling and both sides of
2201    // the arithmetic. "Out of memory" (or a bare 400) tells a caller
2202    // that something did not fit; it does not tell them whether to
2203    // shorten the prompt or to run a bigger box, and those are the only
2204    // two actions available.
2205    if let generate::DecodeError::KvBudgetExceeded {
2206        binding,
2207        estimated_bytes,
2208        limit_bytes,
2209        positions,
2210        positions_limit,
2211        ..
2212    } = &e
2213    {
2214        body["error"]["type"] = serde_json::json!("invalid_request_error");
2215        body["error"]["code"] = serde_json::json!(binding);
2216        body["error"]["binding"] = serde_json::json!(binding);
2217        body["error"]["estimated_bytes"] = serde_json::json!(estimated_bytes);
2218        body["error"]["limit_bytes"] = serde_json::json!(limit_bytes);
2219        body["error"]["positions"] = serde_json::json!(positions);
2220        body["error"]["positions_limit"] = serde_json::json!(positions_limit);
2221    }
2222    // The header carries the same hint (stamped by `limits::retry_after`);
2223    // repeating it in the body is for clients that read JSON and never
2224    // look at headers, which is most of them.
2225    if let Some(secs) = e.retry_after_secs() {
2226        body["error"]["retry_after_seconds"] = serde_json::json!(secs);
2227    }
2228    (status, Json(body))
2229}
2230
2231pub(crate) fn join_error_response(e: tokio::task::JoinError) -> ApiError {
2232    tracing::error!("generation task panicked: {e}");
2233    (
2234        StatusCode::INTERNAL_SERVER_ERROR,
2235        Json(serde_json::json!({"error": {"message": "internal error during generation"}})),
2236    )
2237}
2238
2239/// Runs generation for `params` against `model`, calling `emit` for each
2240/// decoded text chunk. Returns finish reason, usage, and the concatenated
2241/// text (for sessions / tool-call detection). Pure CPU-bound work with
2242/// no I/O and no shared lock: safe to run on `spawn_blocking`.
2243#[allow(clippy::too_many_arguments)] // one clear parameter per concern:
2244                                     // model + prompt + params, then the three optional shared
2245                                     // facilities (KV pool, prefix cache, batcher), the context
2246                                     // ceiling, and the sink. Bundling them would only move the
2247                                     // same list behind a struct at two call sites.
2248fn run_generation_emit(
2249    model: &Model,
2250    prompt: &str,
2251    params: &GenerationParams,
2252    kv_pool: Option<&generate::KvPoolConfig>,
2253    paged_kv: Option<&generate::PagedKvConfig>,
2254    prefix_cache: Option<&Mutex<PrefixCache>>,
2255    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2256    ceiling: Option<&budget::ContextCeiling>,
2257    metal_private_decode_gate: Option<&std::sync::Mutex<()>>,
2258    // Takes the CHOICE INDEX with the text. A streaming `n` interleaves
2259    // the choices a token at a time (`crate::round_robin`), so a piece
2260    // of text that did not say which completion it belongs to could not
2261    // be put on the wire at all.
2262    mut emit: impl FnMut(usize, &str),
2263) -> Result<generate::Generated, generate::DecodeError> {
2264    let synthetic = model.is_synthetic();
2265    // Held for the whole generation: a `POST /lora-adapters`, or a
2266    // request whose `lora` field overrides the scales, waits for this
2267    // one to finish rather than changing the weights under it. See
2268    // `crate::lora`.
2269    let _lora_lease = lora::lease(model, params.lora.as_deref());
2270    let mut chunks: Vec<Vec<String>> = vec![Vec::new(); params.n.max(1)];
2271    // Layer 1 of the stop machinery is resolved exactly here, because
2272    // this is the one place that has both the request's stop strings
2273    // and the model's tokenizer. Both the batched and the private
2274    // decode paths below read the result off the params, so there is
2275    // one answer rather than two that can drift.
2276    let params = &{
2277        let mut resolved = params.clone();
2278        resolved.stop_token_ids = crate::stop::resolve_stop_tokens(&resolved.stop, |text| {
2279            model.encode(text, SpecialTokens::Parse)
2280        });
2281        // `bad_words` are STRINGS on the wire and TOKENS at the
2282        // sampler, and this is the one layer that has both the request
2283        // and the model's tokenizer. Same seam, same reason, as the
2284        // two lines above.
2285        resolved
2286            .token_mask
2287            .resolve(|text| model.encode(text, SpecialTokens::Parse));
2288        // The reasoning budget's markers, for the same reason and at
2289        // the same seam: `<think>` is a token id only to this model,
2290        // and whether the prompt already opened the block is a fact
2291        // about the rendered prompt, which this is the last place to
2292        // hold beside the tokenizer.
2293        resolved.reasoning_budget = resolved
2294            .reasoning_budget
2295            .armed(resolved.reasoning, prompt, |text| {
2296                model.encode(text, SpecialTokens::Parse)
2297            })
2298            .map_err(|detail| generate::DecodeError::ReasoningBudget { detail })?;
2299        resolved
2300    };
2301    let used_batcher = matches!((model, continuous_batcher), (Model::Gguf(_), Some(_)));
2302    let _metal_private_guard =
2303        acquire_metal_private_decode_gate(metal_private_decode_gate, used_batcher);
2304    let (finishes, prompt_rows, prompt_ids, truncated_prompt, usage) = match model {
2305        Model::Gguf(m) => {
2306            if let Some(batcher) = continuous_batcher {
2307                let mut tokens = m.tokenizer.encode(prompt, SpecialTokens::Parse);
2308                frink_models::tokenizer::prepend_bos(&mut tokens, m.bos_id);
2309                let (finish, _generated_ids, text, usage) = if synthetic {
2310                    batcher.generate(tokens, params.clone(), m.stop_tokens.clone())?
2311                } else {
2312                    batcher.generate_streaming(
2313                        tokens,
2314                        params.clone(),
2315                        m.stop_tokens.clone(),
2316                        Some(|chunk: &str| {
2317                            if !chunk.is_empty() {
2318                                chunks[0].push(chunk.to_string());
2319                                emit(0, chunk);
2320                            }
2321                        }),
2322                    )?
2323                };
2324                if !text.is_empty() && chunks[0].is_empty() {
2325                    chunks[0].push(text);
2326                }
2327                // One choice: the batch scheduler serves `n = 1` only,
2328                // and `crate::unimplemented_fields` refuses the rest on
2329                // the wire.
2330                // The batch scheduler serves one choice and publishes
2331                // no distributions; `wants_logprobs` is refused for a
2332                // batched request at the route.
2333                // No prompt rows: the batch scheduler serves one
2334                // choice and `prompt_logprobs` is refused for it at
2335                // the route.
2336                // The batch scheduler tokenizes its own prompt and
2337                // `truncate_prompt_tokens` is not wired through it, so
2338                // there is no truncation for `echo` to report.
2339                (
2340                    vec![(finish, Vec::new())],
2341                    Vec::new(),
2342                    Vec::new(),
2343                    None,
2344                    usage,
2345                )
2346            } else {
2347                generate::generate(
2348                    &m.decoder,
2349                    m.tokenizer.as_ref(),
2350                    &m.stop_tokens,
2351                    m.bos_id,
2352                    prompt,
2353                    params,
2354                    kv_pool,
2355                    paged_kv,
2356                    prefix_cache,
2357                    ceiling,
2358                    |choice, chunk| {
2359                        chunks[choice].push(chunk.to_string());
2360                        // Every choice streams, each saying which it
2361                        // is: a streamed `n` interleaves them a token
2362                        // at a time (`crate::round_robin`).
2363                        if !synthetic {
2364                            emit(choice, chunk);
2365                        }
2366                    },
2367                )?
2368            }
2369        }
2370        Model::Kimi(m) => generate::generate_engine(
2371            &m.engine,
2372            &m.tokenizer,
2373            &m.stop_tokens,
2374            None,
2375            prompt,
2376            params,
2377            |chunk| {
2378                chunks[0].push(chunk.to_string());
2379                if !synthetic {
2380                    emit(0, chunk);
2381                }
2382            },
2383        )?,
2384        Model::Mla(m) => generate::generate_engine(
2385            &m.engine,
2386            &m.tokenizer,
2387            &m.stop_tokens,
2388            m.bos_id,
2389            prompt,
2390            params,
2391            |chunk| {
2392                chunks[0].push(chunk.to_string());
2393                if !synthetic {
2394                    emit(0, chunk);
2395                }
2396            },
2397        )?,
2398        Model::Gemma4(m) => generate::generate_engine(
2399            &m.engine,
2400            &m.tokenizer,
2401            &m.stop_tokens,
2402            m.bos_id,
2403            prompt,
2404            params,
2405            |chunk| {
2406                chunks[0].push(chunk.to_string());
2407                if !synthetic {
2408                    emit(0, chunk);
2409                }
2410            },
2411        )?,
2412        Model::Glm52(m) => generate::generate_engine(
2413            &m.engine,
2414            &m.tokenizer,
2415            &m.stop_tokens,
2416            m.bos_id,
2417            prompt,
2418            params,
2419            |chunk| {
2420                chunks[0].push(chunk.to_string());
2421                if !synthetic {
2422                    emit(0, chunk);
2423                }
2424            },
2425        )?,
2426    };
2427
2428    let mut full = chunks[0].concat();
2429    if synthetic {
2430        full = format!(
2431            "[frink synthetic-weight demo: no real checkpoint loaded -- set FRINK_MODEL_PATH \
2432             to serve a real model. Decoded ids -> {full:?}]"
2433        );
2434        emit(0, &full);
2435    } else if used_batcher && !full.is_empty() && chunks[0].is_empty() {
2436        emit(0, &full);
2437    }
2438
2439    // One `(finish_reason, text)` per choice, choice 0 first. Zipped
2440    // rather than indexed so a mismatch between the two lists is a
2441    // short result rather than a panic -- and the assert says the two
2442    // must agree, because a choice with no finish reason is a bug and
2443    // not a shape.
2444    debug_assert_eq!(finishes.len(), chunks.len(), "one finish reason per choice");
2445    let mut out: Vec<generate::GeneratedChoice> = finishes
2446        .into_iter()
2447        .zip(chunks.into_iter().map(|c| c.concat()))
2448        .map(|((finish, logprobs), text)| generate::GeneratedChoice {
2449            finish,
2450            text,
2451            logprobs,
2452        })
2453        .collect();
2454    if let Some(first) = out.first_mut() {
2455        // The synthetic demo REPLACES the text with a banner, so the
2456        // token pieces the distributions were collected for no longer
2457        // concatenate to what is returned, and `text_offset` would
2458        // index a string that does not contain them. Dropped together
2459        // with the substitution, at the one site that makes it: an
2460        // offset into text the caller did not get is worse than no
2461        // offset.
2462        if synthetic {
2463            first.logprobs.clear();
2464        }
2465        first.text = full;
2466    }
2467    Ok(generate::Generated {
2468        choices: out,
2469        prompt_rows,
2470        prompt_ids,
2471        truncated_prompt,
2472        usage,
2473    })
2474}
2475
2476/// Collecting wrapper around [`run_generation_emit`] for non-streaming
2477/// paths and tests.
2478#[allow(clippy::too_many_arguments)] // mirrors `run_generation_emit`
2479                                     // exactly, minus the sink; see its note.
2480pub(crate) fn run_generation(
2481    model: &Model,
2482    prompt: &str,
2483    params: &GenerationParams,
2484    kv_pool: Option<&generate::KvPoolConfig>,
2485    paged_kv: Option<&generate::PagedKvConfig>,
2486    prefix_cache: Option<&Mutex<PrefixCache>>,
2487    continuous_batcher: Option<&serving::batch::ContinuousBatcher>,
2488    ceiling: Option<&budget::ContextCeiling>,
2489    metal_private_decode_gate: Option<&std::sync::Mutex<()>>,
2490    // One `(finish_reason, text)` per choice, choice 0 first. See
2491    // `run_generation_emit`.
2492) -> Result<generate::Generated, generate::DecodeError> {
2493    run_generation_emit(
2494        model,
2495        prompt,
2496        params,
2497        kv_pool,
2498        paged_kv,
2499        prefix_cache,
2500        continuous_batcher,
2501        ceiling,
2502        metal_private_decode_gate,
2503        |_, _| {},
2504    )
2505}
2506
2507/// Render a conversation into the prompt the served checkpoint expects.
2508///
2509/// Who describes the tools depends on the template: one that reads
2510/// `tools` is handed them structurally and owns the whole grammar, and
2511/// one that does not gets [`tool_preamble`] as an extra leading system
2512/// turn -- this server's original answer, and still the only one
2513/// available for a checkpoint whose template never mentions tools.
2514///
2515/// `extra` is the request's already-sanitized `chat_template_kwargs`
2516/// (see [`resolve_template_kwargs`]).
2517pub(crate) fn prompt_from_messages(
2518    messages: &[ChatMessage],
2519    template: &chat_template::PromptTemplate,
2520    tools: &[ToolDef],
2521    extra: serde_json::Map<String, serde_json::Value>,
2522) -> Result<String, ApiError> {
2523    let rendered = if tools.is_empty() || template.handles_tools() {
2524        template.render(messages, tools, extra)
2525    } else {
2526        let mut with_preamble = Vec::with_capacity(messages.len() + 1);
2527        with_preamble.push(ChatMessage {
2528            role: "system".to_string(),
2529            content: Some(MessageContent::Text(tool_preamble(tools))),
2530            tool_calls: None,
2531            tool_call_id: None,
2532            reasoning_content: None,
2533        });
2534        with_preamble.extend_from_slice(messages);
2535        template.render(&with_preamble, &[], extra)
2536    };
2537    rendered.map_err(template_error_response)
2538}
2539
2540/// A template that will not render is a request failure, never a
2541/// fallback to a guessed one: serving a checkpoint framing it has never
2542/// seen is the exact bug `chat_template` exists to delete, so the
2543/// compiler's own message goes back to the caller instead.
2544fn template_error_response(err: frink_models::chat_template::TemplateError) -> ApiError {
2545    (
2546        StatusCode::BAD_REQUEST,
2547        Json(serde_json::json!({
2548            "error": {
2549                "message": format!("chat template failed to render: {err}"),
2550                "type": "invalid_request_error",
2551                "param": "messages",
2552                "code": null,
2553            }
2554        })),
2555    )
2556}
2557
2558/// Real, disclosed approach for tool-calling without grammar-
2559/// constrained decoding (which doesn't exist in this server):
2560/// describe each tool in plain text and ask the
2561/// model to wrap a call in a literal `<tool_call>{...}</tool_call>`
2562/// marker, then reuse the existing stop-sequence machinery (see
2563/// `ChatCompletionRequest::effective_stop_sequences`) to end
2564/// generation right after it, and parse the captured text for that
2565/// marker afterward (`output::parse_output`, which also accepts the
2566/// format the served checkpoint's own family emits). This is
2567/// stop-bounded,
2568/// prompt-engineered JSON extraction, not enforced-valid-JSON output --
2569/// a real limitation, not overclaimed.
2570fn tool_preamble(tools: &[ToolDef]) -> String {
2571    let mut out = String::from(
2572        "You can call tools to help answer the user. To call a tool, respond with \
2573         EXACTLY one line in this format and nothing else:\n\
2574         <tool_call>{\"name\": \"<tool name>\", \"arguments\": {<arguments as a JSON \
2575         object matching that tool's parameters>}}</tool_call>\n\n\
2576         Available tools:\n",
2577    );
2578    for t in tools {
2579        out.push_str(&format!(
2580            "- {}: {}\n  parameters (JSON schema): {}\n",
2581            t.function.name,
2582            t.function.description.as_deref().unwrap_or(""),
2583            t.function
2584                .parameters
2585                .as_ref()
2586                .map(|v| v.to_string())
2587                .unwrap_or_else(|| "{}".to_string()),
2588        ));
2589    }
2590    out
2591}
2592
2593/// Fold one batch of parser events into the text to stream and the
2594/// tool-call deltas to stream beside it.
2595///
2596/// `opened` counts calls that have gone out, which is both the wire
2597/// `index` and how the terminal chunk knows whether this generation
2598/// ended in a tool call. `CallEnd` deliberately emits nothing: every
2599/// byte of the arguments has already gone out as a fragment, and
2600/// repeating them would make a client that concatenates deltas produce
2601/// the arguments twice.
2602fn tool_call_deltas(
2603    events: Vec<crate::policy::parser::ToolCallEvent>,
2604    opened: &std::cell::Cell<usize>,
2605) -> (String, Vec<ToolCallDelta>) {
2606    let mut text = String::new();
2607    let mut deltas = Vec::new();
2608    for event in events {
2609        match event {
2610            crate::policy::parser::ToolCallEvent::Text(chunk) => text.push_str(&chunk),
2611            crate::policy::parser::ToolCallEvent::CallStart { index, name } => {
2612                opened.set(opened.get().max(index + 1));
2613                deltas.push(ToolCallDelta::opening(index, name));
2614            }
2615            crate::policy::parser::ToolCallEvent::CallArguments { index, fragment } => {
2616                if !fragment.is_empty() {
2617                    deltas.push(ToolCallDelta::arguments(index, fragment));
2618                }
2619            }
2620            crate::policy::parser::ToolCallEvent::CallEnd { .. } => {}
2621        }
2622    }
2623    (text, deltas)
2624}
2625
2626/// Builds the final response message + finish reason from raw
2627/// generated text.
2628///
2629/// Three things come out of the text: a reasoning block, when the
2630/// served checkpoint's family emits one; every tool call it made, in
2631/// whichever format it used; and whatever prose is left. `base_finish`
2632/// is promoted to `"tool_calls"` only when a call was actually found --
2633/// a model can answer in plain text despite tools being offered, and
2634/// that must fall through to an ordinary text response rather than an
2635/// error.
2636fn build_response_message(
2637    text: String,
2638    tools: &[ToolDef],
2639    posture: output::OutputPosture,
2640    base_finish: &'static str,
2641) -> (ChatCompletionResponseMessage, &'static str) {
2642    let parsed = output::parse_output(&text, tools, posture);
2643    let calls: Vec<ToolCallOut> = parsed
2644        .calls
2645        .into_iter()
2646        .enumerate()
2647        .map(|(index, call)| ToolCallOut {
2648            id: format!("call_{index}"),
2649            kind: "function",
2650            function: ToolCallFunctionOut {
2651                name: call.name,
2652                arguments: call.arguments,
2653            },
2654        })
2655        .collect();
2656    if !calls.is_empty() {
2657        return (
2658            ChatCompletionResponseMessage {
2659                role: "assistant",
2660                content: None,
2661                reasoning_content: parsed.reasoning,
2662                tool_calls: Some(calls),
2663            },
2664            "tool_calls",
2665        );
2666    }
2667    (
2668        ChatCompletionResponseMessage {
2669            role: "assistant",
2670            content: Some(parsed.content),
2671            reasoning_content: parsed.reasoning,
2672            tool_calls: None,
2673        },
2674        base_finish,
2675    )
2676}
2677
2678/// Resolves the full message history a prompt should be rendered
2679/// from: `req.messages` verbatim when no session is in play, or (see
2680/// `session` module) `req.messages` appended to `session_id`'s stored
2681/// history, returning the accumulated whole.
2682fn resolve_history(state: &AppState, req: &ChatCompletionRequest) -> Vec<ChatMessage> {
2683    let mut history = match &req.session_id {
2684        Some(id) => state.sessions.extend_and_get(id, &req.messages),
2685        None => req.messages.clone(),
2686    };
2687    if req.json_object_mode() {
2688        inject_json_object_system_hint(&mut history);
2689    }
2690    history
2691}
2692
2693fn inject_json_object_system_hint(messages: &mut Vec<ChatMessage>) {
2694    const HINT: &str =
2695        "You must respond with valid JSON only (a single JSON object, no markdown fences).";
2696    if let Some(sys) = messages.iter_mut().find(|m| m.role == "system") {
2697        match &mut sys.content {
2698            Some(MessageContent::Text(s)) if !s.contains("JSON") => {
2699                s.push_str("\n\n");
2700                s.push_str(HINT);
2701            }
2702            None => {
2703                sys.content = Some(MessageContent::Text(HINT.to_string()));
2704            }
2705            _ => {}
2706        }
2707    } else {
2708        messages.insert(
2709            0,
2710            ChatMessage {
2711                role: "system".to_string(),
2712                content: Some(MessageContent::Text(HINT.to_string())),
2713                tool_calls: None,
2714                tool_call_id: None,
2715                reasoning_content: None,
2716            },
2717        );
2718    }
2719}
2720
2721async fn chat_completions(
2722    State(state): State<Arc<AppState>>,
2723    headers: axum::http::HeaderMap,
2724    Json(req): Json<ChatCompletionRequest>,
2725) -> Response {
2726    let attribution = attribution::Attribution::from_headers(&headers);
2727    state
2728        .requests_total
2729        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2730    let started = std::time::Instant::now();
2731
2732    // One id per request, assigned before any work starts -- including
2733    // before validation -- so the streaming and non-streaming paths
2734    // agree and a rejected request is still nameable in the monitor.
2735    let request_id = frink_api::next_request_id();
2736    let stream = req.stream.unwrap_or(false);
2737
2738    // The maintenance gate comes before validation: while the cache is
2739    // being resized or the server is draining, the honest answer is
2740    // "not now" whichever fields the body carries, and admitting a
2741    // request into a pool that is being rebuilt under it is worse than
2742    // refusing one that would have 400'd anyway.
2743    let refusal = cache_admin::check_admission(&state)
2744        .err()
2745        .or_else(|| req.validate_supported_fields().err());
2746    if let Some(err) = refusal {
2747        state
2748            .request_errors_total
2749            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2750        let response = err.into_response();
2751        state.record_request(stats::Record {
2752            request_id: &request_id,
2753            route: frink_api::routes::V1_CHAT_COMPLETIONS,
2754            model: state.active_model_name(),
2755            status: response.status().as_u16(),
2756            stream,
2757            duration_ms: started.elapsed().as_millis() as u64,
2758            usage: None,
2759            attribution: &attribution,
2760        });
2761        return response;
2762    }
2763
2764    let response = if stream {
2765        chat_completions_stream(
2766            Arc::clone(&state),
2767            req,
2768            request_id.clone(),
2769            started,
2770            attribution.clone(),
2771        )
2772        .await
2773        .into_response()
2774    } else {
2775        chat_completions_full(
2776            Arc::clone(&state),
2777            req,
2778            request_id.clone(),
2779            started,
2780            attribution.clone(),
2781        )
2782        .await
2783        .into_response()
2784    };
2785
2786    if response.status().is_client_error() || response.status().is_server_error() {
2787        state
2788            .request_errors_total
2789            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2790        // Only failures are recorded here. A success has already
2791        // recorded itself from the path that knows the token counts --
2792        // and, for a stream, that has not even happened yet.
2793        state.record_request(stats::Record {
2794            request_id: &request_id,
2795            route: frink_api::routes::V1_CHAT_COMPLETIONS,
2796            // `None` here is the 503 case and says so: nothing was
2797            // loaded, so nothing served it.
2798            model: state.active_model_name(),
2799            status: response.status().as_u16(),
2800            stream,
2801            duration_ms: started.elapsed().as_millis() as u64,
2802            usage: None,
2803            attribution: &attribution,
2804        });
2805    }
2806    state.mark_request_finished();
2807
2808    response
2809}
2810
2811async fn chat_completions_full(
2812    state: Arc<AppState>,
2813    req: ChatCompletionRequest,
2814    request_id: String,
2815    started: std::time::Instant,
2816    attribution: attribution::Attribution,
2817) -> Result<Json<ChatCompletionResponse>, ApiError> {
2818    let tools_active = req.tools_active();
2819    // Cloned once, up front: this request decodes against exactly this
2820    // model even if `/admin/models/load` swaps a different one in
2821    // halfway through (see `AppState::active`).
2822    let active = state.require_active()?;
2823    let history = resolve_history(&state, &req);
2824    let template = active.generative()?.chat_template();
2825    let kwargs = req.resolve_template_kwargs(&template);
2826    let prompt = req.render_prompt(&history, &template, &req.tools, kwargs, active.name())?;
2827    // Resolved BEFORE the lookup, because the constraint is part of the
2828    // key: a grammar, JSON mode and `ignore_eos` all change the answer
2829    // and none of them changes the prompt, so a cache consulted first
2830    // would answer a constrained request with an unconstrained
2831    // completion (#35). It also means an unparseable grammar is a 400
2832    // for the second caller too, rather than a 200 carrying prose
2833    // generated under no grammar at all.
2834    let mut params =
2835        req.generation_params_for_template(&template, active.name(), active.sampler_model())?;
2836    params.lora = lora::resolve_request(active.generative()?, req.lora.as_deref())?;
2837    let key = req.is_cacheable().then(|| req.cache_key(&prompt, &params));
2838
2839    // Per choice, alongside `completion`: a cache HIT carries none,
2840    // and cannot -- which is safe only because a request that asked
2841    // for logprobs is uncacheable (`is_cacheable`).
2842    let mut generated_logprobs: Vec<crate::sampling_loop::PerTokenProbs> = Vec::new();
2843    // Parsed before the generation so a bad `top_logprobs` is a 400
2844    // rather than a wasted decode.
2845    let n_logprobs = req.n_logprobs()?;
2846    // The same detokenizer `/v1/detokenize` answers with.
2847    let decode_piece = |id: usize| active.decode_any(&[id]);
2848    let (completion, cache_status) = if let Some(cached) = key
2849        .as_ref()
2850        .and_then(|key| lock_cache(&state.response_cache).get(key))
2851    {
2852        tracing::debug!("cache hit for key {}", key.as_ref().unwrap().digest());
2853        (cached, "hit")
2854    } else {
2855        let produced = decode_task::buffered(
2856            decode_task::DecodeHandles::take(&state, &active)?,
2857            prompt.clone(),
2858            params,
2859        )
2860        .await?;
2861        let usage = produced.usage;
2862        let choices = produced.choices;
2863
2864        // The distributions do not go into the cache (see
2865        // `CachedCompletion`) and do not need to: a request that asked
2866        // for them is uncacheable, so this branch only ever stores
2867        // entries nobody will ask logprobs of.
2868        generated_logprobs = choices.iter().map(|c| c.logprobs.clone()).collect();
2869        let completion = response_cache::CachedCompletion {
2870            choices: choices.into_iter().map(|c| (c.finish, c.text)).collect(),
2871            usage,
2872        };
2873        // A cacheable KEY is not on its own permission to store an
2874        // answer: `cacheable` refuses a generation that did not run to
2875        // its own end, and is the only way to build the value `put`
2876        // takes, so a cancelled partial cannot become the cached answer
2877        // for the next caller (#57).
2878        let cache_status = match key {
2879            // Nothing is cloned unless there is a key to store it
2880            // under: the common path here is a sampled request, which
2881            // has none.
2882            Some(key) => match completion.clone().cacheable() {
2883                Some(cacheable) => {
2884                    tracing::debug!("cache miss for key {}", key.digest());
2885                    lock_cache(&state.response_cache).put(key, cacheable);
2886                    "miss"
2887                }
2888                None => "skip",
2889            },
2890            None => "skip",
2891        };
2892        (completion, cache_status)
2893    };
2894    // Choice 0's text is what a session stores and what JSON mode
2895    // validates: both describe one reply.
2896    let content = completion.first_text().to_string();
2897
2898    if req.json_object_mode() {
2899        json_mode::validate_json_object_output(&content)?;
2900    }
2901
2902    // Stored regardless of cache hit/miss, so a session's history is
2903    // always consistent with what a client would see, whether or not
2904    // this exact prompt happened to be served from cache.
2905    if let Some(id) = &req.session_id {
2906        state.sessions.store_reply(
2907            id,
2908            ChatMessage {
2909                role: "assistant".to_string(),
2910                content: Some(MessageContent::Text(content.clone())),
2911                tool_calls: None,
2912                tool_call_id: None,
2913                reasoning_content: None,
2914            },
2915        );
2916    }
2917
2918    // One `choices[]` entry per generated choice, each parsed for tool
2919    // calls and reasoning in its own right: a tool call in choice 2 is
2920    // a tool call, and reading only choice 0 would return the others
2921    // as raw marker text.
2922    let posture = output::OutputPosture::resolve_full(
2923        active.reasoning_format(),
2924        active.tool_call_format(),
2925        &prompt,
2926    );
2927    let tools: &[_] = if tools_active { &req.tools } else { &[] };
2928    // The winners when `best_of` generated more than were asked back.
2929    // Scored on the DISTRIBUTIONS, which is why `wants_logprobs` is on
2930    // whenever `best_of` ranks even if the caller never sees them.
2931    let wanted = req.unimplemented.n.unwrap_or(1).max(1) as usize;
2932    let ranked: Vec<(generate::FinishReason, String)> = if completion.choices.len() > wanted {
2933        let scored: Vec<crate::generate::GeneratedChoice> = completion
2934            .choices
2935            .into_iter()
2936            .zip(
2937                generated_logprobs
2938                    .iter()
2939                    .cloned()
2940                    .chain(std::iter::repeat(Vec::new())),
2941            )
2942            .map(
2943                |((finish, text), logprobs)| crate::generate::GeneratedChoice {
2944                    finish,
2945                    text,
2946                    logprobs,
2947                },
2948            )
2949            .collect();
2950        let best = crate::best_of::take_best(scored, wanted);
2951        generated_logprobs = best.iter().map(|c| c.logprobs.clone()).collect();
2952        best.into_iter().map(|c| (c.finish, c.text)).collect()
2953    } else {
2954        completion.choices
2955    };
2956    let rendered: Vec<ChatCompletionChoice> = ranked
2957        .into_iter()
2958        .enumerate()
2959        .map(|(index, (finish, text))| {
2960            let (message, finish_reason) =
2961                build_response_message(text, tools, posture, finish.as_str());
2962            ChatCompletionChoice {
2963                index,
2964                message,
2965                finish_reason,
2966                logprobs: n_logprobs.map(|k| {
2967                    crate::logprobs::render_chat(
2968                        generated_logprobs.get(index).unwrap_or(&Vec::new()),
2969                        Some(k),
2970                        &decode_piece,
2971                    )
2972                }),
2973            }
2974        })
2975        .collect();
2976
2977    state.record_request(stats::Record {
2978        request_id: &request_id,
2979        route: frink_api::routes::V1_CHAT_COMPLETIONS,
2980        // The handle this request decoded against, not `req.model`: a
2981        // swap mid-flight does not change which weights answered.
2982        model: Some(active.name().to_string()),
2983        status: 200,
2984        stream: false,
2985        duration_ms: started.elapsed().as_millis() as u64,
2986        usage: Some(&completion.usage),
2987        attribution: &attribution,
2988    });
2989
2990    Ok(Json(ChatCompletionResponse {
2991        id: request_id.clone(),
2992        request_id,
2993        object: "chat.completion",
2994        model: req.model,
2995        choices: rendered,
2996        usage: completion.usage,
2997        frink_cache: cache_status,
2998    }))
2999}
3000
3001async fn chat_completions_stream(
3002    state: Arc<AppState>,
3003    req: ChatCompletionRequest,
3004    request_id: String,
3005    started: std::time::Instant,
3006    attribution: attribution::Attribution,
3007) -> Result<Response, ApiError> {
3008    // Streaming requests are never served from or written to the response cache.
3009    //
3010    // And they serve one choice. Emitting choice 0 to its end and then
3011    // choice 1 is not what a client reading `choices[].index` expects,
3012    // and interleaving them round-robin needs a sampler that can be
3013    // stepped one token at a time per choice
3014    // (`docs/plans/several-completions-per-request.md`). Refused by
3015    // name rather than silently collapsed to one, which is the whole
3016    // argument of `crate::unimplemented_fields`.
3017    let tools_active = req.tools_active();
3018    // See `chat_completions_full`: the handle is taken once and the
3019    // whole stream runs against it, so a mid-stream model swap cannot
3020    // splice two checkpoints into one completion.
3021    let active = state.require_active()?;
3022    let history = resolve_history(&state, &req);
3023    let template = active.generative()?.chat_template();
3024    let kwargs = req.resolve_template_kwargs(&template);
3025    let prompt = req.render_prompt(&history, &template, &req.tools, kwargs, active.name())?;
3026    let model_name = req.model.clone();
3027    let session_id = req.session_id.clone();
3028    let sessions = state.sessions.clone();
3029
3030    let model = Arc::clone(active.generative()?);
3031    let kv_pool = state.kv_pool.clone();
3032    let paged_kv = state.paged_kv.clone();
3033    let prefix_cache = state.prefix_cache.clone();
3034    let batcher = active.batcher.clone();
3035    let ceiling = active.ceiling.clone();
3036    let metal_private_decode_gate = state.metal_private_decode_gate.clone();
3037    let mut params =
3038        req.generation_params_for_template(&template, active.name(), active.sampler_model())?;
3039    params.lora = lora::resolve_request(active.generative()?, req.lora.as_deref())?;
3040    // A client reading `choices[].index` asked for the choices
3041    // together, so they are decoded a token at a time rather than one
3042    // completion after another (`crate::round_robin`). Set HERE and
3043    // nowhere else: a buffered request collects in an order nobody can
3044    // observe, and the interleaved schedule costs it the drafter.
3045    params.interleave_choices = params.n > 1;
3046    let stats_state = Arc::clone(&state);
3047    // Read now, off the handle this stream will decode against. Read
3048    // later it would name whatever a swap had made current by then.
3049    let served_model = active.name().to_string();
3050    // How to read this stream, fixed before the first token: the family
3051    // from the served checkpoint, and whether the prompt that was
3052    // actually rendered left the model inside a reasoning block.
3053    let posture = output::OutputPosture::resolve_full(
3054        active.reasoning_format(),
3055        active.tool_call_format(),
3056        &prompt,
3057    );
3058    // The offered tools, captured for the terminal parse: the request
3059    // itself does not outlive the closure that consumes it.
3060    let offered_tools: Vec<ToolDef> = if tools_active {
3061        req.tools.clone()
3062    } else {
3063        Vec::new()
3064    };
3065
3066    // Tier two of cancellation: the id is already on the wire, so the
3067    // client can name it. The guard rides with the generation task and
3068    // deregisters however that task ends, panic included -- see the
3069    // `cancel` module.
3070    let (cancel_token, cancel_guard) = state.cancels.register(&request_id);
3071    params.cancel = Some(cancel_token.clone());
3072
3073    // Tool-call detection needs the full stop-bounded text; continuous
3074    // batching returns one string. Both stay buffered. Otherwise each
3075    // decoded chunk is pushed on a channel for overlapped SSE delivery.
3076    // Incremental streaming, including when tools are offered. It used
3077    // to be `!tools_active && ...`: finding a tool call needed the
3078    // whole text. `crate::policy::parser::ToolCallParser` streams prefix-stable
3079    // argument fragments, so that reason is gone, and a coding agent
3080    // now watches an argument arrive instead of waiting for it.
3081    let overlap = true;
3082
3083    // Opt-in replay. Registering a buffer is also what decides whether a
3084    // dropped socket cancels this generation -- see `resume`'s module
3085    // doc for why that is the caller's call and not the server's.
3086    let slot = req
3087        .stream_resumable
3088        .unwrap_or(false)
3089        .then(|| state.streams.register(&request_id));
3090    let emitter = resume::Emitter::new(slot);
3091
3092    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);
3093    // Built here, where the id and model name are still owned by this
3094    // frame: the generation task takes both. Serialized once, because
3095    // it is byte-identical every time it goes out.
3096    let keepalive = sse::keepalive_event(&ChatCompletionChunk {
3097        id: request_id.clone(),
3098        request_id: None,
3099        object: "chat.completion.chunk",
3100        model: model_name.clone(),
3101        choices: vec![ChatCompletionChunkChoice {
3102            index: 0,
3103            delta: ChatCompletionChunkDelta {
3104                role: None,
3105                content: None,
3106                reasoning_content: None,
3107                tool_calls: None,
3108            },
3109            finish_reason: None,
3110        }],
3111        usage: None,
3112    });
3113
3114    tokio::task::spawn_blocking(move || {
3115        // Held for the whole generation; dropping it is what takes the
3116        // id back out of the cancel registry.
3117        let _cancel_guard = cancel_guard;
3118        let tx_chunks = tx.clone();
3119        // The orphan deadline (see `crate::sse`): a client that is
3120        // neither reading nor disconnected must not park this blocking
3121        // thread -- and the model handle and cancel guard it holds --
3122        // for the life of the process.
3123        let orphan_timeout = sse::orphan_timeout_from_env();
3124        let head_request_id = request_id.clone();
3125        // Whether the request id has gone out yet. It names the
3126        // REQUEST, so it rides the first chunk of the whole stream
3127        // rather than the first chunk of each choice.
3128        let announced = std::cell::Cell::new(false);
3129        // One parser set per choice. A streamed `n` interleaves the
3130        // choices a token at a time (`crate::round_robin`), so the
3131        // reasoning split, the tool parser and the opened-call count
3132        // are per COMPLETION rather than per request: two choices can
3133        // be mid-marker in different places.
3134        let emitters: Rc<RefCell<Vec<crate::chat_stream_choice::ChoiceEmitter>>> =
3135            Rc::new(RefCell::new(
3136                (0..params.n.max(1))
3137                    .map(|_| {
3138                        crate::chat_stream_choice::ChoiceEmitter::new(
3139                            posture.reasoning_parser(),
3140                            tools_active.then(|| posture.tool_call_parser(&offered_tools)),
3141                        )
3142                    })
3143                    .collect(),
3144            ));
3145        let emit_choices = Rc::clone(&emitters);
3146        let result = run_generation_emit(
3147            &model,
3148            &prompt,
3149            &params,
3150            kv_pool.as_ref(),
3151            paged_kv.as_ref(),
3152            prefix_cache.as_deref(),
3153            batcher.as_ref(),
3154            ceiling.as_deref(),
3155            metal_private_decode_gate.as_deref(),
3156            |choice, chunk| {
3157                if !overlap || chunk.is_empty() {
3158                    return;
3159                }
3160                let mut held = emit_choices.borrow_mut();
3161                let Some(emitter_state) = held.get_mut(choice) else {
3162                    return;
3163                };
3164                let delta = emitter_state.push(chunk);
3165                if delta.is_empty() {
3166                    return;
3167                }
3168                // The request id rides the first chunk of the whole
3169                // STREAM, not of each choice: it names the request.
3170                let request_id = (!announced.get()).then(|| {
3171                    announced.set(true);
3172                    head_request_id.clone()
3173                });
3174                let wire = delta.into_choice(choice, emitter_state.start());
3175                drop(held);
3176                let payload = ChatCompletionChunk {
3177                    id: head_request_id.clone(),
3178                    request_id,
3179                    object: "chat.completion.chunk",
3180                    model: model_name.clone(),
3181                    choices: vec![wire],
3182                    usage: None,
3183                };
3184                // Tier one of cancellation. A failed send means the SSE
3185                // receiver is gone -- the browser tab closed, the
3186                // client aborted, the connection dropped -- and until
3187                // this was checked the return value was discarded and
3188                // the decode loop happily generated the remaining
3189                // hundreds of tokens into nothing. Flipping the same
3190                // flag `/v1/cancel` sets means there is one stop path,
3191                // not two.
3192                if let Err(why) =
3193                    sse::send_or_orphan(&tx_chunks, Ok(emitter.event(&payload)), orphan_timeout)
3194                {
3195                    if why == sse::SendFailure::Orphaned {
3196                        tracing::warn!(
3197                            "SSE stream {head_request_id} accepted nothing for the orphan \
3198                             deadline; treating it as abandoned"
3199                        );
3200                    }
3201                    // Two features met here and only one of them may
3202                    // win. The orphan deadline exists to stop work
3203                    // nobody is reading. A resumable stream is exactly
3204                    // the case where a gone receiver must NOT stop the
3205                    // work: the client said it may come back, the
3206                    // buffer is still being filled for it, and
3207                    // cancelling would make every reconnect resume into
3208                    // a truncated answer. So the deadline still detects
3209                    // and logs, and only a non-resumable stream is
3210                    // cancelled by it. `POST /v1/cancel` is the stop
3211                    // path for the resumable ones.
3212                    if !emitter.is_resumable() {
3213                        cancel_token.cancel();
3214                    }
3215                }
3216            },
3217        );
3218
3219        // Nothing may have been streamed from the emit closure (the
3220        // buffered tool-call/batching path, or an empty generation), so
3221        // the id may not have gone out yet. `take()` on the way into
3222        // each payload below guarantees it is announced exactly once,
3223        // on whichever chunk really is first.
3224        let mut pending_request_id = (!announced.get()).then(|| request_id.clone());
3225
3226        match result {
3227            Ok(generated) => {
3228                let usage = generated.usage;
3229                let produced: Vec<(generate::FinishReason, String)> = generated
3230                    .choices
3231                    .into_iter()
3232                    .map(|c| (c.finish, c.text))
3233                    .collect();
3234                assert!(
3235                    !produced.is_empty(),
3236                    "a generation produces at least one choice"
3237                );
3238                // The transcript keeps CHOICE 0. A server-side history
3239                // is one conversation, and appending four assistant
3240                // turns for one question would make the next request's
3241                // prompt a conversation that never happened.
3242                if let Some(id) = &session_id {
3243                    sessions.store_reply(
3244                        id,
3245                        ChatMessage {
3246                            role: "assistant".to_string(),
3247                            content: Some(MessageContent::Text(produced[0].1.clone())),
3248                            tool_calls: None,
3249                            tool_call_id: None,
3250                            reasoning_content: None,
3251                        },
3252                    );
3253                }
3254                for (index, (finish, full_text)) in produced.iter().enumerate() {
3255                    let (finish, full_text) = (finish.clone(), full_text.as_str());
3256                    // Both parsers may still be holding a run that could
3257                    // have become a marker and did not. It is ordinary
3258                    // output; dropping it would truncate every answer whose
3259                    // tail happens to look like the start of a `</think>`
3260                    // or a `<tool_call>`.
3261                    let mut streamed_finish: Option<&'static str> = None;
3262                    if overlap {
3263                        let (tail, first, opened) = {
3264                            let mut held = emitters.borrow_mut();
3265                            let state = &mut held[index];
3266                            let tail = state.flush();
3267                            (tail, state.start(), state.opened_calls())
3268                        };
3269                        if !tail.is_empty() {
3270                            let payload = ChatCompletionChunk {
3271                                id: request_id.clone(),
3272                                request_id: pending_request_id.take(),
3273                                object: "chat.completion.chunk",
3274                                model: model_name.clone(),
3275                                choices: vec![tail.into_choice(index, first)],
3276                                usage: None,
3277                            };
3278                            let _ = sse::send_or_orphan(
3279                                &tx,
3280                                Ok(emitter.event(&payload)),
3281                                orphan_timeout,
3282                            );
3283                        }
3284                        if opened > 0 {
3285                            streamed_finish = Some("tool_calls");
3286                        }
3287                    } else {
3288                        // The batched path had no incremental stream to
3289                        // ride on, so the whole answer goes out at once.
3290                        let parsed = output::parse_output(full_text, &offered_tools, posture);
3291                        let tool_calls: Vec<ToolCallDelta> = parsed
3292                            .calls
3293                            .iter()
3294                            .enumerate()
3295                            .map(|(index, call)| {
3296                                ToolCallDelta::whole(
3297                                    index,
3298                                    call.name.clone(),
3299                                    call.arguments.clone(),
3300                                )
3301                            })
3302                            .collect();
3303                        if !tool_calls.is_empty() {
3304                            streamed_finish = Some("tool_calls");
3305                        }
3306                        if !tool_calls.is_empty()
3307                            || !parsed.content.is_empty()
3308                            || parsed.reasoning.is_some()
3309                        {
3310                            let payload = ChatCompletionChunk {
3311                                id: request_id.clone(),
3312                                request_id: pending_request_id.take(),
3313                                object: "chat.completion.chunk",
3314                                model: model_name.clone(),
3315                                choices: vec![ChatCompletionChunkChoice {
3316                                    index,
3317                                    delta: ChatCompletionChunkDelta {
3318                                        role: Some("assistant"),
3319                                        content: (!parsed.content.is_empty()
3320                                            && tool_calls.is_empty())
3321                                        .then(|| parsed.content.clone()),
3322                                        reasoning_content: parsed.reasoning.clone(),
3323                                        tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3324                                    },
3325                                    finish_reason: None,
3326                                }],
3327                                usage: None,
3328                            };
3329                            let _ = sse::send_or_orphan(
3330                                &tx,
3331                                Ok(emitter.event(&payload)),
3332                                orphan_timeout,
3333                            );
3334                        }
3335                    }
3336                    // A truncated generation is `length` even if it managed
3337                    // to open a call: the client must not treat a
3338                    // half-written call as one it should execute.
3339                    let final_finish_reason = match streamed_finish {
3340                        Some(reason) if finish.as_str() != "length" => reason,
3341                        _ => finish.as_str(),
3342                    };
3343                    // The usage block rides the LAST choice's terminal
3344                    // chunk, because it is the request's total and there is
3345                    // exactly one of it.
3346                    let last = index + 1 == produced.len();
3347                    let final_payload = ChatCompletionChunk {
3348                        id: request_id.clone(),
3349                        request_id: pending_request_id.take(),
3350                        object: "chat.completion.chunk",
3351                        model: model_name.clone(),
3352                        choices: vec![ChatCompletionChunkChoice {
3353                            index,
3354                            delta: ChatCompletionChunkDelta {
3355                                role: None,
3356                                content: None,
3357                                reasoning_content: None,
3358                                tool_calls: None,
3359                            },
3360                            finish_reason: Some(final_finish_reason),
3361                        }],
3362                        usage: last.then(|| usage.clone()),
3363                    };
3364                    let _ =
3365                        sse::send_or_orphan(&tx, Ok(emitter.event(&final_payload)), orphan_timeout);
3366                }
3367                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3368                // Recorded here rather than where the handler returned:
3369                // the handler returns as soon as the SSE headers go out,
3370                // which is before a single token exists, so timing it
3371                // there would report every stream as instant.
3372                stats_state.record_request(stats::Record {
3373                    request_id: &request_id,
3374                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3375                    model: Some(served_model.clone()),
3376                    status: 200,
3377                    stream: true,
3378                    duration_ms: started.elapsed().as_millis() as u64,
3379                    usage: Some(&usage),
3380                    attribution: &attribution,
3381                });
3382            }
3383            Err(e) => {
3384                tracing::warn!("decode error on streamed request {request_id}: {e}");
3385                // The socket carried 200 -- SSE headers precede the
3386                // first token -- but the request produced no completion.
3387                // The monitor records outcomes, and a 200 row with zero
3388                // tokens would read as a successful empty answer, so the
3389                // failure is stated as 500 here and only here.
3390                stats_state.record_request(stats::Record {
3391                    request_id: &request_id,
3392                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3393                    model: Some(served_model.clone()),
3394                    status: 500,
3395                    stream: true,
3396                    duration_ms: started.elapsed().as_millis() as u64,
3397                    usage: None,
3398                    attribution: &attribution,
3399                });
3400                let payload = ChatCompletionChunk {
3401                    id: request_id.clone(),
3402                    request_id: pending_request_id.take(),
3403                    object: "chat.completion.chunk",
3404                    model: model_name,
3405                    choices: vec![ChatCompletionChunkChoice {
3406                        index: 0,
3407                        delta: ChatCompletionChunkDelta {
3408                            role: Some("assistant"),
3409                            content: Some(format!("[error: {e}]")),
3410                            reasoning_content: None,
3411                            tool_calls: None,
3412                        },
3413                        finish_reason: Some("stop"),
3414                    }],
3415                    usage: None,
3416                };
3417                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3418                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3419            }
3420        }
3421        // The buffer is closed by dropping `emitter` here -- including
3422        // on a panic, which is the case an explicit call would miss.
3423        // See `resume::Emitter`'s `Drop`.
3424        drop(emitter);
3425    });
3426
3427    let stream = sse::with_keepalive(rx, keepalive, sse::KEEPALIVE_INTERVAL);
3428    // `X-Accel-Buffering: no` is the one header that actually reaches
3429    // the problem the plan names: nginx (and the proxies that copied
3430    // its convention) buffer `text/event-stream` by default, which
3431    // turns a token-by-token stream into one silent wait followed by
3432    // the whole answer at once -- indistinguishable, from the browser,
3433    // from a hung backend. axum already sets `Cache-Control: no-cache`
3434    // on an `Sse` response, so that half is covered.
3435    //
3436    // The keepalive every 15s is the other half: it gives an
3437    // idle-but-healthy stream something to send, so a client's stall
3438    // timeout measures the *connection* rather than the model's
3439    // time-to-first-token on a long prompt.
3440    //
3441    // **Not `Sse::keep_alive`.** axum's keepalive is an SSE COMMENT,
3442    // and a comment does not reach a client's event handler -- codex's
3443    // 300s stream-idle timeout only resets on a data frame, so a
3444    // comment-kept stream is reconnected mid-answer on a long prefill.
3445    // `sse::with_keepalive` sends a real `chat.completion.chunk` with
3446    // an empty delta instead: a concatenating client adds nothing, and
3447    // the transport sees traffic. It also covers the silence BEFORE
3448    // the first token, which is exactly the queue-wait and long-prefill
3449    // window where this matters most.
3450    Ok((
3451        [(
3452            axum::http::HeaderName::from_static("x-accel-buffering"),
3453            axum::http::HeaderValue::from_static("no"),
3454        )],
3455        Sse::new(stream),
3456    )
3457        .into_response())
3458}
3459
3460/// The axum pattern for one of the published path templates.
3461///
3462/// `frink_api::routes` writes placeholders in the OpenAPI style
3463/// because it is imported by clients that have never heard of this
3464/// server's router; axum 0.7 wants `:name`. Converting here keeps one
3465/// published spelling and one router spelling, and the test below fails
3466/// if they ever stop describing the same path.
3467///
3468/// This rewrites EVERY `{name}` it finds rather than one known
3469/// placeholder. The narrow version took `{request_id}` only, so the two
3470/// Responses templates were mounted with their braces intact and axum
3471/// read `{response_id}` as a literal segment: `GET /v1/responses/abc`
3472/// matched no route and got axum's bodiless 404 instead of the
3473/// handler's, and the one path that did match would have panicked on
3474/// `MissingPathParams`. Anything with a placeholder must go through
3475/// here.
3476/// Every route that sits behind `FRINK_API_KEY`, as ONE list.
3477///
3478/// Extracted because there were two of these: this one and a
3479/// hand-written copy in the test module, which had already drifted --
3480/// the test router was missing `/metrics`, `/cache/stats`, both rerank
3481/// spellings and half of `/admin`, so an HTTP test could pass against a
3482/// route the real server does not serve, or 404 on one it does. That is
3483/// this repo's dominant bug shape (two structures that must agree, with
3484/// nothing enforcing it) sitting inside the test harness, where it is
3485/// worst: it makes the tests agree with themselves.
3486///
3487/// `/health` is deliberately NOT here. It is the one route that must
3488/// stay reachable without a key, and it is registered separately for
3489/// that reason.
3490fn protected_routes() -> Router<Arc<AppState>> {
3491    use frink_api::routes;
3492
3493    Router::new()
3494        .route(routes::V1_MODELS, get(list_models))
3495        // The Responses surface decodes tokens, so it sits behind the
3496        // same key as `/v1/chat/completions`: it must cost what
3497        // decoding tokens costs.
3498        .route(routes::V1_RESPONSES, post(responses::responses))
3499        .route(
3500            &axum_path(routes::V1_RESPONSE),
3501            get(responses::responses_get),
3502        )
3503        .route(
3504            &axum_path(routes::V1_RESPONSE_CANCEL),
3505            post(responses::responses_cancel),
3506        )
3507        .route(&axum_path(routes::SLOTS_ID), post(slots::post_slot))
3508        .route(routes::V1_STATS, get(serving_stats))
3509        .route(routes::V1_REQUESTS, get(recent_requests))
3510        .route(routes::V1_CACHE_STATUS, get(cache_admin::cache_status))
3511        .route(routes::V1_CACHE_REBUILD, post(cache_admin::cache_rebuild))
3512        .route(routes::ADMIN_PREPARE_STOP, post(cache_admin::prepare_stop))
3513        .route(
3514            routes::LORA_ADAPTERS,
3515            get(lora::get_lora_adapters).post(lora::post_lora_adapters),
3516        )
3517        .route(routes::V1_CHAT_COMPLETIONS, post(chat_completions))
3518        // Behind the same key as the endpoint that started the work:
3519        // an unauthenticated caller must not be able to stop someone
3520        // else's generation by guessing at request ids.
3521        .route(routes::V1_CANCEL, post(cancel_generation))
3522        // Reconnect and the polling fallback, both behind the same key
3523        // as the request that filled the buffer: the replay window holds
3524        // the model's output, so reading it must cost what producing it
3525        // cost.
3526        .route(&axum_path(routes::V1_STREAM), get(resume::resume))
3527        .route(&axum_path(routes::V1_STREAM_POLL), get(resume::poll))
3528        .route(routes::V1_MESSAGES, post(anthropic::messages))
3529        .route(
3530            routes::V1_MESSAGES_COUNT_TOKENS,
3531            post(anthropic::count_tokens),
3532        )
3533        .route(routes::V1_COMPLETIONS, post(openai_extra::completions))
3534        // llama.cpp's NATIVE completion endpoint, under both spellings
3535        // it mounts. Not an alias of the line above: different request
3536        // fields, a different response object, and a stream that ends
3537        // without `[DONE]`. See `crate::completion`.
3538        .route(routes::COMPLETION, post(completion::completion))
3539        .route(routes::COMPLETIONS, post(completion::completion))
3540        .route(routes::V1_TOKENIZE, post(openai_extra::tokenize))
3541        .route(routes::V1_DETOKENIZE, post(openai_extra::detokenize))
3542        // llama.cpp's unprefixed spelling of the same two, on the SAME
3543        // handlers -- not copies. The `/v1/` prefix was frink's
3544        // invention (OpenAI has no tokenize endpoint), so every
3545        // llama.cpp client was getting a 404 that named nothing. Behind
3546        // the key with their twins: they read the loaded vocabulary.
3547        .route(routes::TOKENIZE, post(openai_extra::tokenize))
3548        .route(routes::DETOKENIZE, post(openai_extra::detokenize))
3549        .route(routes::V1_EMBEDDINGS, post(embeddings::embeddings))
3550        // Cross-encoder reranking, under the `/v1` spelling Cohere and
3551        // Jina clients use and the unprefixed one llama.cpp mounts.
3552        // Same handler: this really is an alias, not a second dialect.
3553        .route(routes::V1_RERANK, post(rerank::rerank))
3554        .route(routes::RERANK, post(rerank::rerank))
3555        .route(routes::CACHE_STATS, get(cache_stats))
3556        .route(routes::METRICS, get(metrics))
3557        // The control surface. Registered inside `protected` on
3558        // purpose: these routes change what the server serves and write
3559        // to disk, so they get the same FRINK_API_KEY gate as /v1/*
3560        // and never the unauthenticated treatment /health has.
3561        .route(routes::ADMIN_MODELS, get(admin::models))
3562        .route(routes::ADMIN_MODELS_LOAD, post(admin::load_model))
3563        .route(routes::ADMIN_MODELS_UNLOAD, post(admin::unload_model))
3564        // Not under `/admin`: a scheduler that puts a server to sleep
3565        // between jobs is not administering it, and vLLM's own routes
3566        // are at the root.
3567        .route(routes::SLEEP, post(admin::sleep))
3568        .route(routes::WAKE_UP, post(admin::wake_up))
3569        .route(routes::IS_SLEEPING, get(admin::is_sleeping))
3570        .route(routes::ADMIN_DOWNLOAD, post(admin::download))
3571        .route(routes::ADMIN_TASKS, get(admin::tasks))
3572        .route(&admin::cancel_route(), post(admin::cancel_task))
3573        .route(routes::ADMIN_STATS, get(admin::stats))
3574        // Server-side conversation storage, mounted here so it inherits
3575        // the same key gate as the endpoint that generated the text it
3576        // stores. Routes and store both live in `conversations`.
3577        .merge(conversations::router())
3578}
3579
3580fn axum_path(template: &str) -> String {
3581    let mut out = String::with_capacity(template.len());
3582    let mut rest = template;
3583    while let Some(open) = rest.find('{') {
3584        let Some(close) = rest[open..].find('}').map(|c| open + c) else {
3585            break;
3586        };
3587        out.push_str(&rest[..open]);
3588        out.push(':');
3589        out.push_str(&rest[open + 1..close]);
3590        rest = &rest[close + 1..];
3591    }
3592    out.push_str(rest);
3593    out
3594}
3595
3596/// `POST /v1/cancel` -- the explicit half of two-tier cancellation.
3597///
3598/// Answers `200` when a live generation was signalled and `404` when
3599/// the id names nothing that is running. That difference is the whole
3600/// point of the endpoint returning a body at all: "already finished"
3601/// and "stopped it" are both fine outcomes, but only one of them saved
3602/// any work, and a UI told `ok: true` for both will claim it stopped
3603/// something it did not.
3604async fn cancel_generation(
3605    State(state): State<Arc<AppState>>,
3606    Json(req): Json<frink_api::CancelGenerationRequest>,
3607) -> Response {
3608    let cancelled = state.cancels.cancel(&req.request_id);
3609    let status = if cancelled {
3610        StatusCode::OK
3611    } else {
3612        StatusCode::NOT_FOUND
3613    };
3614    let detail = if cancelled {
3615        "the generation was asked to stop; it ends at its next token".to_string()
3616    } else {
3617        "no generation with that request_id is running -- it has already \
3618         finished, was never issued, or was served by a path that does \
3619         not register for cancellation"
3620            .to_string()
3621    };
3622    (
3623        status,
3624        Json(frink_api::CancelGenerationResponse {
3625            request_id: req.request_id,
3626            cancelled,
3627            detail,
3628        }),
3629    )
3630        .into_response()
3631}
3632
3633/// What a freshly loaded checkpoint becomes when it is published as the
3634/// active model: the model itself, its optional continuous-batching
3635/// worker, and the context ceiling both decode paths admit on.
3636type Activated = (
3637    Loaded,
3638    Option<serving::batch::ContinuousBatcher>,
3639    Option<Arc<budget::ContextCeiling>>,
3640);
3641
3642/// The scheduler config for a freshly loaded GGUF, with the ceilings an
3643/// operator did not configure *derived* from the checkpoint instead of
3644/// left absent.
3645///
3646/// This is the server half of `mem-preload-kv-budget`: `frink run`
3647/// already priced weights + `n_ctx * per_token_kv` + headroom against
3648/// the device budget before loading, while `frink-server` admitted on
3649/// whatever `FRINK_CB_*` happened to be set and otherwise on nothing.
3650///
3651/// Precedence is one-directional and deliberate: an explicit
3652/// `FRINK_CB_MAX_CONTEXT` / `FRINK_CB_KV_BLOCKS` is never overridden,
3653/// because an operator who names a number has information this
3654/// arithmetic does not. Derivation only ever fills an *absent* ceiling,
3655/// where the alternative is no ceiling at all.
3656///
3657/// `path` is `None` for the synthetic-weights fallback, which has no
3658/// checkpoint on disk to price.
3659fn price_batcher_config(path: Option<&str>) -> serving::batch::BatcherConfig {
3660    let mut batcher = serving::batch::BatcherConfig::from_env();
3661    if batcher.max_context.is_some() && batcher.kv_blocks.is_some() {
3662        // Nothing left to derive, and pricing the checkpoint would only
3663        // print arithmetic that decides nothing.
3664        return batcher;
3665    }
3666    let Some(path) = path else {
3667        return batcher;
3668    };
3669    // `frink_core::cache::KvCache` is `Vec<f32>` on both decode paths,
3670    // so f32 is the width really kept, even under Metal attention where
3671    // the *device* also holds an f16 copy. Budgeting the host store is
3672    // the conservative reading: it over-charges KV and therefore
3673    // under-states the context that fits.
3674    let priced = budget::price_gguf(path, frink_models::KvElem::F32, 1);
3675    let Some((priced, gguf_ctx, source)) = priced else {
3676        return batcher;
3677    };
3678    let Some(derived) = budget::derive_limits(&priced, gguf_ctx, batcher.kv_block_size) else {
3679        // See `budget`'s module doc: a fit of zero tokens is not a
3680        // ceiling of zero, it is an estimate saying this model should
3681        // not have loaded -- and it did. Say so and admit as before.
3682        tracing::warn!(
3683            "this checkpoint's weights leave no room for KV inside the {source}: {} weight \
3684             bytes against a {} byte budget. Serving with no derived context ceiling -- set \
3685             FRINK_DEVICE_BUDGET_BYTES if the probe is wrong, or FRINK_CB_MAX_CONTEXT to \
3686             admit on a number you choose.",
3687            priced.weights_bytes,
3688            priced.device_budget_bytes,
3689        );
3690        return batcher;
3691    };
3692    tracing::info!("{source}");
3693    tracing::info!("{}", derived.fit);
3694    let adopted = budget::apply_derived(&mut batcher, &derived);
3695    if adopted.max_context {
3696        tracing::info!(
3697            "derived per-request context ceiling: {} token positions (prompt + max_tokens); \
3698             override with FRINK_CB_MAX_CONTEXT",
3699            derived.max_context
3700        );
3701    }
3702    if adopted.kv_blocks {
3703        tracing::info!(
3704            "derived KV block budget: {} blocks x {} positions; override with FRINK_CB_KV_BLOCKS",
3705            derived.kv_blocks,
3706            batcher.kv_block_size
3707        );
3708    }
3709    if let Some(narrowed) = adopted.max_context_narrowed {
3710        tracing::info!(
3711            "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",
3712            batcher.kv_blocks.unwrap_or_default(),
3713            batcher.kv_block_size
3714        );
3715    }
3716    batcher
3717}
3718
3719/// Turns a freshly loaded checkpoint into the parts that get published
3720/// as the active model.
3721///
3722/// Extracted from `build_app_state` so `/admin/models/load` builds its
3723/// replacement exactly the way startup builds the first one -- a second
3724/// copy of this match would be a second place for a new engine variant
3725/// to be forgotten, and the difference would only show up as a model
3726/// that silently loses continuous batching after a swap.
3727pub(crate) fn activate_loaded_model(
3728    loaded: model::LoadedModel,
3729    enable_continuous_batching: bool,
3730    path: Option<&str>,
3731    paged_kv: Option<&generate::PagedKvConfig>,
3732) -> Activated {
3733    match loaded {
3734        model::LoadedModel::Gguf(g) => {
3735            let decoder = Arc::new(g.decoder);
3736            let tokenizer = Arc::new(g.tokenizer);
3737            let config = price_batcher_config(path);
3738            // Prefill is still a per-token `forward_token` loop on both
3739            // paths (see `sched-chunked-prefill`: chunking bought
3740            // fairness, not a batched prefill kernel), so a sliding
3741            // layer really does need only `window + 1 - 1` positions
3742            // live. `chunk = 1` here is the truth, not a simplification.
3743            let shape =
3744                frink_models::KvShape::from_config(&decoder.config, frink_models::KvElem::F32);
3745            let ceiling = Arc::new(budget::ContextCeiling::new(config.max_context, shape));
3746            let batcher = if enable_continuous_batching {
3747                tracing::info!(
3748                    "continuous batching enabled: decode steps share Decoder::forward_multi_seq \
3749                     (stop sequences use the same pending-buffer trim as the private generate loop)"
3750                );
3751                let tok = Arc::clone(&tokenizer);
3752                let decode = Arc::new(move |ids: &[usize]| tok.decode_bytes(ids));
3753                Some(serving::batch::ContinuousBatcher::spawn_with_ceiling(
3754                    Arc::clone(&decoder),
3755                    decode,
3756                    config,
3757                    Arc::clone(&ceiling),
3758                    paged_kv.cloned(),
3759                ))
3760            } else {
3761                None
3762            };
3763            (
3764                Loaded::Generative(Arc::new(Model::Gguf(GgufModel {
3765                    decoder,
3766                    tokenizer,
3767                    stop_tokens: g.stop_tokens,
3768                    bos_id: g.bos_id,
3769                    is_synthetic: g.is_synthetic,
3770                    chat_template: g.chat_template,
3771                }))),
3772                batcher,
3773                Some(ceiling),
3774            )
3775        }
3776        model::LoadedModel::Kimi(k) => (
3777            Loaded::Generative(Arc::new(Model::Kimi(KimiModel {
3778                engine: k.engine,
3779                tokenizer: k.tokenizer,
3780                stop_tokens: k.stop_tokens,
3781                chat_template: k.chat_template,
3782            }))),
3783            None,
3784            None,
3785        ),
3786        model::LoadedModel::Mla(m) => (
3787            Loaded::Generative(Arc::new(Model::Mla(MlaModel {
3788                engine: m.engine,
3789                tokenizer: m.tokenizer,
3790                stop_tokens: m.stop_tokens,
3791                bos_id: m.bos_id,
3792                name: m.name,
3793                chat_template: m.chat_template,
3794            }))),
3795            None,
3796            None,
3797        ),
3798        model::LoadedModel::Gemma4(m) => (
3799            Loaded::Generative(Arc::new(Model::Gemma4(Gemma4Model {
3800                engine: m.engine,
3801                tokenizer: m.tokenizer,
3802                stop_tokens: m.stop_tokens,
3803                bos_id: m.bos_id,
3804                name: m.name,
3805                chat_template: m.chat_template,
3806            }))),
3807            None,
3808            None,
3809        ),
3810        model::LoadedModel::Glm52(g) => (
3811            Loaded::Generative(Arc::new(Model::Glm52(Glm52Model {
3812                engine: g.engine,
3813                tokenizer: g.tokenizer,
3814                stop_tokens: g.stop_tokens,
3815                bos_id: g.bos_id,
3816                name: g.name,
3817                chat_template: g.chat_template,
3818            }))),
3819            None,
3820            None,
3821        ),
3822        // No batcher and no ceiling, and neither is an omission: an
3823        // encoder has no decode step to share between requests and no
3824        // KV cache to price a context against. Handing it either would
3825        // be pricing a cost it does not have.
3826        model::LoadedModel::Encoder(e) => (Loaded::Encoder(e), None, None),
3827    }
3828}
3829
3830/// The models a server starts with: the generation model, and the
3831/// embedding model when `FRINK_EMBEDDING_MODEL_PATH` names one.
3832///
3833/// One struct rather than two parameters because they are chosen
3834/// together at startup and are the only two things `build_app_state`
3835/// takes that are a *model*.
3836struct StartupModels {
3837    loaded: model::LoadedModel,
3838    embedding: Option<Arc<frink_models::EmbeddingModel>>,
3839}
3840
3841fn continuous_batching_env() -> Option<bool> {
3842    match std::env::var("FRINK_CONTINUOUS_BATCHING")
3843        .ok()
3844        .map(|v| v.trim().to_ascii_lowercase())
3845        .as_deref()
3846    {
3847        None => None,
3848        Some("1" | "true" | "yes" | "on") => Some(true),
3849        Some("0" | "false" | "no" | "off") => Some(false),
3850        _ => None,
3851    }
3852}
3853
3854fn metal_private_decode_active() -> bool {
3855    #[cfg(feature = "metal")]
3856    {
3857        BUILT_WITH_METAL
3858            && frink_metal::attn::metal_attn_enabled()
3859            && std::env::var("FRINK_METAL").ok().as_deref() != Some("0")
3860    }
3861    #[cfg(not(feature = "metal"))]
3862    {
3863        false
3864    }
3865}
3866
3867fn continuous_batching_compatible(
3868    loaded: &model::LoadedModel,
3869    kv_pool: &Option<generate::KvPoolConfig>,
3870    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3871    paged_kv: &Option<generate::PagedKvConfig>,
3872) -> bool {
3873    matches!(loaded, model::LoadedModel::Gguf(_))
3874        && (paged_kv.is_some() || (kv_pool.is_none() && prefix_cache.is_none()))
3875}
3876
3877fn resolve_continuous_batching_enabled(
3878    loaded: &model::LoadedModel,
3879    kv_pool: &Option<generate::KvPoolConfig>,
3880    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3881    paged_kv: &Option<generate::PagedKvConfig>,
3882) -> bool {
3883    if !continuous_batching_compatible(loaded, kv_pool, prefix_cache, paged_kv) {
3884        return false;
3885    }
3886    match continuous_batching_env() {
3887        Some(true) => true,
3888        Some(false) => false,
3889        None => metal_private_decode_active(),
3890    }
3891}
3892
3893fn acquire_metal_private_decode_gate(
3894    gate: Option<&std::sync::Mutex<()>>,
3895    used_batcher: bool,
3896) -> Option<std::sync::MutexGuard<'_, ()>> {
3897    if used_batcher {
3898        None
3899    } else {
3900        gate.map(|g| g.lock().unwrap_or_else(|p| p.into_inner()))
3901    }
3902}
3903
3904fn build_app_state(
3905    models: StartupModels,
3906    kv_pool: Option<generate::KvPoolConfig>,
3907    paged_kv: Option<generate::PagedKvConfig>,
3908    prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
3909    enable_continuous_batching: bool,
3910    mcp: Option<mcp::LoadedMcpConfig>,
3911    detection: Arc<health::Detection>,
3912) -> AppState {
3913    let StartupModels { loaded, embedding } = models;
3914    let configured_path = std::env::var("FRINK_MODEL_PATH").ok();
3915    let (loaded, batcher, ceiling) = activate_loaded_model(
3916        loaded,
3917        enable_continuous_batching,
3918        configured_path.as_deref(),
3919        paged_kv.as_ref(),
3920    );
3921    // The startup model's admin id is whichever discovered entry sits
3922    // at the configured path; `None` when it was not discovered (the
3923    // synthetic fallback, or a path outside the scanned directories),
3924    // in which case `/admin/models` reports nothing as active rather
3925    // than inventing an id no `load` request could name.
3926    let id = startup_model_id();
3927    let metal_private_decode_gate = if enable_continuous_batching || !metal_private_decode_active()
3928    {
3929        None
3930    } else {
3931        tracing::info!(
3932            "Metal private-loop decode will serialize concurrent requests until \
3933             continuous batching is enabled (FRINK_CONTINUOUS_BATCHING=1 or --cont-batching)"
3934        );
3935        Some(Arc::new(std::sync::Mutex::new(())))
3936    };
3937    AppState {
3938        slept: Mutex::new(None),
3939        embedding,
3940        active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
3941            id,
3942            loaded,
3943            batcher,
3944            ceiling,
3945            checkpoint_path: configured_path.as_deref().map(PathBuf::from),
3946        }))),
3947        paged_kv,
3948        load_in_progress: std::sync::atomic::AtomicBool::new(false),
3949        tasks: Arc::new(tasks::TaskRegistry::new()),
3950        cancels: Arc::new(cancel::CancelRegistry::new()),
3951        stats: stats::Stats::new(),
3952        streams: resume::StreamRegistry::new(),
3953        model_dir: admin::model_dirs().into_iter().next(),
3954        response_cache: Mutex::new(ResponseCache::new(1000, Duration::from_secs(3600))),
3955        kv_pool,
3956        prefix_cache,
3957        sessions: session::SessionStore::new(),
3958        requests_total: std::sync::atomic::AtomicU64::new(0),
3959        request_errors_total: std::sync::atomic::AtomicU64::new(0),
3960        started_at: std::time::Instant::now(),
3961        last_request_ms: std::sync::atomic::AtomicU64::new(0),
3962        detection,
3963        mcp,
3964        continuous_batching_enabled: enable_continuous_batching,
3965        metal_private_decode_gate,
3966        loading_model: Mutex::new(None),
3967        last_load_error: Mutex::new(None),
3968        serving: Mutex::new(crate::stats::ServingStats::default()),
3969        maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
3970        footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
3971        started_unix: unix_now(),
3972    }
3973}
3974
3975/// Builds the `/v1/embeddings` encoder from
3976/// `FRINK_EMBEDDING_MODEL_PATH`, or `None` when the variable is unset.
3977///
3978/// A failure here is fatal rather than deferred: a server that starts
3979/// with a misspelt path and then answers embedding requests out of the
3980/// *decoder* would be handing back vectors from the wrong model with
3981/// nothing in the response saying so.
3982fn load_embedding_model() -> anyhow::Result<Option<Arc<frink_models::EmbeddingModel>>> {
3983    let Ok(path) = std::env::var("FRINK_EMBEDDING_MODEL_PATH") else {
3984        return Ok(None);
3985    };
3986    let model = frink_models::EmbeddingModel::from_gguf_path(&path)
3987        .map_err(|e| anyhow::anyhow!("FRINK_EMBEDDING_MODEL_PATH={path}: {e}"))?;
3988    tracing::info!(
3989        "loaded embedding model '{}' ({}, {} dims, pooling {}, max {} tokens)",
3990        model.name(),
3991        model.architecture(),
3992        model.n_embd(),
3993        model.pooling_type().name(),
3994        model.n_ctx_train(),
3995    );
3996    Ok(Some(Arc::new(model)))
3997}
3998
3999/// Seconds since the epoch, or zero on a machine whose clock is set
4000/// before it. Only ever used to make an id distinct between process
4001/// generations, so a nonsense clock costs distinctness and nothing
4002/// else.
4003fn unix_now() -> u64 {
4004    std::time::SystemTime::now()
4005        .duration_since(std::time::UNIX_EPOCH)
4006        .map(|d| d.as_secs())
4007        .unwrap_or(0)
4008}
4009
4010/// The `/admin/models` id of the checkpoint `FRINK_MODEL_PATH` names,
4011/// when discovery finds it. Matching on the resolved path rather than
4012/// on the filename keeps two same-named files in different directories
4013/// from claiming each other's id.
4014fn startup_model_id() -> Option<String> {
4015    let configured = std::env::var("FRINK_MODEL_PATH").ok()?;
4016    let configured = std::fs::canonicalize(&configured).ok()?;
4017    admin::discover(&admin::model_dirs())
4018        .into_iter()
4019        .find(|d| {
4020            std::fs::canonicalize(&d.path)
4021                .map(|p| p == configured)
4022                .unwrap_or(false)
4023        })
4024        .map(|d| d.id)
4025}
4026
4027/// Builds the global rayon pool up front, on the main thread, with an
4028/// explicit width and QoS (see [`frink_core::threads`]).
4029///
4030/// Doing this from `main` rather than letting rayon build lazily is the
4031/// point: the first rayon call inside this server happens on a Tokio
4032/// `spawn_blocking` thread, so the workers used to inherit that thread's
4033/// QoS class -- which on macOS decides whether they land on performance
4034/// or efficiency cores.
4035fn init_cpu_pool() {
4036    match frink_core::threads::init_cpu_pool() {
4037        Some(n) => eprintln!(
4038            "frink-server: rayon pool {n} threads (perf cores {}; override with FRINK_CPU_THREADS)",
4039            frink_core::threads::perf_core_count()
4040        ),
4041        None => eprintln!("frink-server: global rayon pool already built; leaving it alone"),
4042    }
4043}
4044
4045/// Prints the machine-readable ready line (see `frink_api::lifecycle`)
4046/// on stdout and flushes it.
4047///
4048/// This one line is what makes `--port 0` usable, and it deletes a whole
4049/// feature from any supervising process: no "is the port free" probe, no
4050/// `lsof` to work out whether an existing listener is a stale copy of
4051/// ourselves or a stranger's server, no dialog to explain the result.
4052/// The kernel picks the port and the child says what it got.
4053///
4054/// Shares stdout with the tracing subscriber on purpose -- a parent
4055/// reads stdout line by line and ignores anything that is not the ready
4056/// event, which `ServerReady::from_line` does for it.
4057fn announce_ready(addr: SocketAddr, scheme: &str) {
4058    use std::io::Write;
4059    let ready =
4060        frink_api::ServerReady::new(addr, scheme, env!("CARGO_PKG_VERSION"), std::process::id());
4061    let mut stdout = std::io::stdout().lock();
4062    let _ = writeln!(stdout, "{}", ready.to_line());
4063    let _ = stdout.flush();
4064}
4065
4066/// Resolves when the server should stop serving.
4067///
4068/// Stdin-close is the one orphan-prevention mechanism that behaves
4069/// identically on macOS, Windows and Linux and survives a parent that
4070/// dies rather than exiting cleanly: the kernel closes the pipe either
4071/// way. The POSIX alternative -- a signal handler plus an exit hook plus
4072/// a reaper -- has no Windows equivalent at all, since there is no
4073/// SIGTERM there.
4074///
4075/// When disabled this future never resolves, which is exactly the
4076/// previous behaviour: serve until the process is stopped externally.
4077async fn shutdown_signal(exit_on_stdin_close: bool) {
4078    if !exit_on_stdin_close {
4079        std::future::pending::<()>().await;
4080        return;
4081    }
4082    let _ = tokio::task::spawn_blocking(|| {
4083        use std::io::Read;
4084        let mut sink = [0u8; 256];
4085        let mut stdin = std::io::stdin().lock();
4086        loop {
4087            match stdin.read(&mut sink) {
4088                // EOF: the parent is gone, or closed the pipe.
4089                Ok(0) => break,
4090                // Input on stdin is not a protocol here; drain it.
4091                Ok(_) => continue,
4092                Err(e) => {
4093                    tracing::warn!("stdin read failed ({e}); treating it as closed");
4094                    break;
4095                }
4096            }
4097        }
4098    })
4099    .await;
4100    tracing::info!("stdin closed; shutting down");
4101}
4102
4103/// Tokio worker threads. The default is one per logical core, which on a
4104/// 10-core M2 Pro means 10 async workers oversubscribing the same cores
4105/// the rayon decode pool needs. Serving work here is almost entirely I/O
4106/// plus `spawn_blocking` handoff, so a small fixed pool is enough.
4107fn tokio_worker_threads() -> usize {
4108    std::env::var("FRINK_TOKIO_WORKERS")
4109        .ok()
4110        .and_then(|v| v.trim().parse::<usize>().ok())
4111        .filter(|n| *n > 0)
4112        .unwrap_or(2)
4113}
4114
4115/// Parses llama-server-style options and applies their environment
4116/// overrides before creating Tokio or Rayon worker threads. It then
4117/// brackets the async server lifecycle with journal records.
4118/// Install rustls' `ring` crypto provider as the process default.
4119///
4120/// `axum-server` is built with `tls-rustls-no-provider`, which
4121/// deliberately does NOT pick a backend -- see the comment on the
4122/// dependency in `Cargo.toml`. rustls then has no default provider, and
4123/// building a `ServerConfig` without one fails at ACCEPT time rather
4124/// than at compile time, which is the worst place for it to surface: a
4125/// server that started cleanly and refuses every TLS connection.
4126///
4127/// So this runs unconditionally at startup, not lazily in the TLS arm.
4128/// `install_default` returns `Err` if a provider is already installed,
4129/// which is not a failure -- it means something else got there first
4130/// and the invariant we care about (there IS a provider) already holds.
4131fn install_ring_crypto_provider() {
4132    let _ = rustls::crypto::ring::default_provider().install_default();
4133}
4134
4135/// Runs the server to completion.
4136///
4137/// Takes already-parsed arguments so the same library backs both the
4138/// `frink-server` binary and frink-cli's optional `serve` feature,
4139/// and neither front end can drift into its own startup logic.
4140pub fn run_server(args: ServerArgs) -> anyhow::Result<()> {
4141    if args.list_devices {
4142        frink_models::devices::print_available_devices();
4143        return Ok(());
4144    }
4145    apply_cli_overrides(&args)?;
4146
4147    // Before the model is loaded and before the port is bound: refuse
4148    // to be the second process holding weights on this host. Held for
4149    // the life of the process -- dropping it deregisters us.
4150    let _instance = {
4151        use frink_core::instance::{register, InstancePolicy};
4152        let policy = if args.allow_multiple_instances {
4153            InstancePolicy::Multi
4154        } else {
4155            InstancePolicy::from_env_or(InstancePolicy::Single)
4156        };
4157        let model = std::env::var("FRINK_MODEL_PATH").ok();
4158        register(
4159            "server",
4160            model.as_deref(),
4161            frink_core::instance::current_backend(),
4162            policy,
4163        )
4164        .map_err(|conflict| anyhow::anyhow!("{conflict}"))?
4165    };
4166
4167    let journal = journal::Journal::from_env();
4168    eprintln!(
4169        "frink-server: process lifecycle journal at {:?} (override with FRINK_JOURNAL_PATH)",
4170        journal.path()
4171    );
4172    journal.append(&journal::Record::session_start(
4173        env!("CARGO_PKG_VERSION"),
4174        std::process::id(),
4175    ));
4176    journal::install_panic_hook(journal.clone());
4177
4178    let mcp_config_path = args.mcp_config.clone();
4179    let exit_on_stdin_close = args.exit_on_stdin_close
4180        || std::env::var("FRINK_EXIT_ON_STDIN_CLOSE")
4181            .map(|v| v == "1")
4182            .unwrap_or(false);
4183
4184    // Before Tokio exists, so the decode pool's threads are not spawned
4185    // from (and do not inherit the QoS of) a blocking-pool thread.
4186    // SAFETY: still single-threaded here.
4187    unsafe { frink_core::weight_matrix::default_cpu_int_dot_on() };
4188    init_cpu_pool();
4189
4190    let runtime = tokio::runtime::Builder::new_multi_thread()
4191        .worker_threads(tokio_worker_threads())
4192        .enable_all()
4193        .build()?;
4194    let result = runtime.block_on(run(mcp_config_path, exit_on_stdin_close));
4195
4196    let reason = match &result {
4197        Ok(()) => "normal".to_string(),
4198        Err(e) => e.to_string(),
4199    };
4200    journal.append(&journal::Record::session_exit(reason));
4201
4202    // Dropping the runtime instead would wait for blocking tasks, and
4203    // the stdin watcher parks in a blocking read that may never return
4204    // (a terminal keeps stdin open forever). The serving future has
4205    // already finished by here, so nothing useful is being abandoned.
4206    runtime.shutdown_background();
4207
4208    result
4209}
4210
4211async fn run(mcp_config_path: Option<PathBuf>, exit_on_stdin_close: bool) -> anyhow::Result<()> {
4212    // `try_init`, not `init`. As a library this runs inside a process
4213    // that may already have a subscriber: frink-cli installs one
4214    // before it dispatches, so `frink serve` would panic on startup
4215    // with "a global default trace dispatcher has already been set".
4216    // Losing the race is not an error, it means logging is configured.
4217    let _ = tracing_subscriber::fmt::try_init();
4218
4219    // Fail-closed listener check, before anything else (including
4220    // loading the model, so a misconfigured bind fails fast rather than
4221    // after however long that takes): refuse to start bound to a
4222    // non-loopback address with no API key configured, unless the
4223    // operator has explicitly opted into that via
4224    // FRINK_ALLOW_UNAUTHENTICATED_REMOTE=1 -- see
4225    // `security::check_bind_authorization`'s doc comment for why an
4226    // address that doesn't even parse as loopback is treated the same
4227    // as a confirmed non-loopback one.
4228    let addr = std::env::var("FRINK_ADDR").unwrap_or_else(|_| "127.0.0.1:8383".to_string());
4229    let api_key_configured = std::env::var("FRINK_API_KEY").is_ok();
4230    let allow_unauthenticated_remote = std::env::var("FRINK_ALLOW_UNAUTHENTICATED_REMOTE")
4231        .map(|v| v == "1")
4232        .unwrap_or(false);
4233    if let Err(msg) =
4234        security::check_bind_authorization(&addr, api_key_configured, allow_unauthenticated_remote)
4235    {
4236        anyhow::bail!(msg);
4237    }
4238
4239    // Loaded before the generation model, so a bad path fails the
4240    // start rather than the first `/v1/embeddings` request. This is the
4241    // SIDE-CAR: a second checkpoint beside a generative one. An encoder
4242    // at `FRINK_MODEL_PATH` needs none of this -- it goes through
4243    // `model::load()` below like any other checkpoint and becomes the
4244    // active model.
4245    let embedding_model = load_embedding_model()?;
4246
4247    let mut loaded = model::load()?;
4248    match &loaded {
4249        model::LoadedModel::Gguf(g) => tracing::info!(
4250            "loaded GGUF model '{}' (synthetic={}, tokenizer={})",
4251            g.decoder.config.name,
4252            g.is_synthetic,
4253            g.tokenizer.kind()
4254        ),
4255        model::LoadedModel::Kimi(k) => tracing::info!(
4256            "loaded Kimi K3 checkpoint (tokenizer={} base tokens)",
4257            k.tokenizer.vocab_size()
4258        ),
4259        model::LoadedModel::Mla(m) => tracing::info!(
4260            "loaded MLA GGUF '{}' (tokenizer={})",
4261            m.name,
4262            m.tokenizer.kind()
4263        ),
4264        model::LoadedModel::Gemma4(m) => tracing::info!(
4265            "loaded Gemma4 GGUF '{}' (tokenizer={})",
4266            m.name,
4267            m.tokenizer.kind()
4268        ),
4269        model::LoadedModel::Glm52(g) => tracing::info!(
4270            "loaded GLM-5.2 GGUF '{}' (tokenizer={})",
4271            g.name,
4272            g.tokenizer.kind()
4273        ),
4274        // `model::load_encoder_checkpoint` has already logged the
4275        // dimensions, the pooling rule and which endpoint serves it.
4276        model::LoadedModel::Encoder(_) => {}
4277    }
4278    // Opt-in VRAM budget for GPU-resident MoE experts. When unset but
4279    // Metal is active, default to a large budget so routed experts that
4280    // have Metal-capable quants run via `run_expert_placed` (Metal
4281    // matvec) instead of staying on CPU after Metal attention. Explicit
4282    // `FRINK_GPU_VRAM_BUDGET_BYTES=0` keeps the historical all-CPU MoE
4283    // placement. CUDA builds still require an explicit budget (Vast /
4284    // multi-GPU hosts vary too much for a safe default).
4285    let metal_default_moe_budget = {
4286        #[cfg(feature = "metal")]
4287        {
4288            frink_core::metal_dense_enabled()
4289                && std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES").is_err()
4290        }
4291        #[cfg(not(feature = "metal"))]
4292        {
4293            false
4294        }
4295    };
4296    if let Ok(budget_str) = std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES") {
4297        let budget: u64 = budget_str
4298            .parse()
4299            .expect("FRINK_GPU_VRAM_BUDGET_BYTES must be a non-negative integer");
4300        match &mut loaded {
4301            model::LoadedModel::Gguf(g) => {
4302                tracing::info!(
4303                    "GPU expert placement enabled: {budget} byte VRAM budget for routed experts \
4304                     (CUDA and/or Metal matvecs when built with the matching feature)"
4305                );
4306                g.decoder.gpu_vram_budget_bytes = Some(budget);
4307            }
4308            model::LoadedModel::Kimi(_) => {
4309                tracing::warn!(
4310                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Kimi K3 -- not \
4311                     supported yet (its MoE stack isn't wired to PlacementPlan), ignoring"
4312                );
4313            }
4314            model::LoadedModel::Mla(_) => {
4315                tracing::warn!(
4316                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is MLA -- dense \
4317                     FFN path only today; ignoring expert VRAM budget"
4318                );
4319            }
4320            model::LoadedModel::Gemma4(_) => {
4321                tracing::warn!(
4322                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Gemma4 -- \
4323                     ignoring expert VRAM budget"
4324                );
4325            }
4326            model::LoadedModel::Glm52(_) => {
4327                tracing::warn!(
4328                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is GLM-5.2 DSA -- \
4329                     GPU expert placement not wired yet; ignoring"
4330                );
4331            }
4332            model::LoadedModel::Encoder(_) => {
4333                tracing::warn!(
4334                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is an encoder -- \
4335                     it has no routed experts to place; ignoring"
4336                );
4337            }
4338        }
4339    } else if metal_default_moe_budget {
4340        // ~64 GiB sentinel: place as many experts as the planner allows;
4341        // Metal unified memory makes a hard VRAM split less meaningful
4342        // than on discrete CUDA cards.
4343        const METAL_DEFAULT_MOE_BUDGET: u64 = 64 * 1024 * 1024 * 1024;
4344        if let model::LoadedModel::Gguf(g) = &mut loaded {
4345            tracing::info!(
4346                "Metal MoE expert placement default-on ({METAL_DEFAULT_MOE_BUDGET} byte budget); \
4347                 set FRINK_GPU_VRAM_BUDGET_BYTES=0 to force CPU experts"
4348            );
4349            g.decoder.gpu_vram_budget_bytes = Some(METAL_DEFAULT_MOE_BUDGET);
4350        }
4351    }
4352    #[cfg(feature = "cuda")]
4353    {
4354        if frink_core::cuda_dense_enabled() {
4355            tracing::info!(
4356                "CUDA dense matvec enabled for WeightMatrix::apply \
4357                 (FRINK_CUDA=0|cpu forces CPU; weight buffers stay resident after first upload)"
4358            );
4359        } else {
4360            tracing::info!(
4361                "CUDA dense matvec disabled (FRINK_CUDA); dense decode uses CPU or Metal"
4362            );
4363        }
4364    }
4365    #[cfg(feature = "metal")]
4366    {
4367        if frink_core::metal_dense_enabled() {
4368            tracing::info!(
4369                "Metal dense matvec enabled for WeightMatrix::apply \
4370                 (FRINK_METAL=0|cpu forces CPU; weight buffers stay resident after first upload)"
4371            );
4372            match std::env::var("FRINK_METAL_ATTN").ok().as_deref() {
4373                Some("1") | Some("true") | Some("on") | Some("attn") => {
4374                    tracing::info!(
4375                        "Metal fused attention requested (FRINK_METAL_ATTN): \
4376                         QKV→RoPE→GQA→O on-GPU for Norm/NeoX decode without QKV bias/QK-norm"
4377                    );
4378                }
4379                _ => {}
4380            }
4381            tracing::info!(
4382                "Metal greedy GPU argmax: temperature<=0 folds \
4383                 final_norm+lm_head+argmax into the dense stack"
4384            );
4385        } else {
4386            tracing::info!("Metal dense matvec disabled (FRINK_METAL); dense decode uses CPU");
4387        }
4388    }
4389    // Both env vars are required together to enable pooling; unset ->
4390    // caches keep their original unbounded-per-request growth. This
4391    // mirrors the FRINK_API_KEY / FRINK_RATE_LIMIT_PER_MINUTE
4392    // pattern below: opt-in, off by default.
4393    //
4394    // Block count can be set explicitly (`FRINK_KV_POOL_BLOCKS` +
4395    // `FRINK_KV_POOL_BLOCK_SIZE`) or derived from a byte budget
4396    // (`FRINK_KV_BYTE_BUDGET` + `FRINK_KV_POOL_BLOCK_SIZE`, GGUF
4397    // models only). `FRINK_KV_POOL_BLOCKS` and
4398    // `FRINK_KV_BYTE_BUDGET` are mutually exclusive.
4399    let blocks_env = std::env::var("FRINK_KV_POOL_BLOCKS");
4400    let block_size_env = std::env::var("FRINK_KV_POOL_BLOCK_SIZE");
4401    let byte_budget_env = std::env::var("FRINK_KV_BYTE_BUDGET");
4402    if blocks_env.is_ok() && byte_budget_env.is_ok() {
4403        panic!(
4404            "FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive \
4405             (set one block-count source plus FRINK_KV_POOL_BLOCK_SIZE, or neither to disable)"
4406        );
4407    }
4408    let kv_pool = match (blocks_env, block_size_env, byte_budget_env) {
4409        (Ok(blocks), Ok(block_size), Err(_)) => {
4410            let total_blocks: usize = blocks
4411                .parse()
4412                .expect("FRINK_KV_POOL_BLOCKS must be a positive integer");
4413            let block_size: usize = block_size
4414                .parse()
4415                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4416            // Optional and independent of the two above: how long a
4417            // request retries before giving up when the pool is
4418            // momentarily exhausted, instead of rejecting on the very
4419            // first failed attempt. Zero (the default if unset)
4420            // preserves the original reject-immediately behavior.
4421            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4422                .ok()
4423                .map(|v| {
4424                    v.parse()
4425                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4426                })
4427                .unwrap_or(0);
4428            tracing::info!(
4429                "KV cache block pool enabled: {total_blocks} blocks x {block_size} positions \
4430                 each, shared across all concurrent requests, {queue_wait_ms}ms admission queue wait"
4431            );
4432            Some(generate::KvPoolConfig {
4433                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4434                queue_wait: Duration::from_millis(queue_wait_ms),
4435            })
4436        }
4437        (Err(_), Ok(block_size), Ok(byte_budget)) => {
4438            let block_size: usize = block_size
4439                .parse()
4440                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4441            let budget: u64 = byte_budget
4442                .parse()
4443                .expect("FRINK_KV_BYTE_BUDGET must be a positive integer");
4444            let cfg = match &loaded {
4445                model::LoadedModel::Gguf(g) => &g.decoder.config,
4446                model::LoadedModel::Kimi(_)
4447                | model::LoadedModel::Mla(_)
4448                | model::LoadedModel::Gemma4(_)
4449                | model::LoadedModel::Glm52(_)
4450                | model::LoadedModel::Encoder(_) => {
4451                    panic!(
4452                        "FRINK_KV_BYTE_BUDGET requires a GGUF decoder model \
4453                         (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4454                    );
4455                }
4456            };
4457            let bytes_per_block = block_size
4458                * cfg.kv_heads_all_layers()
4459                * (cfg.head_dim + cfg.v_head_dim())
4460                * std::mem::size_of::<f32>();
4461            assert!(
4462                bytes_per_block > 0,
4463                "derived KV block byte size must be positive (check model config and block size)"
4464            );
4465            let total_blocks = (budget as usize / bytes_per_block).max(1);
4466            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4467                .ok()
4468                .map(|v| {
4469                    v.parse()
4470                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4471                })
4472                .unwrap_or(0);
4473            tracing::info!(
4474                "KV cache block pool enabled from byte budget: {budget} bytes / \
4475                 {bytes_per_block} bytes per block ({block_size} positions x {} layers) -> \
4476                 {total_blocks} blocks, {queue_wait_ms}ms admission queue wait",
4477                cfg.n_layers
4478            );
4479            Some(generate::KvPoolConfig {
4480                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4481                queue_wait: Duration::from_millis(queue_wait_ms),
4482            })
4483        }
4484        (Err(_), Err(_), Err(_)) => None,
4485        (Err(_), Ok(_), Err(_)) => panic!(
4486            "FRINK_KV_POOL_BLOCK_SIZE requires FRINK_KV_POOL_BLOCKS or FRINK_KV_BYTE_BUDGET \
4487             (or unset all three to disable KV cache pooling)"
4488        ),
4489        (Ok(_), Ok(_), Ok(_)) => {
4490            unreachable!("FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive")
4491        }
4492        (Ok(_), Err(_), _) | (Err(_), Err(_), Ok(_)) => panic!(
4493            "FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET and FRINK_KV_POOL_BLOCK_SIZE must be \
4494             set together (or neither, to disable KV cache pooling)"
4495        ),
4496    };
4497    // Paged KV: per-layer shared page storage rather than a private
4498    // contiguous buffer per request. Refused alongside the pool and the
4499    // prefix cache rather than silently preferred over either -- an
4500    // operator who set two of these meant one of them, and picking for
4501    // them is how a deployment ends up not running what it thinks.
4502    let paged_kv = match (
4503        std::env::var("FRINK_PAGED_KV_BLOCKS"),
4504        std::env::var("FRINK_PAGED_KV_BLOCK_SIZE"),
4505    ) {
4506        (Ok(blocks), Ok(block_size)) => {
4507            assert!(
4508                kv_pool.is_none(),
4509                "FRINK_PAGED_KV_BLOCKS and FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET are \
4510                 mutually exclusive: both bound the same KV memory, by different means. \
4511                 Set one."
4512            );
4513            // Paged KV used to be refused here on any GPU backend,
4514            // because it returned fluent wrong tokens on Metal: the
4515            // prefill left K/V on the device and filled the host cache
4516            // with `KvCache::advance_len` placeholders, and the paged
4517            // prefill then copied those placeholders into the page
4518            // store. The decode that followed attended over a prompt
4519            // the model never saw.
4520            //
4521            // Fixed in `frink_models::Decoder`, which now downloads
4522            // the real rows for the caller that reads them, and pinned
4523            // on hardware by `paged_metal_parity` -- greedy ids
4524            // identical between paged and contiguous KV on a dense
4525            // model, an MoE model and a sliding-window model.
4526            let blocks_per_layer: usize = blocks
4527                .parse()
4528                .expect("FRINK_PAGED_KV_BLOCKS must be a positive integer");
4529            let block_size: usize = block_size
4530                .parse()
4531                .expect("FRINK_PAGED_KV_BLOCK_SIZE must be a positive integer");
4532            let gguf = match &loaded {
4533                model::LoadedModel::Gguf(g) => g,
4534                _ => panic!(
4535                    "FRINK_PAGED_KV_BLOCKS requires a GGUF decoder model \
4536                     (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4537                ),
4538            };
4539            let cfg = &gguf.decoder.config;
4540            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4541                .ok()
4542                .map(|v| {
4543                    v.parse()
4544                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4545                })
4546                .unwrap_or(0);
4547            tracing::info!(
4548                "Paged KV enabled: {blocks_per_layer} blocks x {block_size} positions per \
4549                 layer across {} layers, shared by all concurrent requests, \
4550                 {queue_wait_ms}ms admission queue wait",
4551                cfg.n_layers
4552            );
4553            // Prefix sharing rides on the same switch: paged KV is
4554            // what makes it possible at all, since sharing means two
4555            // sequences pointing at one page rather than one of them
4556            // holding a copy.
4557            let radix = Some(Arc::new(Mutex::new(
4558                crate::policy::radix::SaltedRadix::new(block_size),
4559            )));
4560            // The anchor: the position an agentic turn will come back
4561            // to. Resolved ONCE here, from the served checkpoint's own
4562            // family and its own tokenizer, because it has to be a
4563            // single token id for the slide to recognize it on the hot
4564            // path for nothing. A checkpoint whose opener is more than
4565            // one token, or whose family has no opener at all (harmony
4566            // opens a call with an ordinary channel header), simply gets
4567            // no anchors and the slide follows the cursor.
4568            let anchor_token = crate::policy::anchor::resolve_anchor_token(
4569                crate::policy::parser::ToolCallFormat::infer(
4570                    &std::env::var("FRINK_MODEL_PATH").unwrap_or_default(),
4571                )
4572                .opener(),
4573                |text| {
4574                    gguf.tokenizer
4575                        .encode(text, SpecialTokens::Parse)
4576                        .into_iter()
4577                        .map(|t| t as u32)
4578                        .collect()
4579                },
4580            );
4581            if let Some(id) = anchor_token {
4582                tracing::info!(
4583                    "Paged KV window slide: tool-call anchor is token {id}, so a turn's \
4584                     window stops short of where its next turn rejoins"
4585                );
4586            }
4587            let slide_interval: usize = std::env::var("FRINK_PAGED_KV_SLIDE_INTERVAL")
4588                .ok()
4589                .map(|v| {
4590                    v.parse()
4591                        .expect("FRINK_PAGED_KV_SLIDE_INTERVAL must be a positive integer")
4592                })
4593                .unwrap_or(crate::policy::pool_budget::DEFAULT_SWA_EVICTION_INTERVAL);
4594            if let Some(window) = cfg.uniform_sliding_window() {
4595                tracing::info!(
4596                    "Paged KV window slide enabled: every layer slides by {window} every \
4597                     {slide_interval} decode steps, so a request holds its prompt and a \
4598                     window rather than its whole context"
4599                );
4600            } else if cfg.kv_block_window().is_some() {
4601                tracing::info!(
4602                    "Paged KV window slide NOT enabled: this model has full-attention layers, \
4603                     and a page group holds one block in every layer"
4604                );
4605            }
4606            Some(generate::PagedKvConfig {
4607                // Per layer, because a per-layer-shape model's layers do
4608                // not all cache the same width (`layer_shapes`).
4609                store: Arc::new(cfg.new_paged_kv(block_size, blocks_per_layer)),
4610                queue_wait: Duration::from_millis(queue_wait_ms),
4611                radix,
4612                anchor_token,
4613                slide_interval,
4614            })
4615        }
4616        (Err(_), Err(_)) => None,
4617        _ => panic!(
4618            "FRINK_PAGED_KV_BLOCKS and FRINK_PAGED_KV_BLOCK_SIZE must be set together \
4619             (or neither, to disable paged KV)"
4620        ),
4621    };
4622    // Mutually exclusive with kv_pool (see generate::generate's doc
4623    // comment on why a pool-backed cache can't safely be restored from
4624    // a prefix-cache clone): if both are set, the KV pool wins and
4625    // prefix caching is simply never consulted -- generate() already
4626    // enforces this per-request, so this is a heads-up for the
4627    // operator, not a hard failure.
4628    let prefix_cache = std::env::var("FRINK_PREFIX_CACHE_ENTRIES").ok().map(|v| {
4629        let max_entries: usize = v
4630            .parse()
4631            .expect("FRINK_PREFIX_CACHE_ENTRIES must be a positive integer");
4632        if kv_pool.is_some() {
4633            tracing::warn!(
4634                "FRINK_PREFIX_CACHE_ENTRIES is set but so is the KV pool -- prefix \
4635                     caching will never be consulted while a KV pool is configured"
4636            );
4637        }
4638        // A hard refusal rather than the warning above, because the
4639        // outcome is worse than "never consulted": `PrefixCache` stores
4640        // `Vec<KvCache>` snapshots, and a paged request has none to
4641        // give, so every store would be skipped and every lookup miss.
4642        // An operator would see a prefix cache configured, reporting
4643        // zero hits forever, with nothing saying why.
4644        assert!(
4645            paged_kv.is_none(),
4646            "FRINK_PREFIX_CACHE_ENTRIES and FRINK_PAGED_KV_BLOCKS are mutually exclusive: \
4647             the prefix cache stores contiguous KV snapshots, which a paged request does not \
4648             produce, so the cache could never hit. Set one."
4649        );
4650        tracing::info!(
4651            "KV-prefix cache enabled: up to {max_entries} stored prefixes, shared across \
4652                 all requests"
4653        );
4654        Arc::new(Mutex::new(PrefixCache::new(max_entries)))
4655    });
4656    if matches!(
4657        loaded,
4658        model::LoadedModel::Kimi(_) | model::LoadedModel::Mla(_) | model::LoadedModel::Glm52(_)
4659    ) && (kv_pool.is_some() || prefix_cache.is_some())
4660    {
4661        tracing::warn!(
4662            "KV pool / prefix cache are configured but the loaded model is Kimi, MLA, or GLM-5.2 -- \
4663             neither is consulted for those engines (state shapes differ from Decoder KV); see \
4664             frink_models::engine's module docs"
4665        );
4666    }
4667    let enable_cb =
4668        resolve_continuous_batching_enabled(&loaded, &kv_pool, &prefix_cache, &paged_kv);
4669    if enable_cb && continuous_batching_env().is_none() && metal_private_decode_active() {
4670        tracing::info!(
4671            "continuous batching enabled by default on Metal for safe parallel serving \
4672             (set FRINK_CONTINUOUS_BATCHING=0 or --no-cont-batching to use the private path)"
4673        );
4674    }
4675    if continuous_batching_env() == Some(true)
4676        && !continuous_batching_compatible(&loaded, &kv_pool, &prefix_cache, &paged_kv)
4677        && (kv_pool.is_some() || prefix_cache.is_some())
4678    {
4679        tracing::warn!(
4680            "FRINK_CONTINUOUS_BATCHING=1 ignored while KV pool or prefix cache is configured \
4681             (those modes keep the private generate path)"
4682        );
4683    }
4684    if let Ok(n) = std::env::var("FRINK_CHUNKED_PREFILL") {
4685        if let Ok(chunk) = n.parse::<usize>() {
4686            if chunk > 0 {
4687                tracing::info!("chunked prefill enabled: {chunk} tokens per forward_batch chunk");
4688            }
4689        }
4690    }
4691    if matches!(
4692        std::env::var("FRINK_CPU_KV_OFFLOAD").ok().as_deref(),
4693        Some("1")
4694    ) {
4695        tracing::warn!(
4696            "FRINK_CPU_KV_OFFLOAD=1: syncing Metal KV to host after each decode step \
4697             (minimal spill; full layer offload still planned)"
4698        );
4699    }
4700
4701    let mcp = match mcp_config_path {
4702        Some(path) => {
4703            let loaded = mcp::load_mcp_config(&path)?;
4704            tracing::info!(
4705                "MCP config loaded from {} ({} server(s); invocation not wired yet)",
4706                loaded.path,
4707                loaded.servers.len()
4708            );
4709            Some(loaded)
4710        }
4711        None => None,
4712    };
4713
4714    // Started before the router is built so the probe overlaps with
4715    // binding the port: by the time a client can ask, it has usually
4716    // already landed.
4717    let detection = health::Detection::spawn();
4718
4719    let state = Arc::new(build_app_state(
4720        StartupModels {
4721            loaded,
4722            embedding: embedding_model,
4723        },
4724        kv_pool,
4725        paged_kv,
4726        prefix_cache,
4727        enable_cb,
4728        mcp,
4729        detection,
4730    ));
4731
4732    // Paths come from `frink_api::routes` rather than string literals
4733    // so the UI, `frink chat` and this router cannot disagree about
4734    // what the surface is.
4735    use frink_api::routes;
4736
4737    // Frink Studio is a separate app served by its own dev/static
4738    // server (see `ui/` at the repository root); it reaches this
4739    // process over the public HTTP API like any other client, so there
4740    // is nothing to mount here and `/` stays a 404.
4741    let public = Router::new().route(routes::HEALTH, get(health));
4742
4743    let mut protected = protected_routes();
4744
4745    // Both off by default; set the corresponding env var to enable.
4746    // route_layer (not layer) so these apply only to the routes above,
4747    // never to /health, which stays reachable for liveness/readiness
4748    // probes regardless of auth or rate-limit configuration.
4749    if let Ok(key) = std::env::var("FRINK_API_KEY") {
4750        tracing::info!("API key auth enabled");
4751        let auth = limits::AuthConfig {
4752            api_key: Arc::new(key),
4753        };
4754        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4755            auth,
4756            limits::require_api_key,
4757        ));
4758    }
4759    if let Ok(rpm) = std::env::var("FRINK_RATE_LIMIT_PER_MINUTE") {
4760        let rpm: u32 = rpm
4761            .parse()
4762            .expect("FRINK_RATE_LIMIT_PER_MINUTE must be a positive integer");
4763        tracing::info!("rate limiting enabled: {rpm} requests/minute (global)");
4764        let limiter = Arc::new(limits::RateLimiter::per_minute(rpm));
4765        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4766            limiter,
4767            limits::rate_limit,
4768        ));
4769    }
4770    // Off by default; set FRINK_CORS_ORIGINS (comma-separated exact
4771    // origins) to enable. No wildcard support by design -- see
4772    // `security::parse_cors_origins`'s doc comment. Added last (so it's
4773    // the outermost route_layer, run before auth/rate-limiting): a CORS
4774    // preflight (OPTIONS) request carries no Authorization header and
4775    // is answered directly by `CorsLayer` itself, so it must not be
4776    // blocked by the auth/rate-limit layers underneath.
4777    if let Ok(spec) = std::env::var("FRINK_CORS_ORIGINS") {
4778        let origins = security::parse_cors_origins(&spec)
4779            .unwrap_or_else(|e| panic!("FRINK_CORS_ORIGINS: {e}"));
4780        tracing::info!(
4781            "CORS enabled: {} allow-listed origin(s) ({})",
4782            origins.len(),
4783            spec
4784        );
4785        let cors = tower_http::cors::CorsLayer::new()
4786            .allow_origin(tower_http::cors::AllowOrigin::list(origins))
4787            .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
4788            .allow_headers([
4789                axum::http::header::CONTENT_TYPE,
4790                axum::http::header::AUTHORIZATION,
4791                // The self-declared client label the monitor records
4792                // (see `attribution`). A custom header makes every
4793                // cross-origin call preflighted, so omitting it here
4794                // would not merely drop the label -- it would fail the
4795                // request outright.
4796                axum::http::HeaderName::from_static(attribution::CLIENT_HEADER),
4797                // Set by hand rather than by `EventSource`, because
4798                // this API needs POST and a bearer token. Same
4799                // consequence if it is missing.
4800                axum::http::HeaderName::from_static("last-event-id"),
4801            ]);
4802        protected = protected.route_layer(cors);
4803    }
4804
4805    // Outermost on purpose: every 503 this server can emit -- from a
4806    // handler, from `require_active`, or from the batch scheduler's
4807    // queue cap -- leaves with a `Retry-After` a client can act on.
4808    let app = public
4809        .merge(protected)
4810        .layer(axum::middleware::from_fn(limits::retry_after))
4811        .with_state(state);
4812
4813    // TLS is off by default -- set FRINK_TLS_CERT and FRINK_TLS_KEY
4814    // together to serve HTTPS instead of plain HTTP; unset (either or
4815    // both) preserves the original plain-HTTP behavior exactly. See
4816    // `security::tls_paths_from_env`'s doc comment for why this can't
4817    // be meaningfully unit-tested here.
4818    let tls_paths = security::tls_paths_from_env().unwrap_or_else(|e| panic!("{e}"));
4819    install_ring_crypto_provider();
4820    // Both arms bind first and read the address back off the socket
4821    // rather than trusting the requested one: with `--port 0` the
4822    // requested port is a lie by construction, and the ready line has
4823    // to carry what the kernel actually handed out.
4824    match tls_paths {
4825        Some(paths) => {
4826            let config =
4827                axum_server::tls_rustls::RustlsConfig::from_pem_file(&paths.cert, &paths.key)
4828                    .await
4829                    .map_err(|e| {
4830                        anyhow::anyhow!(
4831                            "failed to load TLS cert/key ({:?}, {:?}): {e}",
4832                            paths.cert,
4833                            paths.key
4834                        )
4835                    })?;
4836            let socket_addr: std::net::SocketAddr = addr
4837                .parse()
4838                .map_err(|e| anyhow::anyhow!("invalid FRINK_ADDR {addr:?} for TLS: {e}"))?;
4839            let listener = std::net::TcpListener::bind(socket_addr)?;
4840            // Tokio panics outright when handed a BLOCKING socket
4841            // ("Registering a blocking socket with the tokio runtime is
4842            // unsupported"), and axum-server registers this one
4843            // internally. Without this the TLS arm binds, prints its
4844            // ready line, and then panics on the first accept -- so the
4845            // failure looks like a healthy start followed by a server
4846            // that answers nothing.
4847            listener.set_nonblocking(true)?;
4848            let bound = listener.local_addr()?;
4849            tracing::info!("TLS enabled: frink-server listening on https://{bound}");
4850            announce_ready(bound, "https");
4851
4852            let handle = axum_server::Handle::new();
4853            let shutdown_handle = handle.clone();
4854            tokio::spawn(async move {
4855                shutdown_signal(exit_on_stdin_close).await;
4856                shutdown_handle.graceful_shutdown(Some(Duration::from_secs(5)));
4857            });
4858            axum_server::from_tcp_rustls(listener, config)?
4859                .handle(handle)
4860                .serve(app.into_make_service())
4861                .await?;
4862        }
4863        None => {
4864            let listener = tokio::net::TcpListener::bind(&addr).await?;
4865            let bound = listener.local_addr()?;
4866            tracing::info!("frink-server listening on {bound}");
4867            announce_ready(bound, "http");
4868            axum::serve(listener, app)
4869                .with_graceful_shutdown(shutdown_signal(exit_on_stdin_close))
4870                .await?;
4871        }
4872    }
4873    Ok(())
4874}
4875
4876#[cfg(test)]
4877pub(crate) mod tests {
4878    use super::*;
4879    use frink_models::config::test_dense_fixture;
4880
4881    #[test]
4882    fn the_ready_line_round_trips_through_a_parent_reading_stdout() {
4883        let addr: SocketAddr = "127.0.0.1:51999".parse().unwrap();
4884        let ready = frink_api::ServerReady::new(addr, "http", "0.5.0", std::process::id());
4885        let parsed = frink_api::ServerReady::from_line(&ready.to_line()).unwrap();
4886        assert_eq!(parsed.port, 51999);
4887        assert_eq!(parsed.base_url(), "http://127.0.0.1:51999");
4888        // A parent reads stdout line by line; tracing shares the stream.
4889        assert!(frink_api::ServerReady::from_line("INFO frink-server listening").is_none());
4890    }
4891
4892    fn test_model() -> Model {
4893        // Tiny vocab (32): raw byte ids ≥32 (e.g. ASCII "hello") are OOV.
4894        // HTTP/chat-template tests that need full ASCII use
4895        // `test_model_full_byte_vocab` instead.
4896        let cfg = test_dense_fixture();
4897        Model::Gguf(GgufModel {
4898            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 32)),
4899            tokenizer: Arc::new(ServerTokenizer::Byte),
4900            stop_tokens: StopTokens::default(),
4901            bos_id: None,
4902            is_synthetic: true,
4903            chat_template: chat_template::PromptTemplate::plain(),
4904        })
4905    }
4906
4907    fn greedy_params(max_tokens: usize) -> GenerationParams {
4908        GenerationParams {
4909            cache_salt: None,
4910            prompt_logprobs: None,
4911            wants_logprobs: false,
4912            n: 1,
4913            interleave_choices: false,
4914            truncate_prompt_tokens: None,
4915            token_mask: crate::token_mask::TokenMask::default(),
4916            reasoning: None,
4917            max_tokens,
4918            sampling: SamplingParams::default(),
4919            seed: 1,
4920            stop: Vec::new(),
4921            stop_token_ids: Vec::new(),
4922            json_object: false,
4923            grammar: None,
4924            cancel: None,
4925            ignore_eos: false,
4926            reasoning_budget: crate::reasoning_budget::ReasoningBudget::Unrestricted,
4927            lora: None,
4928        }
4929    }
4930
4931    /// Declares a full 0..255 byte-compatible vocab so HTTP-level tests
4932    /// that render chat templates (ASCII role names) do not spuriously
4933    /// reject their own prompt prefixes.
4934    fn test_model_full_byte_vocab() -> Model {
4935        test_model_full_byte_vocab_with_eos(None)
4936    }
4937
4938    /// [`test_model_full_byte_vocab`] with an end-of-generation id, so a
4939    /// test can tell a turn the MODEL ended from one that merely ran out
4940    /// of budget -- which is the only way `ignore_eos` is observable.
4941    ///
4942    /// Parameterised rather than copied: a second `Model` literal here
4943    /// is one more place a field has to be remembered.
4944    fn test_model_full_byte_vocab_with_eos(eos: Option<usize>) -> Model {
4945        let mut cfg = test_dense_fixture();
4946        cfg.vocab_size = 256;
4947        Model::Gguf(GgufModel {
4948            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4949            tokenizer: Arc::new(ServerTokenizer::Byte),
4950            stop_tokens: StopTokens::from_eos(eos),
4951            bos_id: None,
4952            is_synthetic: true,
4953            chat_template: chat_template::PromptTemplate::plain(),
4954        })
4955    }
4956
4957    /// One `AppState` for the HTTP-level tests, so a new field on the
4958    /// struct is added in one place rather than in every test that
4959    /// builds one.
4960    pub(crate) fn test_state(model: Model, response_cache: ResponseCache) -> AppState {
4961        test_state_at(model, response_cache, None)
4962    }
4963
4964    /// [`test_state`] with a checkpoint path on record, which is what
4965    /// makes a model SLEEPABLE: `/sleep` refuses one it could not
4966    /// bring back, and the plain fixture is deliberately that case.
4967    pub(crate) fn test_state_at(
4968        model: Model,
4969        response_cache: ResponseCache,
4970        checkpoint_path: Option<std::path::PathBuf>,
4971    ) -> AppState {
4972        AppState {
4973            slept: Mutex::new(None),
4974            embedding: None,
4975            paged_kv: None,
4976            active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
4977                id: None,
4978                loaded: Loaded::Generative(Arc::new(model)),
4979                batcher: None,
4980                ceiling: None,
4981                checkpoint_path,
4982            }))),
4983            load_in_progress: std::sync::atomic::AtomicBool::new(false),
4984            tasks: Arc::new(tasks::TaskRegistry::new()),
4985            cancels: Arc::new(cancel::CancelRegistry::new()),
4986            stats: stats::Stats::new(),
4987            streams: resume::StreamRegistry::new(),
4988            model_dir: None,
4989            response_cache: Mutex::new(response_cache),
4990            kv_pool: None,
4991            prefix_cache: None,
4992            sessions: session::SessionStore::new(),
4993            requests_total: std::sync::atomic::AtomicU64::new(0),
4994            request_errors_total: std::sync::atomic::AtomicU64::new(0),
4995            started_at: std::time::Instant::now(),
4996            last_request_ms: std::sync::atomic::AtomicU64::new(0),
4997            detection: Arc::new(health::Detection::ready(health::probe_backends())),
4998            mcp: None,
4999            continuous_batching_enabled: false,
5000            metal_private_decode_gate: None,
5001            loading_model: Mutex::new(None),
5002            last_load_error: Mutex::new(None),
5003            serving: Mutex::new(crate::stats::ServingStats::default()),
5004            maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
5005            footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
5006            started_unix: unix_now(),
5007        }
5008    }
5009
5010    /// A real axum `Router` wired exactly like `main()`'s (minus auth/
5011    /// rate-limiting, which are orthogonal and already covered by
5012    /// `limits`'s own tests), backed by a fresh
5013    /// `test_model_full_byte_vocab()` -- so tool-calling/session tests
5014    /// exercise the real HTTP request/response path (JSON
5015    /// (de)serialization, routing, handler wiring, chat-template
5016    /// rendering) via `tower::ServiceExt::oneshot`, not just the inner
5017    /// functions directly.
5018    pub(crate) fn test_app() -> Router {
5019        test_app_with_state(Arc::new(test_state(
5020            test_model_full_byte_vocab(),
5021            ResponseCache::new(1000, Duration::from_secs(3600)),
5022        )))
5023    }
5024
5025    /// [`test_app`] over a caller-owned state, so a test can reach in
5026    /// and swap or unload the model behind a live router.
5027    pub(crate) fn test_app_with_state(state: Arc<AppState>) -> Router {
5028        // The SAME route list the server builds, not a hand-written
5029        // copy of it. The copy that used to live here had drifted from
5030        // the real one, which is the failure mode that makes an HTTP
5031        // test worthless: it can only ever confirm that the tests agree
5032        // with the tests. See `protected_routes`.
5033        //
5034        // No auth, rate-limit or CORS layer: those are configured from
5035        // the environment in `run`, and a test that set the environment
5036        // would race every other test in the process.
5037        Router::new()
5038            .route(frink_api::routes::HEALTH, get(health))
5039            .merge(protected_routes())
5040            .with_state(state)
5041    }
5042
5043    fn named_test_model(name: &'static str, vocab_size: usize) -> Model {
5044        let mut cfg = test_dense_fixture();
5045        cfg.name = name;
5046        cfg.vocab_size = vocab_size;
5047        Model::Gguf(GgufModel {
5048            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5049            tokenizer: Arc::new(ServerTokenizer::Byte),
5050            stop_tokens: StopTokens::default(),
5051            bos_id: None,
5052            is_synthetic: true,
5053            chat_template: chat_template::PromptTemplate::plain(),
5054        })
5055    }
5056
5057    /// The same model, served through a real checkpoint's template
5058    /// rather than the role-labeled builtin -- so a test can ask what
5059    /// gets advertised for a checkpoint that actually has gears.
5060    fn model_with_template(name: &'static str, source: &str) -> Model {
5061        let mut cfg = test_dense_fixture();
5062        cfg.name = name;
5063        cfg.vocab_size = 256;
5064        Model::Gguf(GgufModel {
5065            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5066            tokenizer: Arc::new(ServerTokenizer::Byte),
5067            stop_tokens: StopTokens::default(),
5068            bos_id: None,
5069            is_synthetic: true,
5070            chat_template: chat_template::PromptTemplate::from_gguf_metadata(
5071                Some(source),
5072                Some("qwen3"),
5073                false,
5074                true,
5075                None,
5076                None,
5077            ),
5078        })
5079    }
5080
5081    /// Once a `200` and `text/event-stream` are on the wire, a
5082    /// rejection can only ride *in* the stream, where several agents
5083    /// render it as an empty response. So the prompt is rendered before
5084    /// the stream is committed, and a template that rejects this
5085    /// particular conversation is an ordinary 400 with a body.
5086    ///
5087    /// Fails if `prompt_from_messages` moves back inside the spawned
5088    /// generation task.
5089    #[tokio::test]
5090    async fn a_template_that_rejects_the_conversation_is_a_400_on_the_streaming_path() {
5091        // Raises on a second user turn, the way a real strict template
5092        // rejects an ordering it was never trained on.
5093        let strict = "{% if messages | length > 1 %}\
5094             {{ raise_exception('this template takes one turn') }}\
5095             {% endif %}{{ messages[0].content }}";
5096        let state = Arc::new(test_state(
5097            model_with_template("strict", strict),
5098            ResponseCache::new(4, Duration::from_secs(60)),
5099        ));
5100        let app = test_app_with_state(state);
5101
5102        let (status, body) = post_json_uri(
5103            &app,
5104            "/v1/chat/completions",
5105            serde_json::json!({
5106                "model": "strict",
5107                "stream": true,
5108                "messages": [
5109                    {"role": "user", "content": "one"},
5110                    {"role": "user", "content": "two"},
5111                ],
5112            }),
5113        )
5114        .await;
5115        assert_eq!(status, StatusCode::BAD_REQUEST);
5116        assert_eq!(body["error"]["param"], serde_json::json!("messages"));
5117        assert!(
5118            body["error"]["message"]
5119                .as_str()
5120                .unwrap()
5121                .contains("one turn"),
5122            "the template's own message must reach the caller: {body}"
5123        );
5124
5125        // And the same template serves a conversation it accepts.
5126        let (status, _) = post_json_uri(
5127            &app,
5128            "/v1/chat/completions",
5129            serde_json::json!({
5130                "model": "strict",
5131                "stream": true,
5132                "max_tokens": 1,
5133                "messages": [{"role": "user", "content": "one"}],
5134            }),
5135        )
5136        .await;
5137        assert_eq!(status, StatusCode::OK);
5138    }
5139
5140    /// A client should not have to guess which gears a checkpoint has.
5141    #[tokio::test]
5142    async fn models_advertises_the_gears_this_checkpoint_actually_has() {
5143        let reasoning = "{% if enable_thinking %}<think>{% endif %}\
5144             {% if reasoning_effort %}\
5145               {% if reasoning_effort not in ['low','medium','high'] %}\
5146                 {{ raise_exception('bad effort') }}\
5147               {% endif %}[{{ reasoning_effort }}]\
5148             {% endif %}{{ messages[0].content }}";
5149        let state = Arc::new(test_state(
5150            model_with_template("thinker", reasoning),
5151            ResponseCache::new(4, Duration::from_secs(60)),
5152        ));
5153        let app = test_app_with_state(state);
5154        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5155        assert_eq!(status, StatusCode::OK);
5156        let entry = &models["data"][0];
5157        assert_eq!(
5158            entry["supported_reasoning_efforts"],
5159            serde_json::json!(["off", "low", "medium", "high"])
5160        );
5161        assert_eq!(entry["default_reasoning_effort"], serde_json::json!("off"));
5162    }
5163
5164    /// The other half of the acceptance criterion: neither field, not
5165    /// an empty one. An empty list would say the question was asked and
5166    /// the answer was "no gears"; absence says it is not that kind of
5167    /// model.
5168    #[tokio::test]
5169    async fn a_checkpoint_with_no_thinking_controls_advertises_neither_field() {
5170        let app = test_app();
5171        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5172        let entry = &models["data"][0];
5173        assert!(entry.get("supported_reasoning_efforts").is_none());
5174        assert!(entry.get("default_reasoning_effort").is_none());
5175    }
5176
5177    fn active_model(state: &AppState, name: &'static str) -> Arc<ActiveModel> {
5178        Arc::new(ActiveModel {
5179            id: Some(name.to_string()),
5180            loaded: Loaded::Generative(Arc::new(named_test_model(name, 256))),
5181            batcher: None,
5182            ceiling: None,
5183            checkpoint_path: None,
5184        })
5185        .tap_into(state)
5186    }
5187
5188    /// Small helper so the swap tests read as "publish this model".
5189    trait TapInto {
5190        fn tap_into(self, state: &AppState) -> Self;
5191    }
5192    impl TapInto for Arc<ActiveModel> {
5193        fn tap_into(self, state: &AppState) -> Self {
5194            state.swap_active(Some(Arc::clone(&self)));
5195            self
5196        }
5197    }
5198
5199    /// The load-order guarantee the whole swap design exists to make:
5200    /// a request that has already taken its handle finishes against the
5201    /// weights it started on, even though a different model has since
5202    /// been published. Anything else would splice two checkpoints into
5203    /// one completion.
5204    #[test]
5205    fn an_in_flight_request_keeps_the_model_it_started_on() {
5206        let state = test_state(
5207            named_test_model("model-a", 256),
5208            ResponseCache::new(4, Duration::from_secs(60)),
5209        );
5210
5211        // A request that has begun: it has cloned the handle and is
5212        // about to decode against it.
5213        let in_flight = state.active().expect("a model is loaded");
5214        assert_eq!(in_flight.name(), "model-a");
5215
5216        active_model(&state, "model-b");
5217
5218        // The swap is visible to anything that asks *now*...
5219        assert_eq!(state.active().unwrap().name(), "model-b");
5220        // ...and completely invisible to the request already running.
5221        assert_eq!(in_flight.name(), "model-a");
5222        let produced = run_generation(
5223            in_flight.generative().unwrap(),
5224            "hi",
5225            &greedy_params(3),
5226            None,
5227            None,
5228            None,
5229            None,
5230            None,
5231            None,
5232        )
5233        .expect("the old model must still decode after being swapped out");
5234        assert!(matches!(
5235            produced.choices[0].finish,
5236            FinishReason::Length | FinishReason::Stop
5237        ));
5238    }
5239
5240    /// The other half of the same guarantee: the old model is not freed
5241    /// at swap time, it is freed when the last holder lets go. A design
5242    /// that dropped it eagerly would free weights out from under a
5243    /// decode loop.
5244    #[test]
5245    fn a_swapped_out_model_lives_until_its_last_holder_releases_it() {
5246        let state = test_state(
5247            named_test_model("model-a", 256),
5248            ResponseCache::new(4, Duration::from_secs(60)),
5249        );
5250        let in_flight = state.active().expect("a model is loaded");
5251        let weights = Arc::clone(in_flight.generative().unwrap());
5252        assert!(Arc::strong_count(&weights) >= 2);
5253
5254        let previous = state.swap_active(Some(Arc::new(ActiveModel {
5255            id: Some("model-b".to_string()),
5256            loaded: Loaded::Generative(Arc::new(named_test_model("model-b", 256))),
5257            batcher: None,
5258            ceiling: None,
5259            checkpoint_path: None,
5260        })));
5261        drop(previous);
5262        // The registry has let go; the in-flight request has not.
5263        assert!(Arc::strong_count(&weights) >= 2);
5264        drop(in_flight);
5265        assert_eq!(Arc::strong_count(&weights), 1);
5266    }
5267
5268    /// Unload is not "keep serving the last thing loaded". A request
5269    /// that arrives afterwards must be told there is no model, not
5270    /// quietly served by a checkpoint the operator dropped.
5271    #[tokio::test]
5272    async fn unloading_answers_503_instead_of_serving_the_dropped_model() {
5273        let state = Arc::new(test_state(
5274            named_test_model("model-a", 256),
5275            ResponseCache::new(4, Duration::from_secs(60)),
5276        ));
5277        let app = test_app_with_state(Arc::clone(&state));
5278
5279        let (status, body) = post_json_uri(
5280            &app,
5281            frink_api::routes::ADMIN_MODELS_UNLOAD,
5282            serde_json::json!({}),
5283        )
5284        .await;
5285        assert_eq!(status, StatusCode::OK);
5286        assert_eq!(body["ok"], true);
5287        assert!(body["active"].is_null());
5288        assert!(state.active().is_none());
5289
5290        let (status, _) = get_json(&app, frink_api::routes::V1_MODELS).await;
5291        assert_eq!(status, StatusCode::OK);
5292        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5293        assert_eq!(models["data"].as_array().unwrap().len(), 0);
5294
5295        let (status, body) = post_json_uri(
5296            &app,
5297            "/v1/chat/completions",
5298            serde_json::json!({
5299                "model": "x",
5300                "messages": [{"role": "user", "content": "hi"}]
5301            }),
5302        )
5303        .await;
5304        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5305        assert_eq!(body["error"]["type"], "model_not_loaded");
5306    }
5307
5308    /// `/health` must keep answering with nothing loaded -- a supervisor
5309    /// polls it to decide whether to kill the process, and "no model"
5310    /// is not "no server".
5311    #[tokio::test]
5312    async fn health_reports_the_unloaded_state_rather_than_going_silent() {
5313        let state = Arc::new(test_state(
5314            named_test_model("model-a", 256),
5315            ResponseCache::new(4, Duration::from_secs(60)),
5316        ));
5317        let app = test_app_with_state(Arc::clone(&state));
5318        state.swap_active(None);
5319
5320        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
5321        // Not `ready`: a supervisor reading 200 here would route traffic
5322        // that is guaranteed to 503 on arrival.
5323        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5324        assert_eq!(body["state"], "unavailable");
5325        assert_eq!(body["reason"], "model_not_loaded");
5326        assert!(body["model"].is_null());
5327        let real_weights = body["capabilities"]
5328            .as_array()
5329            .unwrap()
5330            .iter()
5331            .find(|c| c["id"] == "real_weights")
5332            .cloned()
5333            .expect("real_weights is always reported");
5334        assert_eq!(real_weights["available"], false);
5335        assert_eq!(real_weights["reason"], "model_not_loaded");
5336    }
5337
5338    /// The API-monitor contract: a finished request lands in the ring
5339    /// buffer keyed by the id the response carried, with the two
5340    /// durations reported separately.
5341    #[tokio::test]
5342    async fn a_finished_request_lands_in_the_stats_ring_with_both_durations() {
5343        let app = test_app();
5344
5345        let (status, completion) = post_json_uri(
5346            &app,
5347            "/v1/chat/completions",
5348            serde_json::json!({
5349                "model": "x",
5350                "messages": [{"role": "user", "content": "hi"}],
5351                "max_tokens": 4
5352            }),
5353        )
5354        .await;
5355        assert_eq!(status, StatusCode::OK);
5356        let request_id = completion["request_id"].as_str().unwrap().to_string();
5357
5358        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5359        assert_eq!(status, StatusCode::OK);
5360        let recent = stats["recent"].as_array().unwrap();
5361        assert_eq!(recent.len(), 1);
5362        let row = &recent[0];
5363        assert_eq!(row["request_id"], request_id);
5364        assert_eq!(row["route"], frink_api::routes::V1_CHAT_COMPLETIONS);
5365        assert_eq!(row["status"], 200);
5366        assert_eq!(row["stream"], false);
5367        // Separate fields, and the decode phase is a real measurement
5368        // rather than a copy of the total.
5369        assert!(row["duration_ms"].is_number());
5370        assert!(row["decode_ms"].is_number());
5371        assert!(stats["tokens_generated_total"].as_u64().unwrap() > 0);
5372        assert_eq!(
5373            stats["tokens_prompt_total"].as_u64().unwrap(),
5374            row["prompt_tokens"].as_u64().unwrap()
5375        );
5376    }
5377
5378    /// A rejected request is still a request the monitor should show;
5379    /// otherwise the screen quietly omits exactly the traffic someone
5380    /// is debugging.
5381    #[tokio::test]
5382    async fn a_rejected_request_is_recorded_too() {
5383        let state = Arc::new(test_state(
5384            named_test_model("model-a", 256),
5385            ResponseCache::new(4, Duration::from_secs(60)),
5386        ));
5387        let app = test_app_with_state(Arc::clone(&state));
5388        state.swap_active(None);
5389
5390        let (status, _) = post_json_uri(
5391            &app,
5392            "/v1/chat/completions",
5393            serde_json::json!({"model": "x", "messages": [{"role": "user", "content": "hi"}]}),
5394        )
5395        .await;
5396        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5397
5398        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5399        let recent = stats["recent"].as_array().unwrap();
5400        assert_eq!(recent.len(), 1);
5401        assert_eq!(recent[0]["status"], 503);
5402        assert_eq!(recent[0]["completion_tokens"], 0);
5403        assert!(recent[0]["decode_ms"].is_null());
5404        assert_eq!(stats["errors_total"], 1);
5405    }
5406
5407    /// POSTs with caller-supplied headers, so the attribution tests
5408    /// exercise the same header parsing a real client's request goes
5409    /// through rather than calling `Attribution::from_headers` twice.
5410    async fn post_json_with_headers(
5411        app: &Router,
5412        uri: &str,
5413        body: serde_json::Value,
5414        headers: &[(&str, &str)],
5415    ) -> (StatusCode, serde_json::Value) {
5416        use http_body_util::BodyExt;
5417        use tower::ServiceExt;
5418
5419        let mut builder = axum::http::Request::builder()
5420            .method("POST")
5421            .uri(uri)
5422            .header("content-type", "application/json");
5423        for (name, value) in headers {
5424            builder = builder.header(*name, *value);
5425        }
5426        let response = app
5427            .clone()
5428            .oneshot(
5429                builder
5430                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5431                    .unwrap(),
5432            )
5433            .await
5434            .unwrap();
5435        let status = response.status();
5436        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5437        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
5438        (status, json)
5439    }
5440
5441    /// The three small endpoints used to be served and never recorded,
5442    /// which made the monitor wrong rather than incomplete: an editor
5443    /// hammering `/v1/embeddings` showed up as an idle server.
5444    #[tokio::test]
5445    async fn tokenize_detokenize_and_embeddings_all_land_in_the_ring() {
5446        let app = test_app();
5447
5448        let (status, _) = post_json_uri(
5449            &app,
5450            frink_api::routes::V1_TOKENIZE,
5451            serde_json::json!({"prompt": "hello"}),
5452        )
5453        .await;
5454        assert_eq!(status, StatusCode::OK);
5455        let (status, _) = post_json_uri(
5456            &app,
5457            frink_api::routes::V1_DETOKENIZE,
5458            serde_json::json!({"tokens": [104, 105]}),
5459        )
5460        .await;
5461        assert_eq!(status, StatusCode::OK);
5462        let (status, _) = post_json_uri(
5463            &app,
5464            frink_api::routes::V1_EMBEDDINGS,
5465            serde_json::json!({"input": "hello"}),
5466        )
5467        .await;
5468        assert_eq!(status, StatusCode::OK);
5469
5470        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5471        let routes: Vec<&str> = stats["recent"]
5472            .as_array()
5473            .unwrap()
5474            .iter()
5475            .map(|row| row["route"].as_str().unwrap())
5476            .collect();
5477        for expected in [
5478            frink_api::routes::V1_TOKENIZE,
5479            frink_api::routes::V1_DETOKENIZE,
5480            frink_api::routes::V1_EMBEDDINGS,
5481        ] {
5482            assert!(
5483                routes.contains(&expected),
5484                "{expected} is missing: {routes:?}"
5485            );
5486        }
5487
5488        let row = |route: &str| {
5489            stats["recent"]
5490                .as_array()
5491                .unwrap()
5492                .iter()
5493                .find(|r| r["route"] == route)
5494                .cloned()
5495                .unwrap()
5496        };
5497        // Embeddings run a forward pass, so their prompt tokens are
5498        // real prompt tokens. There is no decode loop, so `decode_ms`
5499        // stays null instead of borrowing the total.
5500        let embed = row(frink_api::routes::V1_EMBEDDINGS);
5501        assert!(embed["prompt_tokens"].as_u64().unwrap() > 0);
5502        assert!(embed["decode_ms"].is_null());
5503        assert_eq!(embed["completion_tokens"], 0);
5504        // Tokenizing runs the tokenizer and not the model, so it
5505        // contributes nothing to the token counters those counters
5506        // claim to measure.
5507        assert_eq!(row(frink_api::routes::V1_TOKENIZE)["prompt_tokens"], 0);
5508        assert_eq!(
5509            stats["tokens_prompt_total"].as_u64().unwrap(),
5510            embed["prompt_tokens"].as_u64().unwrap(),
5511            "only the forward pass counted"
5512        );
5513    }
5514
5515    /// A router over a model that is NOT flagged synthetic, so the
5516    /// decode loop actually emits chunks: `run_generation_emit`
5517    /// suppresses `emit` for a synthetic model, and a streaming test
5518    /// against one would see only the terminal frame.
5519    fn streaming_test_app() -> Router {
5520        let mut cfg = test_dense_fixture();
5521        cfg.vocab_size = 256;
5522        let model = Model::Gguf(GgufModel {
5523            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5524            tokenizer: Arc::new(ServerTokenizer::Byte),
5525            stop_tokens: StopTokens::default(),
5526            bos_id: None,
5527            is_synthetic: false,
5528            chat_template: chat_template::PromptTemplate::plain(),
5529        });
5530        test_app_with_state(Arc::new(test_state(
5531            model,
5532            ResponseCache::new(1000, Duration::from_secs(3600)),
5533        )))
5534    }
5535
5536    /// llama.cpp's native endpoint is a different WIRE, not a shorter
5537    /// path to the OpenAI one. If this ever starts answering `choices`,
5538    /// every llama.cpp client reading `content` breaks silently.
5539    /// Chat logprobs: the CHAT shape (`content[]` with `token`,
5540    /// `logprob`, `bytes` and a nested `top_logprobs`), not the
5541    /// completions wire's parallel arrays, and a request that asks for
5542    /// them must MISS the response cache -- which stores text and
5543    /// finish reasons, never distributions.
5544    #[tokio::test]
5545    async fn chat_logprobs_are_rendered_and_are_never_served_from_cache() {
5546        let app = test_app();
5547        let body = |logprobs: Option<(bool, Option<u32>)>| {
5548            let mut b = serde_json::json!({
5549                "model": "x",
5550                "messages": [{"role": "user", "content": "hi"}],
5551                "max_tokens": 4
5552            });
5553            if let Some((on, top)) = logprobs {
5554                b["logprobs"] = serde_json::json!(on);
5555                if let Some(n) = top {
5556                    b["top_logprobs"] = serde_json::json!(n);
5557                }
5558            }
5559            b
5560        };
5561
5562        // Without: absent, not an empty object.
5563        let (status, plain) =
5564            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(None)).await;
5565        assert_eq!(status, StatusCode::OK, "{plain}");
5566        assert!(plain["choices"][0]["logprobs"].is_null(), "{plain}");
5567
5568        // With: the chat object, and never a cache hit -- twice in a
5569        // row, because the second is exactly when a cacheable request
5570        // would replay.
5571        for attempt in 0..2 {
5572            let (status, with) = post_json_uri(
5573                &app,
5574                frink_api::routes::V1_CHAT_COMPLETIONS,
5575                body(Some((true, Some(2)))),
5576            )
5577            .await;
5578            assert_eq!(status, StatusCode::OK, "{with}");
5579            assert_ne!(
5580                with["frink_cache"], "hit",
5581                "attempt {attempt} replayed a cached answer for a logprobs request: {with}"
5582            );
5583            let lp = &with["choices"][0]["logprobs"];
5584            assert!(lp.is_object(), "attempt {attempt}: {with}");
5585            let content = lp["content"].as_array().expect("content");
5586            // It is the CHAT shape, so there are no parallel arrays.
5587            assert!(lp["tokens"].is_null(), "completions shape leaked: {lp}");
5588            for entry in content {
5589                assert!(entry["token"].is_string(), "{entry}");
5590                assert!(entry["bytes"].is_array(), "{entry}");
5591                let v = entry["logprob"].as_f64().expect("a real number");
5592                assert!(v <= 0.0 && v.is_finite(), "{entry}");
5593                let top = entry["top_logprobs"].as_array().expect("top_logprobs");
5594                assert!(top.len() <= 2, "asked for 2, got {}", top.len());
5595            }
5596        }
5597    }
5598
5599    /// `top_logprobs` without `logprobs: true` is not a valid request
5600    /// upstream, and is refused here rather than read as an implied
5601    /// `true` -- guessing which of two fields the caller meant is how
5602    /// a server answers a question nobody asked. A count above the cap
5603    /// is a 400 on the VALUE, not a 501 on the field.
5604    #[tokio::test]
5605    async fn the_chat_logprobs_pair_is_validated() {
5606        let app = test_app();
5607        for (extra, why) in [
5608            (serde_json::json!({"top_logprobs": 3}), "without logprobs"),
5609            (
5610                serde_json::json!({"logprobs": true, "top_logprobs": 21}),
5611                "above the cap",
5612            ),
5613        ] {
5614            let mut body = serde_json::json!({
5615                "model": "x",
5616                "messages": [{"role": "user", "content": "hi"}],
5617                "max_tokens": 2
5618            });
5619            for (k, v) in extra.as_object().unwrap() {
5620                body[k] = v.clone();
5621            }
5622            let (status, answer) =
5623                post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await;
5624            assert_eq!(status, StatusCode::BAD_REQUEST, "{why}: {answer}");
5625            assert!(
5626                answer["error"]["message"]
5627                    .as_str()
5628                    .is_some_and(|m| m.contains("top_logprobs")),
5629                "{why}: {answer}"
5630            );
5631        }
5632    }
5633
5634    /// **Sleep refuses a model it could not bring back.**
5635    ///
5636    /// A checkpoint with no path on record -- the synthetic fixture,
5637    /// and any model loaded from something this server cannot replay
5638    /// -- would be a one-way door dressed as a round trip. Refusing is
5639    /// the honest answer, and the test server is exactly that case,
5640    /// which is why the state machine below is driven over a state
5641    /// carrying a path instead.
5642    #[tokio::test]
5643    async fn sleep_refuses_a_model_it_could_not_bring_back() {
5644        let app = test_app();
5645        let (status, answer) =
5646            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5647        assert_eq!(status, StatusCode::CONFLICT, "{answer}");
5648        assert_eq!(answer["error"]["type"], "not_reloadable", "{answer}");
5649        // And it stays awake: a refused sleep must not leave the server
5650        // in a state where nothing is loaded.
5651        let (_, still) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5652        assert_eq!(still["is_sleeping"], false, "{still}");
5653        let (status, _) = post_json_uri(
5654            &app,
5655            frink_api::routes::V1_CHAT_COMPLETIONS,
5656            serde_json::json!({
5657                "model": "x",
5658                "messages": [{"role": "user", "content": "hi"}],
5659                "max_tokens": 2
5660            }),
5661        )
5662        .await;
5663        assert_eq!(status, StatusCode::OK, "a refused sleep unloaded the model");
5664    }
5665
5666    /// **Sleep is an unload that REMEMBERS**, and that is the whole
5667    /// difference from `/admin/models/unload`: a slept server can wake
5668    /// itself, where an unloaded one needs a client that knows the id.
5669    ///
5670    /// The state a caller can observe is pinned end to end: asleep is
5671    /// reported by `GET /is_sleeping`, a generation refused while
5672    /// asleep says so with its own error `type` rather than
5673    /// `model_not_loaded`, and sleeping twice is not an error.
5674    #[tokio::test]
5675    async fn sleep_remembers_what_unload_forgets() {
5676        // A path on record is what makes a model sleepable; the plain
5677        // fixture has none and `sleep` refuses that case above.
5678        let state = Arc::new(test_state_at(
5679            test_model_full_byte_vocab(),
5680            ResponseCache::new(1000, Duration::from_secs(3600)),
5681            Some(std::path::PathBuf::from("/nonexistent/fixture.gguf")),
5682        ));
5683        let app = test_app_with_state(Arc::clone(&state));
5684        let ask = || {
5685            let app = app.clone();
5686            async move {
5687                post_json_uri(
5688                    &app,
5689                    frink_api::routes::V1_CHAT_COMPLETIONS,
5690                    serde_json::json!({
5691                        "model": "x",
5692                        "messages": [{"role": "user", "content": "hi"}],
5693                        "max_tokens": 2
5694                    }),
5695                )
5696                .await
5697            }
5698        };
5699
5700        let (status, _) = ask().await;
5701        assert_eq!(status, StatusCode::OK, "the fixture server serves");
5702        let (_, awake) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5703        assert_eq!(awake["is_sleeping"], false, "{awake}");
5704
5705        let (status, slept) =
5706            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5707        assert_eq!(status, StatusCode::OK, "{slept}");
5708        assert_eq!(slept["is_sleeping"], true, "{slept}");
5709        let (_, now) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5710        assert_eq!(now["is_sleeping"], true, "{now}");
5711
5712        // A generation while asleep names the state, so a client can
5713        // tell "wake me" from "load something".
5714        let (status, refused) = ask().await;
5715        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{refused}");
5716        assert_eq!(
5717            refused["error"]["type"], "server_sleeping",
5718            "an asleep server reported itself as empty: {refused}"
5719        );
5720
5721        // Sleeping twice is not an error and must not lose the record.
5722        let (status, again) =
5723            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5724        assert_eq!(status, StatusCode::OK, "{again}");
5725        assert_eq!(again["is_sleeping"], true, "{again}");
5726    }
5727
5728    /// Waking a server that is not asleep is a conflict rather than a
5729    /// silent no-op: a scheduler that lost track of the state should
5730    /// find out, not be told everything is fine.
5731    #[tokio::test]
5732    async fn waking_a_server_that_is_awake_is_refused() {
5733        let app = test_app();
5734        let (status, answer) =
5735            post_json_uri(&app, frink_api::routes::WAKE_UP, serde_json::json!({})).await;
5736        assert_eq!(status, StatusCode::CONFLICT, "{answer}");
5737        assert_eq!(answer["error"]["type"], "not_sleeping", "{answer}");
5738    }
5739
5740    /// **`cache_salt` isolates one caller's cached prefixes from
5741    /// another's**, end to end: two requests with the same prompt and
5742    /// different salts must not be served each other's answer.
5743    ///
5744    /// The response cache is the visible half -- a hit is reported in
5745    /// `frink_cache`, so a leak is observable from the wire.
5746    #[tokio::test]
5747    async fn a_salt_keeps_one_callers_cached_answer_from_another() {
5748        let app = test_app();
5749        let body = |salt: Option<&str>| {
5750            let mut b = serde_json::json!({
5751                "model": "x",
5752                "messages": [{"role": "user", "content": "the same prompt"}],
5753                "max_tokens": 4,
5754                "seed": 1
5755            });
5756            if let Some(s) = salt {
5757                b["cache_salt"] = serde_json::json!(s);
5758            }
5759            b
5760        };
5761        let post = |b: serde_json::Value| {
5762            let app = app.clone();
5763            async move { post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, b).await }
5764        };
5765
5766        // Caller A warms the cache, then hits it.
5767        let (status, _) = post(body(Some("tenant-a"))).await;
5768        assert_eq!(status, StatusCode::OK);
5769        let (_, again) = post(body(Some("tenant-a"))).await;
5770        assert_eq!(
5771            again["frink_cache"], "hit",
5772            "the owner did not get its own entry back: {again}"
5773        );
5774
5775        // Caller B, same prompt, must NOT.
5776        let (_, other) = post(body(Some("tenant-b"))).await;
5777        assert_ne!(
5778            other["frink_cache"], "hit",
5779            "a different caller was served tenant-a's answer: {other}"
5780        );
5781
5782        // And the shared namespace is its own too.
5783        let (_, shared) = post(body(None)).await;
5784        assert_ne!(
5785            shared["frink_cache"], "hit",
5786            "an unsalted request was served a salted answer: {shared}"
5787        );
5788    }
5789
5790    /// `n` on the chat route: several choices from one prefill, each
5791    /// parsed for tool calls and reasoning in its own right.
5792    #[tokio::test]
5793    async fn chat_serves_several_choices_from_one_prefill() {
5794        let app = test_app();
5795        let body = |n: u32, stream: bool| {
5796            serde_json::json!({
5797                "model": "x",
5798                "messages": [{"role": "user", "content": "hi"}],
5799                "max_tokens": 4,
5800                "temperature": 1.0,
5801                "n": n,
5802                "stream": stream
5803            })
5804        };
5805
5806        let (status, one) =
5807            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(1, false)).await;
5808        assert_eq!(status, StatusCode::OK, "{one}");
5809
5810        let (status, three) =
5811            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(3, false)).await;
5812        assert_eq!(status, StatusCode::OK, "{three}");
5813        let choices = three["choices"].as_array().expect("an array");
5814        assert_eq!(choices.len(), 3, "{three}");
5815        for (i, c) in choices.iter().enumerate() {
5816            assert_eq!(c["index"], i);
5817            assert!(c["message"]["role"].is_string(), "{c}");
5818            assert!(c["finish_reason"].is_string(), "{c}");
5819        }
5820        // One prompt, billed once: the prefill was shared.
5821        assert_eq!(
5822            three["usage"]["prompt_tokens"], one["usage"]["prompt_tokens"],
5823            "n = 3 billed the prompt more than once"
5824        );
5825    }
5826
5827    /// **A streamed `n` INTERLEAVES its choices.**
5828    ///
5829    /// The property the route refused for, and the only one that says
5830    /// the schedule is right: a client reading `choices[].index` is
5831    /// handed the choices together. Emitting choice 0 to its end and
5832    /// then choice 1 would satisfy "three indices appear" and satisfy
5833    /// nothing else, so what is asserted is that the FIRST chunk of
5834    /// choice 2 arrives before the LAST chunk of choice 0.
5835    ///
5836    /// Also pinned: exactly one terminal chunk per choice, and exactly
5837    /// one usage block for the request.
5838    #[tokio::test]
5839    async fn a_streamed_n_interleaves_its_choices() {
5840        let app = streaming_test_app();
5841        let raw = post_sse_raw(
5842            &app,
5843            serde_json::json!({
5844                "model": "x",
5845                "messages": [{"role": "user", "content": "hi"}],
5846                "max_tokens": 6,
5847                "temperature": 1.0,
5848                "n": 3,
5849                "stream": true
5850            }),
5851        )
5852        .await;
5853
5854        // The index carried by each chunk, in wire order.
5855        let mut order: Vec<usize> = Vec::new();
5856        let mut finished: Vec<usize> = Vec::new();
5857        let mut usage_blocks = 0usize;
5858        for line in raw.lines() {
5859            let Some(rest) = line.strip_prefix("data: ") else {
5860                continue;
5861            };
5862            if rest.trim() == "[DONE]" {
5863                continue;
5864            }
5865            let v: serde_json::Value = serde_json::from_str(rest).expect(rest);
5866            if v.get("usage").is_some_and(|u| !u.is_null()) {
5867                usage_blocks += 1;
5868            }
5869            let Some(choice) = v["choices"].as_array().and_then(|c| c.first()) else {
5870                continue;
5871            };
5872            let index = choice["index"].as_u64().expect("an index") as usize;
5873            if choice["finish_reason"].is_string() {
5874                finished.push(index);
5875                continue;
5876            }
5877            order.push(index);
5878        }
5879
5880        assert_eq!(
5881            finished,
5882            vec![0, 1, 2],
5883            "one terminal chunk per choice, in index order: {raw}"
5884        );
5885        assert_eq!(usage_blocks, 1, "the usage block is the request's: {raw}");
5886        assert!(
5887            order.contains(&0) && order.contains(&2),
5888            "not every choice streamed: {order:?}"
5889        );
5890        let last_of_zero = order
5891            .iter()
5892            .rposition(|i| *i == 0)
5893            .expect("choice 0 streamed");
5894        let first_of_two = order
5895            .iter()
5896            .position(|i| *i == 2)
5897            .expect("choice 2 streamed");
5898        assert!(
5899            first_of_two < last_of_zero,
5900            "the choices arrived one after another rather than interleaved: {order:?}"
5901        );
5902    }
5903
5904    /// **`echo` returns the prompt and the completion as one string,
5905    /// and the logprobs arrays cover both.**
5906    ///
5907    /// The half that is easy to get wrong is `text_offset`: a client
5908    /// slices `text` with it, so an offset computed over the
5909    /// completion alone points into the middle of the echoed prompt.
5910    /// Checked by SLICING the returned text at each offset and
5911    /// comparing it against the token it names.
5912    #[tokio::test]
5913    async fn echo_returns_the_prompt_with_offsets_that_index_it() {
5914        let app = streaming_test_app();
5915        let prompt = "hello";
5916        let (status, body) = post_json_uri(
5917            &app,
5918            frink_api::routes::V1_COMPLETIONS,
5919            serde_json::json!({
5920                "model": "x",
5921                "prompt": prompt,
5922                "max_tokens": 6,
5923                "temperature": 0,
5924                "echo": true,
5925                "logprobs": 2
5926            }),
5927        )
5928        .await;
5929        assert_eq!(status, StatusCode::OK, "{body}");
5930
5931        let text = body["choices"][0]["text"].as_str().expect("text");
5932        assert!(
5933            text.starts_with(prompt),
5934            "the prompt was not echoed: {text:?}"
5935        );
5936        assert!(
5937            text.len() > prompt.len(),
5938            "nothing was generated after the echo: {text:?}"
5939        );
5940
5941        let lp = &body["choices"][0]["logprobs"];
5942        let tokens = lp["tokens"].as_array().expect("tokens");
5943        let offsets = lp["text_offset"].as_array().expect("text_offset");
5944        let scores = lp["token_logprobs"].as_array().expect("token_logprobs");
5945        assert_eq!(tokens.len(), offsets.len());
5946        assert_eq!(tokens.len(), scores.len());
5947        assert!(
5948            tokens.len() > 6,
5949            "the arrays cover only the completion: {}",
5950            tokens.len()
5951        );
5952        // Nothing predicted the first prompt token.
5953        assert!(scores[0].is_null(), "{lp}");
5954        // Every offset names the token that starts there.
5955        for (i, (tok, off)) in tokens.iter().zip(offsets).enumerate() {
5956            let (piece, at) = (
5957                tok.as_str().expect("a piece"),
5958                off.as_u64().unwrap() as usize,
5959            );
5960            assert!(
5961                text[at..].starts_with(piece),
5962                "entry {i}: offset {at} does not start {piece:?} in {text:?}"
5963            );
5964        }
5965    }
5966
5967    /// **`truncate_prompt_tokens` answers the prompt it kept, and
5968    /// `echo` says so.**
5969    ///
5970    /// The field was the most dangerous refusal in the table because
5971    /// IGNORING it answers a different prompt with no error. Serving
5972    /// it has the mirror risk: echoing the caller's full string after
5973    /// truncating would report a prompt the model never saw. Both are
5974    /// pinned here -- the usage counts the kept tokens, and the echo
5975    /// is the kept tokens.
5976    #[tokio::test]
5977    async fn truncate_prompt_tokens_keeps_the_last_k_and_echo_reports_them() {
5978        let app = streaming_test_app();
5979        let prompt = "abcdefghij";
5980        let ask = |k: Option<u32>| {
5981            let mut b = serde_json::json!({
5982                "model": "x",
5983                "prompt": prompt,
5984                "max_tokens": 2,
5985                "temperature": 0,
5986                "echo": true
5987            });
5988            if let Some(k) = k {
5989                b["truncate_prompt_tokens"] = serde_json::json!(k);
5990            }
5991            b
5992        };
5993
5994        let (status, full) =
5995            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(None)).await;
5996        assert_eq!(status, StatusCode::OK, "{full}");
5997        let full_prompt_tokens = full["usage"]["prompt_tokens"].as_u64().expect("usage");
5998        assert!(full_prompt_tokens > 4, "the prompt is too short to cut");
5999
6000        let (status, cut) =
6001            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(Some(4))).await;
6002        assert_eq!(status, StatusCode::OK, "{cut}");
6003        assert_eq!(
6004            cut["usage"]["prompt_tokens"].as_u64(),
6005            Some(4),
6006            "the prompt was not truncated: {cut}"
6007        );
6008        // A byte tokenizer, so four tokens are the last four bytes.
6009        let text = cut["choices"][0]["text"].as_str().expect("text");
6010        assert!(
6011            text.starts_with("ghij"),
6012            "echo reported a prompt the model never saw: {text:?}"
6013        );
6014        assert!(
6015            !text.starts_with(prompt),
6016            "the full prompt was echoed after a truncation: {text:?}"
6017        );
6018    }
6019
6020    /// Zero and negative counts are a 400: the field IS implemented,
6021    /// and asking to keep none of the prompt is not a request any
6022    /// server can serve.
6023    #[tokio::test]
6024    async fn a_truncation_below_one_is_a_bad_request() {
6025        let app = streaming_test_app();
6026        for k in [0i64, -1] {
6027            let (status, body) = post_json_uri(
6028                &app,
6029                frink_api::routes::V1_COMPLETIONS,
6030                serde_json::json!({
6031                    "model": "x",
6032                    "prompt": "hi",
6033                    "max_tokens": 2,
6034                    "truncate_prompt_tokens": k
6035                }),
6036            )
6037            .await;
6038            assert_eq!(status, StatusCode::BAD_REQUEST, "k = {k}: {body}");
6039        }
6040    }
6041
6042    /// **`allowed_token_ids` restricts what can come back.**
6043    ///
6044    /// Byte tokenizer, so a token id IS a byte and the answer can be
6045    /// read directly: restrict to `A` and `B` and every character of
6046    /// the completion must be one of them. A server that dropped the
6047    /// field answers ordinary text and a 200, which is exactly the
6048    /// failure the refusal existed to avoid.
6049    #[tokio::test]
6050    async fn allowed_token_ids_restricts_the_draw() {
6051        let app = streaming_test_app();
6052        let body = |allowed: Option<serde_json::Value>| {
6053            let mut b = serde_json::json!({
6054                "model": "x",
6055                "prompt": "hi",
6056                "max_tokens": 16,
6057                "temperature": 1.0,
6058                "seed": 3
6059            });
6060            if let Some(ids) = allowed {
6061                b["allowed_token_ids"] = ids;
6062            }
6063            b
6064        };
6065
6066        // Unrestricted first, so the restriction below is measured
6067        // against what this model actually says.
6068        let (status, free) =
6069            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, body(None)).await;
6070        assert_eq!(status, StatusCode::OK, "{free}");
6071        let free_text = free["choices"][0]["text"].as_str().unwrap_or_default();
6072
6073        let (status, restricted) = post_json_uri(
6074            &app,
6075            frink_api::routes::V1_COMPLETIONS,
6076            // 'A' and 'B'.
6077            body(Some(serde_json::json!([65, 66]))),
6078        )
6079        .await;
6080        assert_eq!(status, StatusCode::OK, "{restricted}");
6081        let text = restricted["choices"][0]["text"]
6082            .as_str()
6083            .unwrap_or_default();
6084        assert!(!text.is_empty(), "nothing was generated: {restricted}");
6085        assert!(
6086            text.chars().all(|c| c == 'A' || c == 'B'),
6087            "a token outside `allowed_token_ids` was drawn: {text:?}"
6088        );
6089        // The premise: an unrestricted draw is not already all As and
6090        // Bs, or the assertion above holds for free.
6091        assert!(
6092            !free_text.chars().all(|c| c == 'A' || c == 'B'),
6093            "the unrestricted answer was already inside the allowed set: {free_text:?}"
6094        );
6095    }
6096
6097    /// **An empty `allowed_token_ids` is a 400, not a 501.**
6098    ///
6099    /// The field IS implemented; asking to draw from nothing is not a
6100    /// request any server can serve, and honouring it would produce a
6101    /// row of `-inf` and a token that is an artefact of argmax over
6102    /// negative infinity.
6103    #[tokio::test]
6104    async fn an_empty_allowed_token_ids_is_a_bad_request() {
6105        let app = streaming_test_app();
6106        let (status, body) = post_json_uri(
6107            &app,
6108            frink_api::routes::V1_COMPLETIONS,
6109            serde_json::json!({
6110                "model": "x",
6111                "prompt": "hi",
6112                "max_tokens": 4,
6113                "allowed_token_ids": []
6114            }),
6115        )
6116        .await;
6117        assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
6118        assert!(
6119            body["error"]["message"]
6120                .as_str()
6121                .unwrap_or_default()
6122                .contains("allowed_token_ids"),
6123            "{body}"
6124        );
6125    }
6126
6127    /// **`bad_words` steers around a token without ending the answer.**
6128    ///
6129    /// The distinction from `stop`, stated as behaviour: the forbidden
6130    /// byte must not appear, AND the generation must run to its budget
6131    /// rather than stopping the first time the model wanted it.
6132    #[tokio::test]
6133    async fn bad_words_removes_a_token_without_ending_the_generation() {
6134        let app = streaming_test_app();
6135        let ask = |bad: Option<serde_json::Value>| {
6136            let mut b = serde_json::json!({
6137                "model": "x",
6138                "prompt": "hi",
6139                "max_tokens": 24,
6140                "temperature": 1.0,
6141                "seed": 11
6142            });
6143            if let Some(words) = bad {
6144                b["bad_words"] = words;
6145            }
6146            b
6147        };
6148
6149        let (status, free) =
6150            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(None)).await;
6151        assert_eq!(status, StatusCode::OK, "{free}");
6152        let free_text = free["choices"][0]["text"]
6153            .as_str()
6154            .unwrap_or_default()
6155            .to_string();
6156        // Forbid a character the unrestricted answer really produced,
6157        // or the test proves nothing.
6158        let target = free_text
6159            .chars()
6160            .find(|c| c.is_ascii() && !c.is_control())
6161            .expect("the model produced some ascii");
6162
6163        let (status, steered) = post_json_uri(
6164            &app,
6165            frink_api::routes::V1_COMPLETIONS,
6166            ask(Some(serde_json::json!([target.to_string()]))),
6167        )
6168        .await;
6169        assert_eq!(status, StatusCode::OK, "{steered}");
6170        let text = steered["choices"][0]["text"].as_str().unwrap_or_default();
6171        assert!(
6172            !text.contains(target),
6173            "the forbidden {target:?} came back anyway: {text:?}"
6174        );
6175        // Steered, not stopped: `stop` would have ended the answer at
6176        // the first occurrence.
6177        assert_eq!(
6178            steered["usage"]["completion_tokens"], free["usage"]["completion_tokens"],
6179            "the generation ended early, so `bad_words` acted like `stop`: {steered}"
6180        );
6181    }
6182
6183    /// The three generation routes must agree about every field this
6184    /// server does not implement. They did not: `n: 3` was a 501 on
6185    /// `/v1/chat/completions` and a 200 on `/v1/completions`, measured
6186    /// on a running server, because the chat route hand-wrote its own
6187    /// check and the other two never learned it.
6188    ///
6189    /// This is the test that would have caught that, and it is driven
6190    /// from one list so a field added to `unimplemented_fields` is
6191    /// checked on all three wires at once.
6192    #[tokio::test]
6193    async fn every_route_refuses_the_same_unimplemented_fields() {
6194        let app = test_app();
6195        let fields = [
6196            ("n", serde_json::json!(3)),
6197            ("best_of", serde_json::json!(2)),
6198            ("prompt_logprobs", serde_json::json!(1)),
6199            ("echo", serde_json::json!(true)),
6200            ("use_beam_search", serde_json::json!(true)),
6201            ("truncate_prompt_tokens", serde_json::json!(8)),
6202            ("prompt_embeds", serde_json::json!("AA==")),
6203            ("skip_special_tokens", serde_json::json!(false)),
6204            ("return_tokens_as_token_ids", serde_json::json!(true)),
6205        ];
6206        for (field, value) in fields {
6207            for (uri, base) in [
6208                (
6209                    frink_api::routes::V1_CHAT_COMPLETIONS,
6210                    serde_json::json!({
6211                        "model": "x",
6212                        "messages": [{"role": "user", "content": "hi"}],
6213                        "max_tokens": 2
6214                    }),
6215                ),
6216                (
6217                    frink_api::routes::V1_COMPLETIONS,
6218                    serde_json::json!({"prompt": "hi", "max_tokens": 2}),
6219                ),
6220                (
6221                    frink_api::routes::COMPLETION,
6222                    serde_json::json!({"prompt": "hi", "n_predict": 2}),
6223                ),
6224            ] {
6225                let mut body = base;
6226                body[field] = value.clone();
6227                // `n` is SERVED where the response has a `choices`
6228                // array to carry the answers, which is the one
6229                // per-route exception in the table
6230                // (`unimplemented_fields::SERVES_SEVERAL_CHOICES`).
6231                // `prompt_logprobs` is served on the one wire with a
6232                // field for it, and is not a choices-array question.
6233                if field == "prompt_logprobs" && uri == frink_api::routes::V1_COMPLETIONS {
6234                    let (status, answer) = post_json_uri(&app, uri, body).await;
6235                    assert_eq!(status, StatusCode::OK, "{uri} refused it: {answer}");
6236                    assert!(
6237                        answer["prompt_logprobs"].is_array(),
6238                        "served without the field: {answer}"
6239                    );
6240                    continue;
6241                }
6242                // `echo` is served on the one wire that returns a
6243                // continuation of the prompt, and refused on the two
6244                // that return a message.
6245                if field == "echo" && uri == frink_api::routes::V1_COMPLETIONS {
6246                    let (status, answer) = post_json_uri(&app, uri, body).await;
6247                    assert_eq!(status, StatusCode::OK, "{uri} refused `echo`: {answer}");
6248                    assert!(
6249                        answer["choices"][0]["text"]
6250                            .as_str()
6251                            .unwrap_or_default()
6252                            .starts_with("hi"),
6253                        "served without echoing the prompt: {answer}"
6254                    );
6255                    continue;
6256                }
6257                // `truncate_prompt_tokens` is served on every wire that
6258                // tokenizes a prompt here, which is all three.
6259                if field == "truncate_prompt_tokens" {
6260                    let (status, answer) = post_json_uri(&app, uri, body).await;
6261                    assert_eq!(
6262                        status,
6263                        StatusCode::OK,
6264                        "{uri} refused `truncate_prompt_tokens`: {answer}"
6265                    );
6266                    continue;
6267                }
6268                if (field == "n" || field == "best_of")
6269                    && (uri == frink_api::routes::V1_COMPLETIONS
6270                        || uri == frink_api::routes::V1_CHAT_COMPLETIONS)
6271                {
6272                    let (status, answer) = post_json_uri(&app, uri, body).await;
6273                    assert_eq!(
6274                        status,
6275                        StatusCode::OK,
6276                        "{uri} refused a served `{field}`: {answer}"
6277                    );
6278                    // `n: 3` returns three; `best_of: 2` generates two
6279                    // and returns the best ONE, which is the whole
6280                    // difference between the two fields.
6281                    let want = if field == "n" { 3 } else { 1 };
6282                    assert_eq!(
6283                        answer["choices"].as_array().map(Vec::len),
6284                        Some(want),
6285                        "{field}: {answer}"
6286                    );
6287                    continue;
6288                }
6289                let (status, answer) = post_json_uri(&app, uri, body).await;
6290                assert_eq!(
6291                    status,
6292                    StatusCode::NOT_IMPLEMENTED,
6293                    "{uri} served `{field}` instead of refusing it: {answer}"
6294                );
6295                assert!(
6296                    answer["error"]["message"]
6297                        .as_str()
6298                        .is_some_and(|m| m.contains(field)),
6299                    "{uri} refused `{field}` without naming it: {answer}"
6300                );
6301            }
6302        }
6303    }
6304
6305    #[tokio::test]
6306    async fn the_native_completion_wire_is_not_the_openai_one() {
6307        let app = test_app();
6308
6309        let (status, native) = post_json_uri(
6310            &app,
6311            frink_api::routes::COMPLETION,
6312            serde_json::json!({"prompt": "hi", "n_predict": 4}),
6313        )
6314        .await;
6315        assert_eq!(status, StatusCode::OK, "{native}");
6316        assert!(native["content"].is_string(), "{native}");
6317        assert_eq!(native["stop"], true);
6318        assert_eq!(native["stop_type"], "limit");
6319        assert_eq!(native["stopping_word"], "");
6320        assert_eq!(native["truncated"], false);
6321        assert_eq!(native["id_slot"], -1);
6322        assert!(native["timings"]["prompt_n"].is_number(), "{native}");
6323        assert!(native["generation_settings"]["n_predict"] == 4, "{native}");
6324        assert!(
6325            native.get("choices").is_none(),
6326            "the native shape has no `choices`: {native}"
6327        );
6328
6329        let (status, openai) = post_json_uri(
6330            &app,
6331            frink_api::routes::V1_COMPLETIONS,
6332            serde_json::json!({"prompt": "hi", "max_tokens": 4}),
6333        )
6334        .await;
6335        assert_eq!(status, StatusCode::OK);
6336        assert!(openai["choices"][0]["text"].is_string(), "{openai}");
6337        assert!(
6338            openai.get("content").is_none(),
6339            "the OpenAI shape has no top-level `content`: {openai}"
6340        );
6341    }
6342
6343    /// llama.cpp mounts the native endpoint under both spellings
6344    /// (`server.cpp:240-241`), and its own web UI uses the plural. One
6345    /// handler, so the two cannot answer differently.
6346    #[tokio::test]
6347    async fn both_native_spellings_reach_the_same_handler() {
6348        let app = test_app();
6349        for route in [
6350            frink_api::routes::COMPLETION,
6351            frink_api::routes::COMPLETIONS,
6352        ] {
6353            let (status, body) = post_json_uri(
6354                &app,
6355                route,
6356                serde_json::json!({"prompt": "hi", "n_predict": 2, "seed": 1}),
6357            )
6358            .await;
6359            assert_eq!(status, StatusCode::OK, "{route}: {body}");
6360            assert_eq!(body["stop"], true, "{route}");
6361            assert!(body["content"].is_string(), "{route}");
6362        }
6363
6364        // And the ring records which one was called, so the split
6365        // between clients stays visible.
6366        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6367        let routes: Vec<&str> = stats["recent"]
6368            .as_array()
6369            .unwrap()
6370            .iter()
6371            .map(|row| row["route"].as_str().unwrap())
6372            .collect();
6373        assert!(
6374            routes.contains(&frink_api::routes::COMPLETION),
6375            "{routes:?}"
6376        );
6377        assert!(
6378            routes.contains(&frink_api::routes::COMPLETIONS),
6379            "{routes:?}"
6380        );
6381    }
6382
6383    /// The native stream is not OpenAI's. Frames are bare objects with
6384    /// `content` and `stop`, the last one carries `stop: true` and the
6385    /// whole terminal body, and there is **no `[DONE]`** -- a client
6386    /// waiting for one would hang, and one that got it would try to
6387    /// parse it as JSON.
6388    #[tokio::test]
6389    async fn a_native_stream_ends_on_a_stop_frame_with_no_done_sentinel() {
6390        let app = streaming_test_app();
6391        let raw = post_sse_raw_uri(
6392            &app,
6393            frink_api::routes::COMPLETION,
6394            serde_json::json!({"prompt": "hi", "n_predict": 6, "stream": true, "seed": 7}),
6395        )
6396        .await;
6397
6398        assert!(
6399            !raw.contains("[DONE]"),
6400            "llama.cpp's native stream has no sentinel: {raw}"
6401        );
6402        let frames: Vec<serde_json::Value> = raw
6403            .lines()
6404            .filter_map(|line| line.strip_prefix("data: "))
6405            .map(|json| serde_json::from_str(json).expect("every frame is one JSON object"))
6406            .collect();
6407        assert!(frames.len() >= 2, "expected partials then a final: {raw}");
6408
6409        let (last, partials) = frames.split_last().unwrap();
6410        assert_eq!(last["stop"], true, "the last frame closes the stream");
6411        assert!(last["timings"].is_object(), "{last}");
6412        assert!(last["stop_type"].is_string(), "{last}");
6413        for partial in partials {
6414            assert_eq!(partial["stop"], false, "{partial}");
6415            assert!(partial["content"].is_string(), "{partial}");
6416            // Upstream's documented partial carries content/tokens/stop
6417            // and nothing else; the terminal fields belong to the last
6418            // frame only.
6419            assert!(partial.get("timings").is_none(), "{partial}");
6420            assert!(partial.get("generation_settings").is_none(), "{partial}");
6421        }
6422        // The concatenated partials are the answer, so a client that
6423        // streams sees what a client that buffers would get.
6424        let streamed: String = partials
6425            .iter()
6426            .filter_map(|p| p["content"].as_str())
6427            .collect();
6428        assert_eq!(last["content"].as_str().unwrap(), streamed);
6429    }
6430
6431    /// `n_predict: -1` is llama.cpp's default AND its "until the
6432    /// context is full". With no derived ceiling there is no context to
6433    /// be full of, and quietly substituting a small budget would hand a
6434    /// caller a truncated answer it never asked for.
6435    #[tokio::test]
6436    async fn an_unbounded_n_predict_is_refused_rather_than_quietly_shrunk() {
6437        let app = test_app();
6438        for body in [
6439            serde_json::json!({"prompt": "hi"}),
6440            serde_json::json!({"prompt": "hi", "n_predict": -1}),
6441        ] {
6442            let (status, refusal) =
6443                post_json_uri(&app, frink_api::routes::COMPLETION, body.clone()).await;
6444            assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}: {refusal}");
6445            assert!(
6446                refusal["error"]["message"]
6447                    .as_str()
6448                    .unwrap()
6449                    .contains("n_predict"),
6450                "{refusal}"
6451            );
6452        }
6453        // An explicit budget is served, so the refusal is about the
6454        // unbounded case and not about the endpoint.
6455        let (status, _) = post_json_uri(
6456            &app,
6457            frink_api::routes::COMPLETION,
6458            serde_json::json!({"prompt": "hi", "n_predict": 2}),
6459        )
6460        .await;
6461        assert_eq!(status, StatusCode::OK);
6462    }
6463
6464    /// A caller's `stop` must actually reach the sampler, and be named
6465    /// back in llama.cpp's own vocabulary. Dropping it is the dangerous
6466    /// silent failure: the caller believes generation halts at its
6467    /// sentinel and instead gets the whole budget of text past it.
6468    ///
6469    /// Deterministic without depending on what random weights say:
6470    /// generate once with no stop, then take a character out of that
6471    /// answer and demand the second run halt before it.
6472    #[tokio::test]
6473    async fn a_stop_string_halts_the_answer_and_is_named_back() {
6474        let app = streaming_test_app();
6475        let ask = |stop: serde_json::Value| {
6476            let app = app.clone();
6477            async move {
6478                post_json_uri(
6479                    &app,
6480                    frink_api::routes::COMPLETION,
6481                    serde_json::json!({
6482                        "prompt": "hi",
6483                        "n_predict": 64,
6484                        "ignore_eos": true,
6485                        "stop": stop,
6486                    }),
6487                )
6488                .await
6489                .1
6490            }
6491        };
6492
6493        let baseline = ask(serde_json::json!([])).await;
6494        assert_eq!(baseline["stop_type"], "limit");
6495        assert_eq!(baseline["stopping_word"], "");
6496        let text = baseline["content"].as_str().unwrap().to_string();
6497        // Two characters, so the sentinel is more than one token in
6498        // this vocabulary and goes through the output-suffix layer that
6499        // reports WHICH string matched. A single-token stop is caught
6500        // by the token layer, which does not carry the string back --
6501        // see `stop_type`'s note and docs/API.md.
6502        let sentinel: String = text.chars().skip(1).take(2).collect();
6503        assert_eq!(
6504            sentinel.chars().count(),
6505            2,
6506            "the fixture must produce enough output to cut: {text:?}"
6507        );
6508        let cut = text.find(&sentinel).expect("it came out of this text");
6509
6510        let stopped = ask(serde_json::json!([sentinel])).await;
6511        assert_eq!(stopped["stop_type"], "word", "{stopped}");
6512        assert_eq!(stopped["stopping_word"], sentinel);
6513        assert_eq!(
6514            stopped["content"].as_str().unwrap(),
6515            &text[..cut],
6516            "the answer must be cut at the sentinel, not run past it"
6517        );
6518    }
6519
6520    /// llama.cpp mounts these two unprefixed and sends `content`, not
6521    /// `prompt`. frink mounted only the `/v1/` spelling it invented,
6522    /// so every llama.cpp client got a 404 that named nothing. The
6523    /// alias must reach the SAME handler -- identical ids for identical
6524    /// text -- rather than a second implementation of it.
6525    #[tokio::test]
6526    async fn the_llama_cpp_spelling_of_tokenize_reaches_the_same_handler() {
6527        let app = test_app();
6528
6529        let (v1_status, v1) = post_json_uri(
6530            &app,
6531            frink_api::routes::V1_TOKENIZE,
6532            serde_json::json!({"prompt": "hello"}),
6533        )
6534        .await;
6535        let (alias_status, alias) = post_json_uri(
6536            &app,
6537            frink_api::routes::TOKENIZE,
6538            serde_json::json!({"content": "hello"}),
6539        )
6540        .await;
6541        assert_eq!(v1_status, StatusCode::OK);
6542        assert_eq!(alias_status, StatusCode::OK, "{alias}");
6543        assert_eq!(v1["tokens"], alias["tokens"]);
6544        assert!(!alias["tokens"].as_array().unwrap().is_empty());
6545
6546        // And the reverse: frink's own field still works on llama.cpp's
6547        // path, so a client that switches URLs need not switch dialects.
6548        let (status, both_ways) = post_json_uri(
6549            &app,
6550            frink_api::routes::TOKENIZE,
6551            serde_json::json!({"prompt": "hello"}),
6552        )
6553        .await;
6554        assert_eq!(status, StatusCode::OK);
6555        assert_eq!(both_ways["tokens"], v1["tokens"]);
6556    }
6557
6558    /// llama.cpp answers detokenize under `content`
6559    /// (`server-context.cpp:4970`); frink has always answered under
6560    /// `text`. Both keys carry the same string, so neither dialect's
6561    /// client reads a null.
6562    #[tokio::test]
6563    async fn detokenize_answers_under_both_dialects_keys() {
6564        let app = test_app();
6565        for route in [
6566            frink_api::routes::DETOKENIZE,
6567            frink_api::routes::V1_DETOKENIZE,
6568        ] {
6569            let (status, body) =
6570                post_json_uri(&app, route, serde_json::json!({"tokens": [104, 105]})).await;
6571            assert_eq!(status, StatusCode::OK, "{route}");
6572            assert_eq!(body["text"], "hi", "{route}");
6573            assert_eq!(body["content"], body["text"], "{route}");
6574        }
6575    }
6576
6577    /// The alias is one handler, so the ring must not attribute a
6578    /// llama.cpp client's traffic to the frink spelling: the row
6579    /// carries the path that was actually matched.
6580    #[tokio::test]
6581    async fn the_alias_is_recorded_under_the_path_the_client_called() {
6582        let app = test_app();
6583        let (status, _) = post_json_uri(
6584            &app,
6585            frink_api::routes::TOKENIZE,
6586            serde_json::json!({"content": "hello"}),
6587        )
6588        .await;
6589        assert_eq!(status, StatusCode::OK);
6590
6591        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6592        let routes: Vec<&str> = stats["recent"]
6593            .as_array()
6594            .unwrap()
6595            .iter()
6596            .map(|row| row["route"].as_str().unwrap())
6597            .collect();
6598        assert!(
6599            routes.contains(&frink_api::routes::TOKENIZE),
6600            "the alias must be its own row: {routes:?}"
6601        );
6602        assert!(
6603            !routes.contains(&frink_api::routes::V1_TOKENIZE),
6604            "nothing called /v1/tokenize: {routes:?}"
6605        );
6606    }
6607
6608    /// `add_special` is llama.cpp's "prepend BOS". Honoured, and with
6609    /// the id the generation path itself would prepend -- a tokenize
6610    /// endpoint that disagrees with the decoder about the prompt is
6611    /// worse than one that has no such option.
6612    #[tokio::test]
6613    async fn add_special_prepends_the_same_bos_the_decoder_would() {
6614        let mut cfg = test_dense_fixture();
6615        cfg.vocab_size = 256;
6616        let model = Model::Gguf(GgufModel {
6617            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
6618            tokenizer: Arc::new(ServerTokenizer::Byte),
6619            stop_tokens: StopTokens::default(),
6620            bos_id: Some(7),
6621            is_synthetic: true,
6622            chat_template: chat_template::PromptTemplate::plain(),
6623        });
6624        let app = test_app_with_state(Arc::new(test_state(
6625            model,
6626            ResponseCache::new(1000, Duration::from_secs(3600)),
6627        )));
6628
6629        let (_, plain) = post_json_uri(
6630            &app,
6631            frink_api::routes::TOKENIZE,
6632            serde_json::json!({"content": "hi"}),
6633        )
6634        .await;
6635        let (_, special) = post_json_uri(
6636            &app,
6637            frink_api::routes::TOKENIZE,
6638            serde_json::json!({"content": "hi", "add_special": true}),
6639        )
6640        .await;
6641
6642        assert_eq!(plain["tokens"], serde_json::json!([104, 105]));
6643        assert_eq!(special["tokens"], serde_json::json!([7, 104, 105]));
6644        assert_eq!(special["count"], 3);
6645    }
6646
6647    /// A failed small-endpoint call is still traffic. A 400 that leaves
6648    /// no row is indistinguishable from a request that was never sent.
6649    #[tokio::test]
6650    async fn a_rejected_embeddings_request_is_recorded_with_its_status() {
6651        let app = test_app();
6652        let (status, _) = post_json_uri(
6653            &app,
6654            frink_api::routes::V1_EMBEDDINGS,
6655            serde_json::json!({"input": "hi", "encoding_format": "base64"}),
6656        )
6657        .await;
6658        assert_eq!(status, StatusCode::BAD_REQUEST);
6659
6660        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6661        let recent = stats["recent"].as_array().unwrap();
6662        assert_eq!(recent.len(), 1);
6663        assert_eq!(recent[0]["route"], frink_api::routes::V1_EMBEDDINGS);
6664        assert_eq!(recent[0]["status"], 400);
6665        assert_eq!(
6666            recent[0]["prompt_tokens"], 0,
6667            "a rejected call embedded nothing"
6668        );
6669    }
6670
6671    /// Attribution: which key served a request, and what the caller
6672    /// says it is. The key itself must never appear.
6673    #[tokio::test]
6674    async fn a_row_names_the_key_that_served_it_without_carrying_the_key() {
6675        let app = test_app();
6676        let key = "sk-monitor-secret";
6677        let (status, _) = post_json_with_headers(
6678            &app,
6679            "/v1/chat/completions",
6680            serde_json::json!({
6681                "model": "x",
6682                "messages": [{"role": "user", "content": "hi"}],
6683                "max_tokens": 2
6684            }),
6685            &[
6686                ("authorization", &format!("Bearer {key}")),
6687                ("x-frink-client", "frink-studio"),
6688            ],
6689        )
6690        .await;
6691        assert_eq!(status, StatusCode::OK);
6692
6693        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6694        let row = stats["recent"].as_array().unwrap()[0].clone();
6695        let fingerprint = row["via_api_key"]
6696            .as_str()
6697            .expect("the row names the key that served it")
6698            .to_string();
6699        assert_eq!(fingerprint, attribution::key_fingerprint(key));
6700        assert!(!fingerprint.contains(key));
6701        assert!(
6702            !serde_json::to_string(&stats).unwrap().contains(key),
6703            "the stats payload must not carry the key in any form"
6704        );
6705        assert_eq!(row["client"], "frink-studio");
6706    }
6707
6708    /// Two different keys are two different callers, and no key at all
6709    /// is a third answer -- not a copy of either.
6710    #[tokio::test]
6711    async fn different_keys_are_different_callers_and_no_key_is_null() {
6712        let app = test_app();
6713        let body = serde_json::json!({
6714            "model": "x",
6715            "messages": [{"role": "user", "content": "hi"}],
6716            "max_tokens": 1
6717        });
6718        for headers in [
6719            vec![("authorization", "Bearer key-one")],
6720            vec![("authorization", "Bearer key-two")],
6721            vec![],
6722        ] {
6723            let (status, _) =
6724                post_json_with_headers(&app, "/v1/chat/completions", body.clone(), &headers).await;
6725            assert_eq!(status, StatusCode::OK);
6726        }
6727
6728        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6729        let recent = stats["recent"].as_array().unwrap();
6730        assert_eq!(recent.len(), 3);
6731        let one = recent[0]["via_api_key"].as_str().unwrap();
6732        let two = recent[1]["via_api_key"].as_str().unwrap();
6733        assert_ne!(one, two, "two keys must not collapse into one caller");
6734        assert!(
6735            recent[2]["via_api_key"].is_null(),
6736            "an unauthenticated call is null, not a fingerprint of nothing"
6737        );
6738        assert!(recent[2]["client"].is_null());
6739    }
6740
6741    /// The row names the model that SERVED the request. `req.model` is
6742    /// ignored by this server -- it decodes against whatever is loaded
6743    /// -- so echoing that string back would make the log agree with the
6744    /// caller's belief instead of with what happened.
6745    #[tokio::test]
6746    async fn a_row_names_the_model_that_served_it_not_the_one_requested() {
6747        let state = Arc::new(test_state(
6748            named_test_model("really-loaded", 256),
6749            ResponseCache::new(4, Duration::from_secs(60)),
6750        ));
6751        let app = test_app_with_state(Arc::clone(&state));
6752
6753        let (status, _) = post_json_uri(
6754            &app,
6755            "/v1/chat/completions",
6756            serde_json::json!({
6757                "model": "gpt-4-turbo-that-is-not-here",
6758                "messages": [{"role": "user", "content": "hi"}],
6759                "max_tokens": 2
6760            }),
6761        )
6762        .await;
6763        assert_eq!(status, StatusCode::OK);
6764
6765        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6766        assert_eq!(stats["recent"][0]["model"], "really-loaded");
6767
6768        // Nothing loaded: nothing served it, and the row says so rather
6769        // than repeating what the request asked for.
6770        state.swap_active(None);
6771        let (status, _) = post_json_uri(
6772            &app,
6773            "/v1/chat/completions",
6774            serde_json::json!({
6775                "model": "gpt-4-turbo-that-is-not-here",
6776                "messages": [{"role": "user", "content": "hi"}]
6777            }),
6778        )
6779        .await;
6780        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
6781        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6782        let recent = stats["recent"].as_array().unwrap();
6783        assert!(recent[recent.len() - 1]["model"].is_null());
6784    }
6785
6786    /// A streamed request names its model too, and names the handle it
6787    /// decoded against rather than whatever a swap made current while it
6788    /// was running.
6789    #[tokio::test]
6790    async fn a_streamed_row_names_the_model_it_decoded_against() {
6791        let state = Arc::new(test_state(
6792            named_test_model("model-before", 256),
6793            ResponseCache::new(4, Duration::from_secs(60)),
6794        ));
6795        let app = test_app_with_state(Arc::clone(&state));
6796        let _ = post_sse_raw(&app, resumable_request()).await;
6797        // The stream has finished; a swap now must not rewrite history.
6798        active_model(&state, "model-after");
6799
6800        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6801        assert_eq!(stats["recent"][0]["model"], "model-before");
6802    }
6803
6804    /// The queue gauge reports a queue that exists or says there is
6805    /// none. `0` would claim an empty queue was measured.
6806    #[tokio::test]
6807    async fn the_queue_gauge_is_null_when_nothing_can_queue() {
6808        let app = test_app();
6809        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6810        assert_eq!(status, StatusCode::OK);
6811        assert!(
6812            stats["queue_depth"].is_null(),
6813            "without continuous batching nothing queues, so there is nothing to measure"
6814        );
6815        assert!(stats["queue_rejected_total"].is_null());
6816        assert_eq!(
6817            stats["generating_now"], 0,
6818            "work in progress is measured and really is zero here"
6819        );
6820    }
6821
6822    /// The raw SSE body, so the tests below can assert on the `id:` and
6823    /// `retry:` fields themselves rather than only on the JSON inside
6824    /// `data:`. Those two fields are the whole of the replay contract
6825    /// on the wire.
6826    async fn post_sse_raw(app: &Router, body: serde_json::Value) -> String {
6827        post_sse_raw_uri(app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await
6828    }
6829
6830    /// The same, on any route: `/completion` streams a different
6831    /// protocol over the same transport, and a second copy of this
6832    /// helper would be a second thing to keep in step.
6833    async fn post_sse_raw_uri(app: &Router, uri: &str, body: serde_json::Value) -> String {
6834        use http_body_util::BodyExt;
6835        use tower::ServiceExt;
6836
6837        let response = app
6838            .clone()
6839            .oneshot(
6840                axum::http::Request::builder()
6841                    .method("POST")
6842                    .uri(uri)
6843                    .header("content-type", "application/json")
6844                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
6845                    .unwrap(),
6846            )
6847            .await
6848            .unwrap();
6849        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6850        String::from_utf8(bytes.to_vec()).unwrap()
6851    }
6852
6853    async fn get_json_with_headers(
6854        app: &Router,
6855        uri: &str,
6856        headers: &[(&str, &str)],
6857    ) -> (StatusCode, serde_json::Value) {
6858        use http_body_util::BodyExt;
6859        use tower::ServiceExt;
6860
6861        let mut builder = axum::http::Request::builder().method("GET").uri(uri);
6862        for (name, value) in headers {
6863            builder = builder.header(*name, *value);
6864        }
6865        let response = app
6866            .clone()
6867            .oneshot(builder.body(axum::body::Body::empty()).unwrap())
6868            .await
6869            .unwrap();
6870        let status = response.status();
6871        let bytes = response.into_body().collect().await.unwrap().to_bytes();
6872        (
6873            status,
6874            serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({})),
6875        )
6876    }
6877
6878    fn sse_field<'a>(body: &'a str, field: &str) -> Vec<&'a str> {
6879        body.lines()
6880            .filter_map(|line| line.strip_prefix(field))
6881            .map(str::trim)
6882            .collect()
6883    }
6884
6885    fn resumable_request() -> serde_json::Value {
6886        serde_json::json!({
6887            "model": "m",
6888            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
6889            "max_tokens": 4,
6890            "temperature": 0,
6891            "stream": true,
6892            "stream_resumable": true,
6893        })
6894    }
6895
6896    /// The wire half of the replay contract: every event is numbered,
6897    /// the numbers are qualified by the request so a `Last-Event-ID`
6898    /// cannot be mistaken for a position in another stream, and the
6899    /// reconnect delay is stated once.
6900    #[tokio::test]
6901    async fn a_resumable_stream_numbers_every_event_and_states_retry_once() {
6902        let app = test_app();
6903        let body = post_sse_raw(&app, resumable_request()).await;
6904
6905        let request_id = body
6906            .lines()
6907            .find_map(|l| l.strip_prefix("data: "))
6908            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
6909            .and_then(|v| v["request_id"].as_str().map(str::to_string))
6910            .expect("the first chunk names the request");
6911
6912        let ids = sse_field(&body, "id:");
6913        let datas = sse_field(&body, "data:");
6914        assert_eq!(
6915            ids.len(),
6916            datas.len(),
6917            "every event carries an id, or a reconnect cannot name where it stopped"
6918        );
6919        for (i, id) in ids.iter().enumerate() {
6920            assert_eq!(*id, format!("{request_id}:{i}"));
6921        }
6922        let retries = sse_field(&body, "retry:");
6923        assert_eq!(
6924            retries.len(),
6925            1,
6926            "the reconnect delay is stated once, not on every event"
6927        );
6928        assert_eq!(retries[0], "1500");
6929        assert!(
6930            body.contains("data: [DONE]"),
6931            "the end of stream is still stated"
6932        );
6933    }
6934
6935    /// The refusal this feature was written around: an `id:` with no
6936    /// replay buffer behind it tells a client it may reconnect into
6937    /// something that does not exist.
6938    #[tokio::test]
6939    async fn a_plain_stream_carries_no_id_because_nothing_could_replay_it() {
6940        let app = test_app();
6941        let mut request = resumable_request();
6942        request["stream_resumable"] = serde_json::json!(false);
6943        let body = post_sse_raw(&app, request).await;
6944        assert!(!sse_field(&body, "data:").is_empty(), "it still streams");
6945        assert!(
6946            sse_field(&body, "id:").is_empty(),
6947            "an id promises a replay this stream cannot serve"
6948        );
6949        assert!(sse_field(&body, "retry:").is_empty());
6950    }
6951
6952    /// The polling fallback, which is the answer to the proxy that
6953    /// buffers `text/event-stream`: the same events, over a short JSON
6954    /// response nothing can hold back.
6955    #[tokio::test]
6956    async fn the_polling_fallback_serves_exactly_what_the_stream_delivered() {
6957        let app = test_app();
6958        let body = post_sse_raw(&app, resumable_request()).await;
6959        let request_id = sse_field(&body, "id:")[0]
6960            .rsplit_once(':')
6961            .unwrap()
6962            .0
6963            .to_string();
6964        let streamed: Vec<String> = sse_field(&body, "data:")
6965            .iter()
6966            .map(|d| d.to_string())
6967            .collect();
6968
6969        let (status, polled) = get_json(
6970            &app,
6971            &format!("{}?from=0", frink_api::routes::v1_stream_poll(&request_id)),
6972        )
6973        .await;
6974        assert_eq!(status, StatusCode::OK);
6975        let events: Vec<String> = polled["events"]
6976            .as_array()
6977            .unwrap()
6978            .iter()
6979            .map(|e| e["data"].as_str().unwrap().to_string())
6980            .collect();
6981        assert_eq!(
6982            events, streamed,
6983            "the fallback must deliver the same answer, not a re-run of it"
6984        );
6985        assert_eq!(polled["request_id"], request_id);
6986        assert_eq!(
6987            polled["done"], false,
6988            "events were still being handed out, so the client must ask again"
6989        );
6990
6991        // Drained: only now is it done, so a client that stops on
6992        // `done` never discards events it was not given.
6993        let next = polled["next_index"].as_u64().unwrap();
6994        let (_, drained) = get_json(
6995            &app,
6996            &format!(
6997                "{}?from={next}",
6998                frink_api::routes::v1_stream_poll(&request_id)
6999            ),
7000        )
7001        .await;
7002        assert_eq!(drained["done"], true);
7003        assert_eq!(drained["events"].as_array().unwrap().len(), 0);
7004    }
7005
7006    /// A resume returns what was missed and not what was already
7007    /// rendered -- repeating delivered tokens would make replay worse
7008    /// than starting over.
7009    #[tokio::test]
7010    async fn a_resume_continues_after_the_last_event_id_rather_than_repeating() {
7011        let app = test_app();
7012        let body = post_sse_raw(&app, resumable_request()).await;
7013        let ids = sse_field(&body, "id:");
7014        let datas: Vec<String> = sse_field(&body, "data:")
7015            .iter()
7016            .map(|d| d.to_string())
7017            .collect();
7018        assert!(
7019            ids.len() >= 3,
7020            "need a few events to resume into the middle"
7021        );
7022        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
7023
7024        let (status, resumed) = get_json_with_headers(
7025            &app,
7026            &format!("{}/poll", frink_api::routes::v1_stream(&request_id)),
7027            &[],
7028        )
7029        .await;
7030        assert_eq!(status, StatusCode::OK);
7031        assert_eq!(resumed["events"].as_array().unwrap().len(), datas.len());
7032
7033        // Now from the middle, the way a reconnect would.
7034        let (_, tail) = get_json(
7035            &app,
7036            &format!("{}?from=2", frink_api::routes::v1_stream_poll(&request_id)),
7037        )
7038        .await;
7039        let tail_events: Vec<String> = tail["events"]
7040            .as_array()
7041            .unwrap()
7042            .iter()
7043            .map(|e| e["data"].as_str().unwrap().to_string())
7044            .collect();
7045        assert_eq!(tail_events, datas[2..].to_vec());
7046    }
7047
7048    /// Reconnecting over SSE picks up where the last id left off, with
7049    /// the ids still attached so a second drop can be resumed too.
7050    #[tokio::test]
7051    async fn an_sse_reconnect_resumes_from_the_last_event_id() {
7052        use http_body_util::BodyExt;
7053        use tower::ServiceExt;
7054
7055        let app = test_app();
7056        let body = post_sse_raw(&app, resumable_request()).await;
7057        let ids = sse_field(&body, "id:");
7058        let datas: Vec<String> = sse_field(&body, "data:")
7059            .iter()
7060            .map(|d| d.to_string())
7061            .collect();
7062        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
7063
7064        let response = app
7065            .clone()
7066            .oneshot(
7067                axum::http::Request::builder()
7068                    .method("GET")
7069                    .uri(frink_api::routes::v1_stream(&request_id))
7070                    .header("last-event-id", format!("{request_id}:0"))
7071                    .body(axum::body::Body::empty())
7072                    .unwrap(),
7073            )
7074            .await
7075            .unwrap();
7076        assert_eq!(response.status(), StatusCode::OK);
7077        assert_eq!(
7078            response
7079                .headers()
7080                .get("x-accel-buffering")
7081                .and_then(|v| v.to_str().ok()),
7082            Some("no"),
7083            "the reconnect needs the same anti-buffering header as the stream"
7084        );
7085        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7086        let resumed = String::from_utf8(bytes.to_vec()).unwrap();
7087        assert_eq!(
7088            sse_field(&resumed, "data:")
7089                .iter()
7090                .map(|d| d.to_string())
7091                .collect::<Vec<_>>(),
7092            datas[1..].to_vec()
7093        );
7094        assert_eq!(sse_field(&resumed, "id:")[0], format!("{request_id}:1"));
7095    }
7096
7097    /// A `Last-Event-ID` from another stream is refused rather than
7098    /// rounded down to zero: replaying a whole different answer would
7099    /// be a silent, confident lie.
7100    #[tokio::test]
7101    async fn a_last_event_id_from_another_stream_is_refused() {
7102        let app = test_app();
7103        let body = post_sse_raw(&app, resumable_request()).await;
7104        let request_id = sse_field(&body, "id:")[0]
7105            .rsplit_once(':')
7106            .unwrap()
7107            .0
7108            .to_string();
7109
7110        let (status, err) = get_json_with_headers(
7111            &app,
7112            &frink_api::routes::v1_stream(&request_id),
7113            &[("last-event-id", "chatcmpl-someone-else:3")],
7114        )
7115        .await;
7116        assert_eq!(status, StatusCode::BAD_REQUEST);
7117        assert_eq!(err["error"]["code"], "bad_last_event_id");
7118    }
7119
7120    /// A stream that was never resumable, or has been forgotten, is a
7121    /// 404 that says which -- not an empty stream that reads as an
7122    /// answer with no tokens in it.
7123    #[tokio::test]
7124    async fn resuming_a_stream_that_was_never_resumable_is_a_404_that_says_why() {
7125        let app = test_app();
7126        let mut request = resumable_request();
7127        request["stream_resumable"] = serde_json::json!(false);
7128        let body = post_sse_raw(&app, request).await;
7129        let request_id = body
7130            .lines()
7131            .find_map(|l| l.strip_prefix("data: "))
7132            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
7133            .and_then(|v| v["request_id"].as_str().map(str::to_string))
7134            .unwrap();
7135
7136        let (status, err) = get_json(&app, &frink_api::routes::v1_stream_poll(&request_id)).await;
7137        assert_eq!(status, StatusCode::NOT_FOUND);
7138        assert_eq!(err["error"]["code"], "stream_not_found");
7139        assert!(err["error"]["message"]
7140            .as_str()
7141            .unwrap()
7142            .contains("stream_resumable"));
7143    }
7144
7145    /// The published template and the router's pattern must describe
7146    /// the same path, or a client built from `frink_api::routes` asks
7147    /// for something this server does not serve.
7148    #[test]
7149    fn the_axum_stream_patterns_match_the_published_templates() {
7150        assert_eq!(
7151            axum_path(frink_api::routes::V1_STREAM),
7152            "/v1/stream/:request_id"
7153        );
7154        assert_eq!(
7155            axum_path(frink_api::routes::V1_STREAM_POLL),
7156            "/v1/stream/:request_id/poll"
7157        );
7158        assert_eq!(
7159            frink_api::routes::v1_stream("abc"),
7160            axum_path(frink_api::routes::V1_STREAM).replace(":request_id", "abc")
7161        );
7162    }
7163
7164    /// Every published template goes through the converter, and what
7165    /// comes out has no braces left in it.
7166    ///
7167    /// The two Responses routes were mounted raw, so axum matched the
7168    /// literal segment `{response_id}` and a real id fell through to a
7169    /// bodiless 404. The test router had the same two lines, which is
7170    /// why nothing caught it. This walks the templates instead of
7171    /// naming them, so the next one added is covered without anybody
7172    /// remembering to come back here.
7173    #[test]
7174    fn no_published_template_reaches_the_router_with_its_braces() {
7175        for template in [
7176            frink_api::routes::V1_STREAM,
7177            frink_api::routes::V1_STREAM_POLL,
7178            frink_api::routes::V1_RESPONSE,
7179            frink_api::routes::V1_RESPONSE_CANCEL,
7180            frink_api::routes::ADMIN_TASK_CANCEL,
7181        ] {
7182            assert!(
7183                template.contains('{'),
7184                "{template} is in the template list but has no placeholder"
7185            );
7186            let mounted = axum_path(template);
7187            assert!(
7188                !mounted.contains('{') && !mounted.contains('}'),
7189                "{template} would be mounted as {mounted}, whose braces axum reads as a literal segment"
7190            );
7191            assert!(
7192                mounted.contains(':'),
7193                "{template} lost its placeholder entirely and would match one path only"
7194            );
7195        }
7196    }
7197
7198    /// A real id must reach the handler, not axum's catch-all 404.
7199    ///
7200    /// The distinction is the whole point: axum answers an unmatched
7201    /// path with an empty body, while the handler answers an unknown id
7202    /// with a reasoned JSON error. Asserting on the body rather than
7203    /// the status is what separates "the route is missing" from "the
7204    /// response is not here".
7205    #[tokio::test]
7206    async fn an_unknown_response_id_gets_the_handler_not_a_bare_404() {
7207        let app = test_app();
7208        let (status, body) = get_json(&app, "/v1/responses/resp_nonexistent").await;
7209        assert_eq!(status, StatusCode::NOT_FOUND);
7210        assert!(
7211            !body.is_null(),
7212            "empty body means axum never matched the route, so the id was read as a literal segment"
7213        );
7214    }
7215
7216    /// An empty task list is a list, not a missing key -- the UI renders
7217    /// "no jobs" from it rather than from an error.
7218    #[tokio::test]
7219    async fn the_task_list_starts_empty_rather_than_absent() {
7220        let app = test_app();
7221        let (status, body) = get_json(&app, frink_api::routes::ADMIN_TASKS).await;
7222        assert_eq!(status, StatusCode::OK);
7223        assert_eq!(body["tasks"].as_array().unwrap().len(), 0);
7224    }
7225
7226    /// The slots route exists, is reachable, and refuses by naming the
7227    /// flag that would turn it on -- rather than 404ing, which is what
7228    /// an unregistered route would do and is indistinguishable from
7229    /// "this build has no slots".
7230    ///
7231    /// The condition is reachable by default: `FRINK_SLOT_SAVE_PATH`
7232    /// is unset unless an operator passes `--slot-save-path`, so this
7233    /// is the answer every stock server gives.
7234    #[tokio::test]
7235    async fn the_slots_route_is_registered_and_refuses_by_naming_slot_save_path() {
7236        assert!(
7237            std::env::var("FRINK_SLOT_SAVE_PATH").is_err(),
7238            "this test asserts the unconfigured behaviour"
7239        );
7240        let app = test_app();
7241        let (status, body) = post_json_uri(
7242            &app,
7243            &format!("{}?action=save", frink_api::routes::slots_id(0)),
7244            serde_json::json!({"filename": "sys.fslot", "prompt": "hi"}),
7245        )
7246        .await;
7247        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
7248        assert!(
7249            body["error"]["message"]
7250                .as_str()
7251                .unwrap()
7252                .contains("--slot-save-path"),
7253            "{body}"
7254        );
7255    }
7256
7257    pub(crate) async fn post_json_uri(
7258        app: &Router,
7259        uri: &str,
7260        body: serde_json::Value,
7261    ) -> (StatusCode, serde_json::Value) {
7262        use http_body_util::BodyExt;
7263        use tower::ServiceExt;
7264
7265        let response = app
7266            .clone()
7267            .oneshot(
7268                axum::http::Request::builder()
7269                    .method("POST")
7270                    .uri(uri)
7271                    .header("content-type", "application/json")
7272                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7273                    .unwrap(),
7274            )
7275            .await
7276            .unwrap();
7277        let status = response.status();
7278        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7279        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
7280        (status, json)
7281    }
7282
7283    /// The GET twin of [`post_json_uri`], for the routes that report
7284    /// state rather than change it.
7285    pub(crate) async fn get_json_uri(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
7286        use http_body_util::BodyExt;
7287        use tower::ServiceExt;
7288
7289        let response = app
7290            .clone()
7291            .oneshot(
7292                axum::http::Request::builder()
7293                    .method("GET")
7294                    .uri(uri)
7295                    .body(axum::body::Body::empty())
7296                    .unwrap(),
7297            )
7298            .await
7299            .unwrap();
7300        let status = response.status();
7301        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7302        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
7303        (status, json)
7304    }
7305
7306    async fn post_json(app: &Router, body: serde_json::Value) -> serde_json::Value {
7307        post_json_uri(app, "/v1/chat/completions", body).await.1
7308    }
7309
7310    /// The engine's live footprint, beside the budget it was sized
7311    /// against. Two things are asserted rather than the number itself,
7312    /// which is a property of the host: it is never a ZERO (an engine
7313    /// using no memory is not a thing that happens, so a zero would be
7314    /// a failed read presented as a fact), and it always says WHICH
7315    /// quantity it is -- a caller comparing a PSS figure with an RSS
7316    /// one is comparing two different things and will read the
7317    /// difference as a leak.
7318    #[tokio::test]
7319    async fn stats_says_what_the_engine_is_using_and_which_quantity_that_is() {
7320        let app = test_app();
7321        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
7322        assert_eq!(status, StatusCode::OK);
7323
7324        let memory = &body["memory"];
7325        if memory.is_null() {
7326            // No `/proc`: absent is the honest answer, and the point of
7327            // this branch is that it is absent rather than zero.
7328            return;
7329        }
7330        assert!(
7331            memory["bytes"].as_u64().is_some_and(|b| b > 0),
7332            "a read that produced a zero is a broken read, not an idle \
7333             engine: {memory}"
7334        );
7335        assert!(
7336            ["pss", "rss"].contains(&memory["kind"].as_str().unwrap_or("")),
7337            "the quantity must travel with the number: {memory}"
7338        );
7339    }
7340
7341    /// A pool this deployment does not have is reported `null`, never
7342    /// as a zero row. "No window pool" and "a window pool with nothing
7343    /// in it" are different facts, and an operator shown the second for
7344    /// the first sizes against a pool that does not exist. The test
7345    /// state runs with no shared KV pool, so all three are absent here.
7346    #[tokio::test]
7347    async fn stats_reports_a_pool_it_does_not_have_as_absent_and_not_as_zero() {
7348        let app = test_app();
7349        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
7350        assert_eq!(status, StatusCode::OK);
7351        for pool in ["kv_pages", "window_slots", "state_slots"] {
7352            assert!(
7353                body["pools"][pool].is_null(),
7354                "{pool} must be null rather than a zero row: {}",
7355                body["pools"]
7356            );
7357        }
7358    }
7359
7360    /// A streamed `/v1/messages` can be cancelled only if the client
7361    /// can learn the id, and the Anthropic protocol has no field for
7362    /// it -- the `message_start` `msg_...` is a different identifier
7363    /// the cancel registry has never seen. So the header carries it,
7364    /// on the success path and on the error path alike, because a
7365    /// client that logs one id per call should not lose it exactly
7366    /// when something went wrong.
7367    #[tokio::test]
7368    async fn a_messages_response_states_the_id_that_v1_cancel_takes() {
7369        use http_body_util::BodyExt;
7370        use tower::ServiceExt;
7371
7372        let app = test_app();
7373        let send = |body: serde_json::Value| {
7374            let app = app.clone();
7375            async move {
7376                app.oneshot(
7377                    axum::http::Request::builder()
7378                        .method("POST")
7379                        .uri(frink_api::routes::V1_MESSAGES)
7380                        .header("content-type", "application/json")
7381                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7382                        .unwrap(),
7383                )
7384                .await
7385                .unwrap()
7386            }
7387        };
7388
7389        let ok = send(serde_json::json!({
7390            "model": "test",
7391            "max_tokens": 1,
7392            "messages": [{"role": "user", "content": "hi"}],
7393        }))
7394        .await;
7395        assert_eq!(ok.status(), StatusCode::OK);
7396        let id = ok
7397            .headers()
7398            .get("request-id")
7399            .expect("a served message names its id")
7400            .to_str()
7401            .unwrap()
7402            .to_string();
7403        assert!(!id.is_empty());
7404
7405        // A rejected body still gets one, and a different one: two calls
7406        // must never collide in the ring.
7407        let bad = send(serde_json::json!({"model": "test"})).await;
7408        assert!(bad.status().is_client_error());
7409        let other = bad.headers().get("request-id").expect("errors too");
7410        assert_ne!(other.to_str().unwrap(), id);
7411        let _ = bad.into_body().collect().await.unwrap();
7412    }
7413
7414    /// The gate is the point of the rebuild endpoint: a request that
7415    /// arrives while the KV pool is being re-split must be refused,
7416    /// because admitting it would let a decode allocate out of a pool
7417    /// whose block count is about to change under it. `503` and not
7418    /// `500` -- the caller should retry in a moment, and the body says
7419    /// which of the four closed states it hit so a client can tell
7420    /// "not yet" from "not ever".
7421    #[tokio::test]
7422    async fn a_request_that_arrives_mid_rebuild_is_refused_and_admitted_again_after() {
7423        let state = Arc::new(test_state(
7424            test_model_full_byte_vocab(),
7425            ResponseCache::new(1000, Duration::from_secs(3600)),
7426        ));
7427        let app = test_app_with_state(Arc::clone(&state));
7428        let body = serde_json::json!({
7429            "model": "test",
7430            "messages": [{"role": "user", "content": "hi"}],
7431            "max_tokens": 1,
7432        });
7433
7434        state
7435            .maintenance
7436            .lock()
7437            .unwrap()
7438            .begin_rebuild()
7439            .expect("a fresh server is serving, so the rebuild starts");
7440        let (status, refused) = post_json_uri(&app, "/v1/chat/completions", body.clone()).await;
7441        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
7442        assert_eq!(refused["error"]["type"], "cache_rebuilding");
7443
7444        state.maintenance.lock().unwrap().finish_rebuild(true);
7445        let (status, _) = post_json_uri(&app, "/v1/chat/completions", body).await;
7446        assert_eq!(
7447            status,
7448            StatusCode::OK,
7449            "the gate reopens; a rebuild is not a latch"
7450        );
7451    }
7452
7453    /// Cancelling an id that is not generating must not answer `200`.
7454    /// A UI told "ok" for an already-finished request would report that
7455    /// it stopped work it did not stop, and the two outcomes are the
7456    /// only thing this endpoint exists to distinguish.
7457    #[tokio::test]
7458    async fn cancelling_an_id_that_is_not_generating_is_a_404_that_says_so() {
7459        let app = test_app();
7460        let (status, body) = post_json_uri(
7461            &app,
7462            frink_api::routes::V1_CANCEL,
7463            serde_json::json!({ "request_id": "chatcmpl-never-issued" }),
7464        )
7465        .await;
7466        assert_eq!(status, StatusCode::NOT_FOUND);
7467        assert_eq!(body["cancelled"], serde_json::json!(false));
7468        assert_eq!(body["request_id"], "chatcmpl-never-issued");
7469        assert!(
7470            body["detail"].as_str().is_some_and(|d| !d.is_empty()),
7471            "the verdict must carry a human reason: {body}"
7472        );
7473    }
7474
7475    /// The endpoint reaches the registry the streaming path registers
7476    /// into -- not a second, parallel one. Registered by hand here
7477    /// because a `oneshot` router cannot hold a stream open.
7478    #[tokio::test]
7479    async fn cancelling_a_live_generation_signals_its_token_and_answers_200() {
7480        let state = Arc::new(test_state(
7481            test_model_full_byte_vocab(),
7482            ResponseCache::new(1000, Duration::from_secs(3600)),
7483        ));
7484        let app = test_app_with_state(Arc::clone(&state));
7485        let (token, _guard) = state.cancels.register("chatcmpl-live");
7486
7487        let (status, before) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
7488        assert_eq!(status, StatusCode::OK);
7489        assert_eq!(before["generating_now"], serde_json::json!(1));
7490
7491        let (status, body) = post_json_uri(
7492            &app,
7493            frink_api::routes::V1_CANCEL,
7494            serde_json::json!({ "request_id": "chatcmpl-live" }),
7495        )
7496        .await;
7497        assert_eq!(status, StatusCode::OK);
7498        assert_eq!(body["cancelled"], serde_json::json!(true));
7499        assert!(
7500            token.is_cancelled(),
7501            "the endpoint answered ok without setting the flag the decode loop reads"
7502        );
7503    }
7504
7505    #[tokio::test]
7506    async fn tokenize_detokenize_roundtrip_and_embeddings_mean() {
7507        let app = test_app();
7508        let (status, tok) =
7509            post_json_uri(&app, "/v1/tokenize", serde_json::json!({ "prompt": "Hi" })).await;
7510        assert_eq!(status, StatusCode::OK);
7511        let tokens = tok["tokens"].as_array().unwrap();
7512        assert_eq!(tok["count"], tokens.len());
7513        assert!(!tokens.is_empty());
7514
7515        let (status, detok) = post_json_uri(
7516            &app,
7517            "/v1/detokenize",
7518            serde_json::json!({ "tokens": tokens }),
7519        )
7520        .await;
7521        assert_eq!(status, StatusCode::OK);
7522        assert_eq!(detok["text"], "Hi");
7523
7524        let (status, emb) = post_json_uri(
7525            &app,
7526            "/v1/embeddings",
7527            serde_json::json!({
7528                "input": "Hi",
7529                "embedding_type": "mean"
7530            }),
7531        )
7532        .await;
7533        assert_eq!(status, StatusCode::OK);
7534        let vec = emb["data"][0]["embedding"].as_array().unwrap();
7535        assert!(!vec.is_empty());
7536        assert!(vec.iter().all(|v| v.as_f64().is_some()));
7537    }
7538
7539    /// The decoder path's accepted `embedding_type` set must not have
7540    /// widened when the encoder path arrived: `cls` is row 0 of a
7541    /// decoder's hidden states, which is its BOS position and means
7542    /// nothing, so it stays refused here and the refusal names what is
7543    /// accepted.
7544    #[tokio::test]
7545    async fn the_decoder_path_still_refuses_a_pooling_it_cannot_mean() {
7546        let app = test_app();
7547        let (status, body) = post_json_uri(
7548            &app,
7549            "/v1/embeddings",
7550            serde_json::json!({ "input": "Hi", "embedding_type": "cls" }),
7551        )
7552        .await;
7553        assert_eq!(status, StatusCode::BAD_REQUEST);
7554        let msg = body["error"]["message"].as_str().unwrap();
7555        assert!(msg.contains("mean") && msg.contains("last"), "{msg}");
7556    }
7557
7558    /// A real BGE checkpoint served through the route: CLS by default
7559    /// because the file says `pooling_type = 2`, 384 dims, unit norm,
7560    /// and `usage.prompt_tokens` counting the `[CLS]`/`[SEP]` the model
7561    /// actually saw.
7562    #[tokio::test]
7563    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
7564    async fn a_real_embedding_model_serves_v1_embeddings() {
7565        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7566            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
7567        if !path.exists() {
7568            eprintln!("SKIP: {} not present", path.display());
7569            return;
7570        }
7571        let encoder = frink_models::EmbeddingModel::from_gguf_path(&path).expect("load bge");
7572        let mut state = test_state(
7573            test_model_full_byte_vocab(),
7574            ResponseCache::new(1000, Duration::from_secs(3600)),
7575        );
7576        state.embedding = Some(Arc::new(encoder));
7577        let app = test_app_with_state(Arc::new(state));
7578
7579        let (status, body) = post_json_uri(
7580            &app,
7581            "/v1/embeddings",
7582            serde_json::json!({ "input": ["Hello world", "a second input"] }),
7583        )
7584        .await;
7585        assert_eq!(status, StatusCode::OK, "{body}");
7586        assert_eq!(body["model"], "bge-small-en-v1.5");
7587        let data = body["data"].as_array().unwrap();
7588        assert_eq!(data.len(), 2);
7589        for (i, row) in data.iter().enumerate() {
7590            assert_eq!(row["index"], i);
7591            let v: Vec<f64> = row["embedding"]
7592                .as_array()
7593                .unwrap()
7594                .iter()
7595                .map(|x| x.as_f64().unwrap())
7596                .collect();
7597            assert_eq!(v.len(), 384, "the encoder\'s width, not the decoder\'s");
7598            let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
7599            assert!((norm - 1.0).abs() < 1e-4, "not L2-normalized: {norm}");
7600        }
7601        // "Hello world" is [CLS] hello world [SEP] = 4, and the second
7602        // input adds its own two specials.
7603        assert!(body["usage"]["prompt_tokens"].as_u64().unwrap() >= 4 + 2);
7604
7605        // The default came from the file. Asking for MEAN must give a
7606        // different vector, which is what proves CLS was not a
7607        // coincidence of this input.
7608        let (status, mean) = post_json_uri(
7609            &app,
7610            "/v1/embeddings",
7611            serde_json::json!({ "input": "Hello world", "embedding_type": "mean" }),
7612        )
7613        .await;
7614        assert_eq!(status, StatusCode::OK);
7615        assert_ne!(mean["data"][0]["embedding"], data[0]["embedding"]);
7616    }
7617
7618    /// The same BGE checkpoint as `FRINK_MODEL_PATH` -- the *loaded*
7619    /// model, not a side-car.
7620    ///
7621    /// Four claims, and the third is the one this whole seam exists
7622    /// for: the loader routes an encoder-only GGUF away from every
7623    /// decoder path, `/v1/embeddings` serves it, `/v1/chat/completions`
7624    /// refuses it NAMING IT AS AN EMBEDDING MODEL (before this, the
7625    /// same file died in `tokenizer_from_gguf` with a message about
7626    /// WordPiece being unreadable -- true, and the wrong thing to send
7627    /// a user after), and `/v1/models` says which endpoint it is for so
7628    /// a client need not send a request to find out.
7629    #[tokio::test]
7630    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
7631    async fn an_encoder_can_be_the_loaded_model() {
7632        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7633            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
7634        if !path.exists() {
7635            eprintln!("SKIP: {} not present", path.display());
7636            return;
7637        }
7638
7639        // Through the real `FRINK_MODEL_PATH` loader, not by
7640        // constructing an `EmbeddingModel` directly: the routing
7641        // decision is half of what is under test.
7642        let loaded = model::load_from_path(path.to_str().unwrap()).expect("load bge as the model");
7643        assert!(
7644            matches!(loaded, model::LoadedModel::Encoder(_)),
7645            "an encoder-only GGUF reached a decoder loader"
7646        );
7647        let (loaded, batcher, ceiling) = activate_loaded_model(loaded, true, None, None);
7648        assert!(
7649            matches!(loaded, Loaded::Encoder(_)),
7650            "the encoder did not stay an encoder through activation"
7651        );
7652        assert!(
7653            batcher.is_none() && ceiling.is_none(),
7654            "an encoder was given a decode batcher or a KV ceiling it has no use for"
7655        );
7656
7657        let state = test_state(
7658            test_model_full_byte_vocab(),
7659            ResponseCache::new(1000, Duration::from_secs(3600)),
7660        );
7661        state.swap_active(Some(Arc::new(ActiveModel {
7662            id: None,
7663            loaded,
7664            batcher,
7665            ceiling,
7666            checkpoint_path: None,
7667        })));
7668        let app = test_app_with_state(Arc::new(state));
7669
7670        // 1. It embeds.
7671        let (status, body) = post_json_uri(
7672            &app,
7673            "/v1/embeddings",
7674            serde_json::json!({ "input": "Hello world" }),
7675        )
7676        .await;
7677        assert_eq!(status, StatusCode::OK, "{body}");
7678        assert_eq!(body["model"], "bge-small-en-v1.5");
7679        let v = body["data"][0]["embedding"].as_array().unwrap();
7680        assert_eq!(v.len(), 384, "the encoder's width, not the decoder's");
7681
7682        // 2. It refuses to chat, by name.
7683        let (status, body) = post_json_uri(
7684            &app,
7685            "/v1/chat/completions",
7686            serde_json::json!({
7687                "model": "bge-small-en-v1.5",
7688                "messages": [{"role": "user", "content": "hi"}],
7689            }),
7690        )
7691        .await;
7692        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}");
7693        let msg = body["error"]["message"].as_str().unwrap();
7694        for fact in [
7695            "bge-small-en-v1.5",
7696            "bert",
7697            "embedding model",
7698            "/v1/embeddings",
7699        ] {
7700            assert!(msg.contains(fact), "the refusal does not say {fact}: {msg}");
7701        }
7702
7703        // 3. `/v1/models` lists it as what it is.
7704        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
7705        assert_eq!(status, StatusCode::OK);
7706        let entry = &models["data"][0];
7707        assert_eq!(entry["id"], "bge-small-en-v1.5");
7708        assert_eq!(entry["frink_model_kind"], "embedding");
7709        assert_eq!(entry["frink_tokenizer"], "gguf-wordpiece");
7710        assert_eq!(entry["frink_n_embd"], 384);
7711        assert_eq!(entry["frink_pooling"], "CLS");
7712        assert_eq!(
7713            entry["frink_endpoints"],
7714            serde_json::json!(["/v1/embeddings"])
7715        );
7716        // A reasoning-gear field here would be an invented answer about
7717        // a template the checkpoint does not have.
7718        assert!(entry.get("supported_reasoning_efforts").is_none());
7719
7720        // 4. `/health` is ready, and says which endpoint is ready.
7721        let (status, health) = get_json(&app, frink_api::routes::HEALTH).await;
7722        assert_eq!(status, StatusCode::OK, "an encoder is a loaded model");
7723        assert_eq!(health["model"]["id"], "bge-small-en-v1.5");
7724        assert_eq!(health["model"]["synthetic_weights"], false);
7725        let weights = health["capabilities"]
7726            .as_array()
7727            .unwrap()
7728            .iter()
7729            .find(|c| c["id"] == frink_api::health::capability::REAL_WEIGHTS)
7730            .expect("a real-weights capability row");
7731        let detail = weights["detail"].as_str().unwrap_or_default();
7732        assert!(detail.contains("ENCODER"), "{detail}");
7733        // 5. It tokenizes, and round-trips. An embedding model's whole
7734        // contract is the vector it returns for a string, so when that
7735        // vector surprises you the first question is what tokens it
7736        // actually saw. These routes used to go through
7737        // `generative()?` and answer 501 "not a generative model",
7738        // which left no way to ask without loading the checkpoint in a
7739        // second tool (issue #28).
7740        let (status, body) = post_json_uri(
7741            &app,
7742            frink_api::routes::V1_TOKENIZE,
7743            serde_json::json!({ "content": "hello world" }),
7744        )
7745        .await;
7746        assert_eq!(
7747            status,
7748            StatusCode::OK,
7749            "an encoder has a real tokenizer: {body}"
7750        );
7751        let tokens = body["tokens"].as_array().expect("tokens array").clone();
7752        assert!(!tokens.is_empty(), "WordPiece produced nothing: {body}");
7753
7754        let (status, body) = post_json_uri(
7755            &app,
7756            frink_api::routes::V1_DETOKENIZE,
7757            serde_json::json!({ "tokens": tokens }),
7758        )
7759        .await;
7760        assert_eq!(status, StatusCode::OK, "{body}");
7761        let round_tripped = body["content"].as_str().expect("content").to_string();
7762        assert!(
7763            round_tripped.contains("hello") && round_tripped.contains("world"),
7764            "the ids did not decode back through the encoder's own vocabulary: {round_tripped}"
7765        );
7766
7767        // And the refusal that must NOT have been weakened: a decode is
7768        // still a decode, and this checkpoint still cannot do one.
7769        let (status, _) = post_json_uri(
7770            &app,
7771            "/v1/completions",
7772            serde_json::json!({ "model": "m", "prompt": "hi", "max_tokens": 1 }),
7773        )
7774        .await;
7775        assert_eq!(
7776            status,
7777            StatusCode::NOT_IMPLEMENTED,
7778            "tokenizing an encoder must not have opened a path to generating with one"
7779        );
7780    }
7781
7782    /// The /metrics endpoint must expose the bounded expert cache's
7783    /// counters when the model streams routed experts, and the
7784    /// counters must reflect real decode activity (a forward pass
7785    /// through store-backed MoE layers produces misses/hits).
7786    #[tokio::test]
7787    async fn metrics_exposes_expert_store_counters_when_streaming_is_active() {
7788        use http_body_util::BodyExt;
7789        use tower::ServiceExt;
7790
7791        let fixture = concat!(
7792            "../frink-models/tests/fixtures/",
7793            "frink_real_moe_test.gguf"
7794        );
7795        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
7796        let decoder = Decoder::from_gguf_with_expert_cache(
7797            &fixture,
7798            frink_models::config::test_moe_fixture(),
7799            Some(1024 * 1024),
7800        )
7801        .expect("MoE fixture must load store-backed");
7802
7803        // Drive one real forward pass so the store sees decode
7804        // activity (the fixture's tiny vocab can't survive the HTTP
7805        // path's template text, so decode directly).
7806        let mut caches: Vec<frink_core::cache::KvCache> = decoder.config.new_kv_caches();
7807        decoder.forward_token(1, 0, &mut caches);
7808
7809        let model = Model::Gguf(GgufModel {
7810            decoder: Arc::new(decoder),
7811            tokenizer: Arc::new(ServerTokenizer::Byte),
7812            stop_tokens: StopTokens::default(),
7813            bos_id: None,
7814            is_synthetic: false,
7815            chat_template: chat_template::PromptTemplate::plain(),
7816        });
7817        let state = Arc::new(test_state(
7818            model,
7819            ResponseCache::new(16, Duration::from_secs(60)),
7820        ));
7821        let app = Router::new()
7822            .route("/metrics", axum::routing::get(metrics))
7823            .route("/v1/chat/completions", post(chat_completions))
7824            .with_state(state);
7825
7826        let fetch_metrics = |app: Router| async move {
7827            let resp = app
7828                .oneshot(
7829                    axum::http::Request::builder()
7830                        .method("GET")
7831                        .uri("/metrics")
7832                        .body(axum::body::Body::empty())
7833                        .unwrap(),
7834                )
7835                .await
7836                .unwrap();
7837            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
7838            String::from_utf8(bytes.to_vec()).unwrap()
7839        };
7840
7841        let after = fetch_metrics(app.clone()).await;
7842        assert!(
7843            after.contains("frink_expert_cache_misses_total"),
7844            "streaming model must expose expert-cache metrics: {after}"
7845        );
7846        let misses: u64 = after
7847            .lines()
7848            .find(|l| l.starts_with("frink_expert_cache_misses_total"))
7849            .and_then(|l| l.split_whitespace().nth(1))
7850            .and_then(|v| v.parse().ok())
7851            .expect("misses metric line must parse");
7852        assert!(
7853            misses > 0,
7854            "decode must have read experts through the store: {after}"
7855        );
7856    }
7857
7858    fn weather_tool() -> serde_json::Value {
7859        serde_json::json!({
7860            "type": "function",
7861            "function": {
7862                "name": "get_weather",
7863                "description": "Get the current weather for a location.",
7864                "parameters": {
7865                    "type": "object",
7866                    "properties": {"location": {"type": "string"}},
7867                    "required": ["location"]
7868                }
7869            }
7870        })
7871    }
7872
7873    fn weather_tool_def() -> ToolDef {
7874        ToolDef {
7875            kind: "function".to_string(),
7876            function: ToolFunctionDef {
7877                name: "get_weather".to_string(),
7878                description: Some("Get the current weather for a location.".to_string()),
7879                parameters: Some(serde_json::json!({
7880                    "type": "object",
7881                    "properties": {"location": {"type": "string"}},
7882                    "required": ["location"]
7883                })),
7884            },
7885        }
7886    }
7887
7888    #[test]
7889    fn tool_preamble_mentions_every_tool_name_and_description() {
7890        let preamble = tool_preamble(&[weather_tool_def()]);
7891        assert!(preamble.contains("get_weather"));
7892        assert!(preamble.contains("Get the current weather for a location."));
7893        assert!(preamble.contains("<tool_call>"));
7894        assert!(preamble.contains("</tool_call>"));
7895    }
7896
7897    #[test]
7898    fn a_real_marker_becomes_a_structured_tool_call() {
7899        let text = "sure, let me check.<tool_call>{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}</tool_call>";
7900        let (message, finish) = build_response_message(
7901            text.to_string(),
7902            &[weather_tool_def()],
7903            output::OutputPosture::for_model("test-model"),
7904            "stop",
7905        );
7906        assert_eq!(finish, "tool_calls");
7907        let calls = message.tool_calls.expect("must carry a tool call");
7908        assert_eq!(calls[0].function.name, "get_weather");
7909        let parsed: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
7910        assert_eq!(parsed["location"], "Paris");
7911    }
7912
7913    #[test]
7914    fn a_plain_answer_is_not_promoted_to_a_tool_call() {
7915        let (message, finish) = build_response_message(
7916            "just an answer".to_string(),
7917            &[weather_tool_def()],
7918            output::OutputPosture::for_model("test-model"),
7919            "stop",
7920        );
7921        assert_eq!(finish, "stop");
7922        assert!(message.tool_calls.is_none());
7923        assert_eq!(message.content.as_deref(), Some("just an answer"));
7924    }
7925
7926    /// Malformed JSON inside the marker is not a call. Returning it as
7927    /// one would hand a client arguments it cannot parse.
7928    #[test]
7929    fn a_malformed_payload_is_not_a_tool_call() {
7930        let (message, finish) = build_response_message(
7931            "<tool_call>not valid json at all</tool_call>".to_string(),
7932            &[weather_tool_def()],
7933            output::OutputPosture::for_model("test-model"),
7934            "stop",
7935        );
7936        assert_eq!(finish, "stop");
7937        assert!(message.tool_calls.is_none());
7938    }
7939
7940    /// A call to something the request never offered is refused: the
7941    /// client would be asked to execute a tool it does not have.
7942    #[test]
7943    fn a_tool_that_was_never_offered_is_not_returned() {
7944        let (message, finish) = build_response_message(
7945            "<tool_call>{\"name\": \"ping\", \"arguments\": {}}</tool_call>".to_string(),
7946            &[weather_tool_def()],
7947            output::OutputPosture::for_model("test-model"),
7948            "stop",
7949        );
7950        assert_eq!(finish, "stop");
7951        assert!(message.tool_calls.is_none());
7952    }
7953
7954    /// With no tools offered at all, marker text is just text.
7955    #[test]
7956    fn marker_text_with_no_tools_offered_stays_content() {
7957        let (message, finish) = build_response_message(
7958            "<tool_call>{\"name\": \"get_weather\", \"arguments\": {}}</tool_call>".to_string(),
7959            &[],
7960            output::OutputPosture::for_model("test-model"),
7961            "stop",
7962        );
7963        assert_eq!(finish, "stop");
7964        assert!(message.tool_calls.is_none());
7965        assert!(message.content.is_some());
7966    }
7967
7968    /// The streaming contract a coding agent depends on: the call's
7969    /// identity arrives first, then its arguments in pieces, and the
7970    /// pieces concatenate to exactly the final arguments.
7971    #[test]
7972    fn a_streamed_call_opens_then_delivers_its_arguments_in_pieces() {
7973        let opened = std::cell::Cell::new(0usize);
7974        let mut parser = crate::policy::parser::ToolCallParser::new(
7975            crate::policy::parser::ToolCallFormat::Qwen3Coder,
7976            vec![
7977                crate::policy::parser::tool_call::ToolSchema::with_parameters(
7978                    "write_file",
7979                    serde_json::json!({"type": "object", "properties": {
7980                        "path": {"type": "string"},
7981                        "contents": {"type": "string"}
7982                    }}),
7983                ),
7984            ],
7985        );
7986        let wire = "<tool_call><function=write_file>\
7987                    <parameter=path>\n/tmp/x\n</parameter>\
7988                    <parameter=contents>\nhello world\n</parameter>\
7989                    </function></tool_call>";
7990
7991        let mut deltas = Vec::new();
7992        let mut text = String::new();
7993        for piece in wire.as_bytes().chunks(7) {
7994            let chunk = String::from_utf8_lossy(piece).into_owned();
7995            let (more_text, more) = tool_call_deltas(parser.push(&chunk), &opened);
7996            text.push_str(&more_text);
7997            deltas.extend(more);
7998        }
7999        let (more_text, more) = tool_call_deltas(parser.finish(), &opened);
8000        text.push_str(&more_text);
8001        deltas.extend(more);
8002
8003        assert_eq!(opened.get(), 1, "one call opened");
8004        assert!(text.is_empty(), "the markers are not content: {text:?}");
8005
8006        let first = &deltas[0];
8007        assert_eq!(first.index, 0);
8008        assert_eq!(first.id.as_deref(), Some("call_0"));
8009        assert_eq!(first.kind, Some("function"));
8010        assert_eq!(first.function.name.as_deref(), Some("write_file"));
8011
8012        // Everything after the opening delta is argument text only,
8013        // and it parses once concatenated.
8014        let joined: String = deltas
8015            .iter()
8016            .filter_map(|d| d.function.arguments.clone())
8017            .collect();
8018        let parsed: serde_json::Value =
8019            serde_json::from_str(&joined).expect("the fragments concatenate to valid JSON");
8020        assert_eq!(parsed["path"], serde_json::json!("/tmp/x"));
8021        assert_eq!(parsed["contents"], serde_json::json!("hello world"));
8022        assert!(
8023            deltas.len() >= 3,
8024            "the arguments arrived in pieces, not whole: {}",
8025            deltas.len()
8026        );
8027        assert!(
8028            deltas[1..].iter().all(|d| d.function.name.is_none()),
8029            "only the opening delta carries identity"
8030        );
8031    }
8032
8033    /// Text either side of a call still streams as content, in order.
8034    #[test]
8035    fn text_around_a_streamed_call_is_still_content() {
8036        let opened = std::cell::Cell::new(0usize);
8037        let mut parser = crate::policy::parser::ToolCallParser::new(
8038            crate::policy::parser::ToolCallFormat::Qwen25,
8039            vec![crate::policy::parser::tool_call::ToolSchema::new(
8040                "get_weather",
8041            )],
8042        );
8043        let wire = "let me check. <tool_call>{\"name\": \"get_weather\", \
8044                    \"arguments\": {}}</tool_call> done";
8045        let mut text = String::new();
8046        for piece in wire.as_bytes().chunks(5) {
8047            let chunk = String::from_utf8_lossy(piece).into_owned();
8048            let (more, _) = tool_call_deltas(parser.push(&chunk), &opened);
8049            text.push_str(&more);
8050        }
8051        let (more, _) = tool_call_deltas(parser.finish(), &opened);
8052        text.push_str(&more);
8053
8054        assert_eq!(opened.get(), 1);
8055        assert!(text.starts_with("let me check. "), "{text:?}");
8056        assert!(text.ends_with(" done"), "{text:?}");
8057        assert!(!text.contains("<tool_call>"), "markers leaked: {text:?}");
8058    }
8059
8060    /// A reasoning model's thinking must not be returned as its
8061    /// answer.
8062    #[test]
8063    fn a_reasoning_block_is_split_out_of_the_answer() {
8064        let (message, finish) = build_response_message(
8065            "<think>weighing it up</think>The answer is 4.".to_string(),
8066            &[],
8067            output::OutputPosture::for_model("Qwen3-8B"),
8068            "stop",
8069        );
8070        assert_eq!(finish, "stop");
8071        assert_eq!(message.content.as_deref(), Some("The answer is 4."));
8072        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
8073    }
8074
8075    /// ... and a model with no reasoning format keeps its text intact,
8076    /// markers and all.
8077    #[test]
8078    fn a_non_reasoning_model_keeps_a_literal_marker_in_its_answer() {
8079        let (message, _) = build_response_message(
8080            "Use the <think> tag like this.".to_string(),
8081            &[],
8082            output::OutputPosture::for_model("llama-3.1-8b"),
8083            "stop",
8084        );
8085        assert_eq!(
8086            message.content.as_deref(),
8087            Some("Use the <think> tag like this.")
8088        );
8089        assert!(message.reasoning_content.is_none());
8090    }
8091
8092    /// Zero-regression proof: an ordinary request with no `tools`/
8093    /// `session_id` produces the plain response shape -- `content` a
8094    /// string, no `tool_calls` field -- with an honest finish reason:
8095    /// this 4-token greedy request truncates at `max_tokens`, so
8096    /// `finish_reason` must be "length" (an earlier version hardcoded
8097    /// "stop" for every non-streaming response), and `usage` counts
8098    /// exactly the generated tokens.
8099    #[tokio::test]
8100    async fn a_request_with_no_tools_or_session_behaves_exactly_as_before() {
8101        let app = test_app();
8102        let body = serde_json::json!({
8103            "model": "m",
8104            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8105            "max_tokens": 4,
8106            "temperature": 0,
8107        });
8108        let resp = post_json(&app, body).await;
8109        let message = &resp["choices"][0]["message"];
8110        assert!(message["content"].is_string());
8111        assert!(message.get("tool_calls").is_none());
8112        assert_eq!(resp["choices"][0]["finish_reason"], "length");
8113        assert_eq!(resp["usage"]["completion_tokens"], 4);
8114        assert_eq!(
8115            resp["usage"]["total_tokens"],
8116            resp["usage"]["prompt_tokens"].as_u64().unwrap() + 4
8117        );
8118    }
8119
8120    pub(crate) async fn get_json(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
8121        use http_body_util::BodyExt;
8122        use tower::ServiceExt;
8123
8124        let response = app
8125            .clone()
8126            .oneshot(
8127                axum::http::Request::builder()
8128                    .method("GET")
8129                    .uri(uri)
8130                    .body(axum::body::Body::empty())
8131                    .unwrap(),
8132            )
8133            .await
8134            .unwrap();
8135        let status = response.status();
8136        let bytes = response.into_body().collect().await.unwrap().to_bytes();
8137        (status, serde_json::from_slice(&bytes).unwrap())
8138    }
8139
8140    #[tokio::test]
8141    async fn health_answers_a_capability_handshake_not_a_boolean() {
8142        let app = test_app();
8143        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
8144        assert_eq!(status, StatusCode::OK);
8145
8146        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
8147        assert_eq!(health.state, frink_api::HealthState::Ready);
8148        assert!(health.pid > 0);
8149        assert!(health.server_time_unix_ms > 0);
8150        // Nothing has been served yet: the field is absent rather than
8151        // claiming a request happened at time zero.
8152        assert_eq!(health.last_request_age_seconds, None);
8153
8154        // Every control the UI might grey out has a code it can switch
8155        // on and a sentence it can show.
8156        for id in [
8157            frink_api::health::capability::CPU,
8158            frink_api::health::capability::METAL,
8159            frink_api::health::capability::CUDA,
8160            frink_api::health::capability::REAL_WEIGHTS,
8161            frink_api::health::capability::CONTINUOUS_BATCHING,
8162        ] {
8163            let cap = health
8164                .capability(id)
8165                .unwrap_or_else(|| panic!("{id} missing"));
8166            assert!(!cap.reason.is_empty(), "{cap:?}");
8167            assert!(!cap.detail.is_empty(), "{cap:?}");
8168        }
8169        // The test app serves synthetic random weights, and health must
8170        // say so: a UI that presents noise as a model invites a bug
8171        // report about "quality".
8172        let weights = health
8173            .capability(frink_api::health::capability::REAL_WEIGHTS)
8174            .unwrap();
8175        assert!(!weights.available);
8176        assert_eq!(weights.reason, frink_api::health::reason::MODEL_NOT_LOADED);
8177        assert!(health.model.as_ref().unwrap().synthetic_weights);
8178    }
8179
8180    #[tokio::test]
8181    async fn health_vouches_for_liveness_after_a_request_has_been_served() {
8182        let app = test_app();
8183        let _ = post_json(
8184            &app,
8185            serde_json::json!({
8186                "model": "m",
8187                "messages": [{"role": "user", "content": "\u{1}"}],
8188                "max_tokens": 1,
8189                "temperature": 0,
8190            }),
8191        )
8192        .await;
8193        let (_status, body) = get_json(&app, frink_api::routes::HEALTH).await;
8194        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
8195        let age = health
8196            .last_request_age_seconds
8197            .expect("a served request is evidence of liveness");
8198        assert!((0.0..5.0).contains(&age), "implausible age {age}");
8199    }
8200
8201    /// Every `data:` payload of an SSE response body, `[DONE]` excluded.
8202    async fn post_sse_chunks(app: &Router, body: serde_json::Value) -> Vec<serde_json::Value> {
8203        use http_body_util::BodyExt;
8204        use tower::ServiceExt;
8205
8206        let response = app
8207            .clone()
8208            .oneshot(
8209                axum::http::Request::builder()
8210                    .method("POST")
8211                    .uri("/v1/chat/completions")
8212                    .header("content-type", "application/json")
8213                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
8214                    .unwrap(),
8215            )
8216            .await
8217            .unwrap();
8218        let bytes = response.into_body().collect().await.unwrap().to_bytes();
8219        String::from_utf8(bytes.to_vec())
8220            .unwrap()
8221            .lines()
8222            .filter_map(|line| line.strip_prefix("data: "))
8223            .filter(|payload| *payload != "[DONE]")
8224            .map(|payload| serde_json::from_str(payload).unwrap())
8225            .collect()
8226    }
8227
8228    #[tokio::test]
8229    async fn a_stream_states_its_request_id_once_in_the_first_chunk() {
8230        let app = test_app();
8231        let chunks = post_sse_chunks(
8232            &app,
8233            serde_json::json!({
8234                "model": "m",
8235                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8236                "max_tokens": 4,
8237                "temperature": 0,
8238                "stream": true,
8239            }),
8240        )
8241        .await;
8242
8243        assert!(!chunks.is_empty());
8244        let request_id = chunks[0]["request_id"]
8245            .as_str()
8246            .expect("the first chunk names the request")
8247            .to_string();
8248        assert!(request_id.starts_with("chatcmpl-"), "{request_id}");
8249        // Once, and before any content: a client that reads the id from
8250        // chunk zero never has to correlate by heuristic.
8251        for (i, chunk) in chunks.iter().enumerate().skip(1) {
8252            assert!(
8253                chunk.get("request_id").is_none(),
8254                "chunk {i} repeats request_id"
8255            );
8256        }
8257        // Every chunk of one stream carries the same `id`, and it is
8258        // that request id -- not a shared constant.
8259        for chunk in &chunks {
8260            assert_eq!(chunk["id"], serde_json::json!(request_id));
8261        }
8262
8263        let other = post_sse_chunks(
8264            &app,
8265            serde_json::json!({
8266                "model": "m",
8267                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8268                "max_tokens": 4,
8269                "temperature": 0,
8270                "stream": true,
8271            }),
8272        )
8273        .await;
8274        assert_ne!(
8275            other[0]["request_id"].as_str().unwrap(),
8276            request_id,
8277            "two concurrent chats must not share an id"
8278        );
8279    }
8280
8281    #[tokio::test]
8282    async fn a_non_streamed_response_names_the_same_request_id_as_its_completion_id() {
8283        let app = test_app();
8284        let resp = post_json(
8285            &app,
8286            serde_json::json!({
8287                "model": "m",
8288                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8289                "max_tokens": 2,
8290                "temperature": 0,
8291            }),
8292        )
8293        .await;
8294        assert_eq!(resp["id"], resp["request_id"]);
8295        assert!(resp["request_id"]
8296            .as_str()
8297            .unwrap()
8298            .starts_with("chatcmpl-"));
8299    }
8300
8301    /// The whole point of server-reported timings: a client can tell
8302    /// prefill from decode without a stopwatch (see `frink_api::usage`).
8303    #[tokio::test]
8304    async fn usage_carries_separate_prefill_and_decode_timings() {
8305        let app = test_app();
8306        let resp = post_json(
8307            &app,
8308            serde_json::json!({
8309                "model": "m",
8310                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8311                "max_tokens": 4,
8312                "temperature": 0,
8313            }),
8314        )
8315        .await;
8316        let usage = &resp["usage"];
8317        assert!(usage["prompt_eval_duration_ms"].is_number(), "{usage}");
8318        assert!(usage["generation_duration_ms"].is_number(), "{usage}");
8319        assert!(usage["time_to_first_token_ms"].is_number(), "{usage}");
8320        assert!(usage["predicted_per_second"].is_number(), "{usage}");
8321        // No prefix cache in this app: the field must be absent, not 0.
8322        assert!(usage.get("cached_tokens").is_none(), "{usage}");
8323    }
8324
8325    /// A real, deterministic small model with random weights will not
8326    /// spontaneously produce a `<tool_call>{...}</tool_call>` marker
8327    /// (whether a real deployed model does is a property of that
8328    /// model, not of frink's plumbing) -- so the real, testable
8329    /// end-to-end property here is that a `tools`-bearing request
8330    /// whose output does NOT contain the marker falls through cleanly
8331    /// to an ordinary text response instead of erroring or panicking.
8332    #[tokio::test]
8333    async fn a_tools_request_with_no_marker_in_the_output_falls_back_to_plain_content() {
8334        let app = test_app();
8335        let body = serde_json::json!({
8336            "model": "m",
8337            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8338            "max_tokens": 4,
8339            "temperature": 0,
8340            "tools": [weather_tool()],
8341        });
8342        let resp = post_json(&app, body).await;
8343        let message = &resp["choices"][0]["message"];
8344        assert!(
8345            message["content"].is_string(),
8346            "must fall back to plain content when no real tool-call marker is present: {resp:?}"
8347        );
8348        assert!(message.get("tool_calls").is_none());
8349        // Truncated at max_tokens, so the honest finish reason is
8350        // "length" -- the point here is only that it is NOT
8351        // "tool_calls".
8352        assert_eq!(resp["choices"][0]["finish_reason"], "length");
8353    }
8354
8355    /// A whole-response cache hit must be indistinguishable from
8356    /// recomputing: same content, same (honest) finish_reason, same
8357    /// usage counts -- only the `frink_cache` marker may differ.
8358    #[tokio::test]
8359    async fn a_cache_hit_reports_the_original_finish_reason_and_usage() {
8360        let app = test_app();
8361        let body = serde_json::json!({
8362            "model": "m",
8363            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8364            "max_tokens": 3,
8365            "temperature": 0,
8366        });
8367        let first = post_json(&app, body.clone()).await;
8368        assert_eq!(first["frink_cache"], "miss");
8369        let second = post_json(&app, body).await;
8370        assert_eq!(second["frink_cache"], "hit");
8371        assert_eq!(
8372            first["choices"][0]["message"]["content"],
8373            second["choices"][0]["message"]["content"]
8374        );
8375        assert_eq!(
8376            first["choices"][0]["finish_reason"],
8377            second["choices"][0]["finish_reason"]
8378        );
8379        assert_eq!(first["usage"], second["usage"]);
8380        assert_eq!(second["usage"]["completion_tokens"], 3);
8381    }
8382
8383    /// The whole of #35 through the real router: a request that adds a
8384    /// GRAMMAR to a body already answered without one must be generated
8385    /// afresh, under that grammar.
8386    ///
8387    /// The cache used to be consulted before
8388    /// `generation_params_for_template` had even compiled the grammar,
8389    /// and the key held no trace of it, so the constrained request was
8390    /// handed the previous caller's unconstrained prose with a 200. The
8391    /// answer is asserted, not the key: a key that differs proves
8392    /// nothing if the lookup uses something else.
8393    #[tokio::test]
8394    async fn a_grammar_request_is_not_answered_from_an_unconstrained_cache_entry() {
8395        let app = test_app();
8396        let plain = serde_json::json!({
8397            "model": "m",
8398            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8399            "max_tokens": 3,
8400            "temperature": 0,
8401        });
8402
8403        let first = post_json(&app, plain.clone()).await;
8404        assert_eq!(first["frink_cache"], "miss");
8405        let unconstrained = first["choices"][0]["message"]["content"]
8406            .as_str()
8407            .expect("content")
8408            .to_string();
8409
8410        let mut constrained = plain.clone();
8411        constrained["grammar"] = serde_json::json!("root ::= \"yes\"");
8412        let second = post_json(&app, constrained).await;
8413        assert_eq!(
8414            second["frink_cache"], "miss",
8415            "a grammar is part of the key, so this body has never been answered"
8416        );
8417        // The synthetic demo model wraps its decode in a banner, so the
8418        // assertion is on the decoded text inside it: `yes` is the only
8419        // string this grammar admits, and it is there.
8420        let constrained_answer = second["choices"][0]["message"]["content"]
8421            .as_str()
8422            .expect("content")
8423            .to_string();
8424        assert!(
8425            constrained_answer.contains("-> \"yes\"]"),
8426            "the grammar must have been compiled AND applied, not skipped \
8427             by a cache hit: {constrained_answer}"
8428        );
8429        assert_ne!(
8430            constrained_answer, unconstrained,
8431            "the constrained request was served the unconstrained answer"
8432        );
8433
8434        // And the entry the first request made is still the first
8435        // request's: the miss above is the grammar, not a key that
8436        // fails to repeat.
8437        let third = post_json(&app, plain).await;
8438        assert_eq!(third["frink_cache"], "hit");
8439        assert_eq!(third["choices"][0]["message"]["content"], unconstrained);
8440    }
8441
8442    /// The third of #35's fields, and the one whose old failure was
8443    /// LOUD: `validate_json_object_output` runs against whatever came
8444    /// back, so a `json_object` request answered from a cached prose
8445    /// entry got a hard 400 for a body that had never been generated
8446    /// under the JSON mask at all.
8447    ///
8448    /// The system message is what makes this reproducible, and it is the
8449    /// repo's own bug shape underneath. `inject_json_object_system_hint`
8450    /// usually leaves a fingerprint in the PROMPT, which happened to
8451    /// split the two keys apart -- a correctness property nothing stated
8452    /// or enforced, resting on a string edit made for a different
8453    /// reason. Its `!s.contains("JSON")` arm is the hole: a caller who
8454    /// already says "JSON" in their own system message gets NO hint
8455    /// appended, so the two requests render byte-identical prompts and
8456    /// the old key could not tell them apart.
8457    ///
8458    /// The synthetic model emits its demo banner under either mask, so
8459    /// the 400 is the same on both sides of this fix and cannot be the
8460    /// assertion; the cache-level twin in `response_cache` asserts the
8461    /// answer. What is asserted here is that the answer did not come
8462    /// from the other request's entry.
8463    #[tokio::test]
8464    async fn a_json_object_request_does_not_reuse_the_unconstrained_cache_entry() {
8465        let state = Arc::new(test_state(
8466            test_model_full_byte_vocab(),
8467            ResponseCache::new(1000, Duration::from_secs(3600)),
8468        ));
8469        let app = test_app_with_state(state.clone());
8470        let plain = serde_json::json!({
8471            "model": "m",
8472            "messages": [
8473                {"role": "system", "content": "Answer in JSON when it helps."},
8474                {"role": "user", "content": "\u{1}\u{2}"},
8475            ],
8476            "max_tokens": 3,
8477            "temperature": 0,
8478        });
8479
8480        let first = post_json(&app, plain.clone()).await;
8481        assert_eq!(first["frink_cache"], "miss");
8482        assert_eq!(state.cache_stats().entries, 1);
8483
8484        let mut as_json = plain.clone();
8485        as_json["response_format"] = serde_json::json!({"type": "json_object"});
8486        let (status, _) = post_json_uri(&app, "/v1/chat/completions", as_json).await;
8487        assert_eq!(
8488            status,
8489            StatusCode::BAD_REQUEST,
8490            "the demo banner is not a JSON object, whoever generated it"
8491        );
8492        assert_eq!(
8493            state.cache_stats().hits,
8494            0,
8495            "a json_object request must not be answered from an entry the \
8496             JSON mask never produced"
8497        );
8498        assert_eq!(
8499            state.cache_stats().entries,
8500            2,
8501            "json_object must key its own entry, not reuse the unconstrained \
8502             one it happens to render the same prompt as"
8503        );
8504    }
8505
8506    /// The same failure for `ignore_eos`, whose whole purpose is that a
8507    /// benchmarking run produces EXACTLY `max_tokens`. Answered from a
8508    /// cache entry the model's own EOS had cut short, it produced the
8509    /// short answer instead -- the one outcome the field exists to rule
8510    /// out (#35).
8511    ///
8512    /// `0x77` is the id this model greedily emits SECOND for the prompt
8513    /// below, so with it as the EOS the plain request stops after one
8514    /// token and the `ignore_eos` one runs the whole budget. Asserted on
8515    /// the token count and the finish reason, which is where a replayed
8516    /// answer shows.
8517    #[tokio::test]
8518    async fn an_ignore_eos_request_is_not_answered_from_a_cache_entry_that_stopped_at_eos() {
8519        let app = test_app_with_state(Arc::new(test_state(
8520            test_model_full_byte_vocab_with_eos(Some(0x77)),
8521            ResponseCache::new(1000, Duration::from_secs(3600)),
8522        )));
8523        let body = serde_json::json!({
8524            "model": "m",
8525            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8526            "max_tokens": 6,
8527            "temperature": 0,
8528        });
8529
8530        let stopped = post_json(&app, body.clone()).await;
8531        assert_eq!(stopped["frink_cache"], "miss");
8532        assert_eq!(
8533            stopped["choices"][0]["finish_reason"], "stop",
8534            "the fixture is only meaningful if the model's EOS really fires here"
8535        );
8536        assert_eq!(stopped["usage"]["completion_tokens"], 1);
8537
8538        let mut ignoring = body.clone();
8539        ignoring["ignore_eos"] = serde_json::json!(true);
8540        let ran_on = post_json(&app, ignoring).await;
8541        assert_eq!(
8542            ran_on["frink_cache"], "miss",
8543            "ignore_eos is part of the key, so this body has never been answered"
8544        );
8545        assert_eq!(
8546            ran_on["usage"]["completion_tokens"], 6,
8547            "ignore_eos must run the full budget, not replay the EOS-terminated answer"
8548        );
8549        assert_eq!(ran_on["choices"][0]["finish_reason"], "length");
8550        assert_ne!(
8551            ran_on["choices"][0]["message"]["content"],
8552            stopped["choices"][0]["message"]["content"]
8553        );
8554    }
8555
8556    /// The real proof for session reuse:
8557    /// a two-request session where the second request sends only its
8558    /// new message must produce exactly the same output as manually
8559    /// resending the full history (built from the *real* first reply,
8560    /// not an assumed one) with no `session_id` at all.
8561    #[tokio::test]
8562    async fn session_reuse_produces_the_same_output_as_manually_resending_full_history() {
8563        let session_app = test_app();
8564        let manual_app = test_app();
8565
8566        // Turn 1, via session.
8567        let turn1 = post_json(
8568            &session_app,
8569            serde_json::json!({
8570                "model": "m",
8571                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8572                "session_id": "s1",
8573                "max_tokens": 5,
8574                "temperature": 0,
8575            }),
8576        )
8577        .await;
8578        let reply1 = turn1["choices"][0]["message"]["content"]
8579            .as_str()
8580            .unwrap()
8581            .to_string();
8582
8583        // Turn 1, manually, for comparison -- must match exactly
8584        // (trivially, since it's the literal same single-turn
8585        // request), confirming the session path's first turn isn't
8586        // doing anything different from a plain request.
8587        let manual_turn1 = post_json(
8588            &manual_app,
8589            serde_json::json!({
8590                "model": "m",
8591                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8592                "max_tokens": 5,
8593                "temperature": 0,
8594            }),
8595        )
8596        .await;
8597        assert_eq!(
8598            manual_turn1["choices"][0]["message"]["content"]
8599                .as_str()
8600                .unwrap(),
8601            reply1
8602        );
8603
8604        // Turn 2, via session: sends ONLY the new message.
8605        let turn2 = post_json(
8606            &session_app,
8607            serde_json::json!({
8608                "model": "m",
8609                "messages": [{"role": "user", "content": "\u{4}\u{5}"}],
8610                "session_id": "s1",
8611                "max_tokens": 5,
8612                "temperature": 0,
8613            }),
8614        )
8615        .await;
8616        let reply2 = turn2["choices"][0]["message"]["content"]
8617            .as_str()
8618            .unwrap()
8619            .to_string();
8620
8621        // Turn 2, manually: the full three-message history
8622        // reconstructed using the REAL reply1 text, with no
8623        // session_id -- must produce byte-identical output.
8624        let manual_turn2 = post_json(
8625            &manual_app,
8626            serde_json::json!({
8627                "model": "m",
8628                "messages": [
8629                    {"role": "user", "content": "\u{1}\u{2}\u{3}"},
8630                    {"role": "assistant", "content": reply1},
8631                    {"role": "user", "content": "\u{4}\u{5}"},
8632                ],
8633                "max_tokens": 5,
8634                "temperature": 0,
8635            }),
8636        )
8637        .await;
8638        assert_eq!(
8639            manual_turn2["choices"][0]["message"]["content"]
8640                .as_str()
8641                .unwrap(),
8642            reply2,
8643            "resuming a session must produce identical output to manually resending the full history"
8644        );
8645    }
8646
8647    /// `lock_cache` must return a usable guard even after the mutex was
8648    /// poisoned by a panic elsewhere.
8649    #[test]
8650    fn lock_cache_recovers_from_a_poisoned_mutex() {
8651        let cache = Arc::new(Mutex::new(ResponseCache::new(10, Duration::from_secs(60))));
8652
8653        let poison_cache = Arc::clone(&cache);
8654        let _ = std::thread::spawn(move || {
8655            let _guard = poison_cache.lock().unwrap();
8656            panic!("simulated panic while holding the lock");
8657        })
8658        .join();
8659
8660        // A plain `.lock().unwrap()` would panic here; lock_cache must not.
8661        let recovered = lock_cache(&cache);
8662        assert_eq!(recovered.stats().entries, 0);
8663    }
8664
8665    #[test]
8666    fn is_cacheable_true_for_greedy_or_seeded_requests() {
8667        let mut req_body = serde_json::json!({
8668            "model": "m",
8669            "messages": [{"role": "user", "content": "hi"}],
8670        });
8671        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8672        assert!(
8673            req.is_cacheable(),
8674            "default (temperature 0) must be cacheable"
8675        );
8676
8677        req_body["temperature"] = serde_json::json!(0.8);
8678        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8679        assert!(
8680            !req.is_cacheable(),
8681            "unseeded sampling must never be cacheable"
8682        );
8683
8684        req_body["seed"] = serde_json::json!(42);
8685        let req: ChatCompletionRequest = serde_json::from_value(req_body).unwrap();
8686        assert!(
8687            req.is_cacheable(),
8688            "sampling with an explicit seed is deterministic and must be cacheable"
8689        );
8690    }
8691
8692    /// A template that grades only the OpenAI triple. `raise_exception`
8693    /// is how a real one rejects a value it does not know, which is what
8694    /// makes the load-time probe able to learn the vocabulary at all.
8695    const GRADED: &str = "{% if reasoning_effort %}\
8696         {% if reasoning_effort not in ['low','medium','high'] %}\
8697           {{ raise_exception('unsupported effort') }}\
8698         {% endif %}E:{{ reasoning_effort }}|{% endif %}\
8699         {% if enable_thinking %}THINK|{% endif %}{{ messages[0].content }}";
8700
8701    fn graded_template() -> chat_template::PromptTemplate {
8702        chat_template::PromptTemplate::from_gguf_metadata(
8703            Some(GRADED),
8704            Some("qwen3"),
8705            false,
8706            true,
8707            None,
8708            None,
8709        )
8710    }
8711
8712    fn chat_request(value: serde_json::Value) -> ChatCompletionRequest {
8713        serde_json::from_value(value).expect("request")
8714    }
8715
8716    /// The wire field reaches the sampler, compiled.
8717    ///
8718    /// Serde is the failure mode here, not the grammar engine: an
8719    /// undeclared field is dropped silently and the caller is served
8720    /// unconstrained text with a 200, which is exactly why `logit_bias`
8721    /// is declared on this struct only to be refused by name.
8722    #[test]
8723    fn a_grammar_on_the_chat_wire_reaches_the_generation_params() {
8724        let req = chat_request(serde_json::json!({
8725            "model": "m",
8726            "messages": [{"role": "user", "content": "hi"}],
8727            "grammar": "root ::= \"a\"+",
8728        }));
8729        req.validate_supported_fields()
8730            .expect("a valid grammar is a valid request");
8731        let params = req
8732            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8733            .expect("a valid grammar compiles at params time too");
8734        assert!(
8735            params.grammar.is_some(),
8736            "the grammar was dropped between the wire and the sampler"
8737        );
8738        assert!(
8739            params.needs_vocab_logits(),
8740            "a grammar request that may fold lm_head into a GPU argmax is \
8741             a grammar request served unconstrained"
8742        );
8743
8744        let plain = chat_request(serde_json::json!({
8745            "model": "m",
8746            "messages": [{"role": "user", "content": "hi"}],
8747        }));
8748        assert!(plain
8749            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8750            .unwrap()
8751            .grammar
8752            .is_none());
8753    }
8754
8755    fn tool_request(tool_choice: serde_json::Value) -> ChatCompletionRequest {
8756        chat_request(serde_json::json!({
8757            "model": "m",
8758            "messages": [{"role": "user", "content": "weather in Rome?"}],
8759            "tools": [weather_tool()],
8760            "tool_choice": tool_choice,
8761        }))
8762    }
8763
8764    /// `tool_choice: "required"` used to be a 501. It now compiles the
8765    /// offered tools into a grammar that rides on the params, which is
8766    /// the only thing every decode path shares.
8767    #[test]
8768    fn a_forced_tool_choice_puts_a_grammar_on_the_generation_params() {
8769        for choice in [
8770            serde_json::json!("required"),
8771            serde_json::json!({"type": "function", "function": {"name": "get_weather"}}),
8772        ] {
8773            let req = tool_request(choice.clone());
8774            req.validate_supported_fields()
8775                .unwrap_or_else(|e| panic!("{choice} is a valid request: {e:?}"));
8776            let params = req
8777                .generation_params_for_template(
8778                    &graded_template(),
8779                    "Qwen3-8B",
8780                    crate::sampling_knobs::SamplerModel::absent(),
8781                )
8782                .unwrap_or_else(|e| panic!("{choice} compiles: {e:?}"));
8783            let grammar = params
8784                .grammar
8785                .as_ref()
8786                .unwrap_or_else(|| panic!("{choice} was accepted and then not enforced"));
8787            assert!(
8788                grammar.is_awaiting_trigger(),
8789                "the model must be free to think before it calls"
8790            );
8791            assert!(
8792                !grammar.allows_eog(),
8793                "{choice} must not be able to end the turn without a call"
8794            );
8795            // The bug that has been fixed three times: a constrained
8796            // request that lets a backend fold lm_head+argmax on device
8797            // is a constrained request served unconstrained. A LAZY
8798            // grammar needs the vocabulary from the FIRST token, because
8799            // its trigger can fire on any of them.
8800            assert!(
8801                params.needs_vocab_logits(),
8802                "{choice} would let a backend return a token id instead of logits"
8803            );
8804            assert!(
8805                !generate::greedy_gpu_fold_allowed(&params),
8806                "{choice} at temperature 0 must still refuse the greedy GPU fold"
8807            );
8808        }
8809    }
8810
8811    /// `auto` and `none` force nothing, and must not acquire a grammar.
8812    #[test]
8813    fn an_unforced_tool_choice_leaves_the_generation_unconstrained() {
8814        for choice in [serde_json::json!("auto"), serde_json::json!("none")] {
8815            let req = tool_request(choice.clone());
8816            req.validate_supported_fields().expect("still supported");
8817            let params = match req.generation_params_for_template(
8818                &graded_template(),
8819                "Qwen3-8B",
8820                crate::sampling_knobs::SamplerModel::absent(),
8821            ) {
8822                Ok(p) => p,
8823                Err((status, _)) => panic!("{choice} has no constraint to compile: {status}"),
8824            };
8825            assert!(
8826                params.grammar.is_none(),
8827                "{choice} does not force a call and must not be constrained"
8828            );
8829        }
8830    }
8831
8832    /// Every refusal a forced choice can produce names the field, and
8833    /// none of them is a silent downgrade to `auto`.
8834    #[test]
8835    fn a_forced_tool_choice_refuses_rather_than_quietly_not_forcing() {
8836        // No tools to choose between.
8837        let req = chat_request(serde_json::json!({
8838            "model": "m",
8839            "messages": [{"role": "user", "content": "hi"}],
8840            "tool_choice": "required",
8841        }));
8842        let (status, _) = req
8843            .validate_supported_fields()
8844            .expect_err("nothing to call");
8845        assert_eq!(status, StatusCode::BAD_REQUEST);
8846
8847        // A name that is not on offer.
8848        let req =
8849            tool_request(serde_json::json!({"type": "function", "function": {"name": "nope"}}));
8850        let (status, Json(body)) = req.validate_supported_fields().expect_err("no such tool");
8851        assert_eq!(status, StatusCode::BAD_REQUEST);
8852        assert_eq!(body["error"]["param"], "tool_choice");
8853
8854        // An object that names nothing at all.
8855        let req = tool_request(serde_json::json!({"type": "function"}));
8856        let (status, _) = req.validate_supported_fields().expect_err("names nothing");
8857        assert_eq!(status, StatusCode::BAD_REQUEST);
8858
8859        // Two constraints on one generation.
8860        let req = chat_request(serde_json::json!({
8861            "model": "m",
8862            "messages": [{"role": "user", "content": "hi"}],
8863            "tools": [weather_tool()],
8864            "tool_choice": "required",
8865            "grammar": "root ::= \"a\"+",
8866        }));
8867        let (status, _) = req
8868            .validate_supported_fields()
8869            .expect_err("a grammar and a forced call are two constraints");
8870        assert_eq!(status, StatusCode::BAD_REQUEST);
8871
8872        // A checkpoint whose wire format has no grammar is refused by
8873        // name at params time, when the served model is known. GLM and
8874        // gemma4 both used to stand here and are forced now;
8875        // muse_glimmer is the one `tool_grammar::wire::shape` still
8876        // refuses, and the refusal says which format and why.
8877        let req = tool_request(serde_json::json!("required"));
8878        let (status, Json(body)) = match req.generation_params_for_template(
8879            &graded_template(),
8880            "muse-glimmer-8b",
8881            crate::sampling_knobs::SamplerModel::absent(),
8882        ) {
8883            Err(e) => e,
8884            Ok(_) => panic!("a muse_glimmer call's boundary is a channel, not a marker"),
8885        };
8886        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
8887        assert!(
8888            body["error"]["message"]
8889                .as_str()
8890                .unwrap()
8891                .contains("muse_glimmer"),
8892            "{body}"
8893        );
8894
8895        // And the format this once refused is served: a served model
8896        // whose name resolves to gemma4 reaches a grammar rather than a
8897        // 501. `generation_params_for_template` is the only place a
8898        // forced choice becomes one, so this is the request-level
8899        // evidence that the wire work is wired.
8900        let req = tool_request(serde_json::json!("required"));
8901        let params = req
8902            .generation_params_for_template(
8903                &graded_template(),
8904                "gemma-4-E2B-it",
8905                crate::sampling_knobs::SamplerModel::absent(),
8906            )
8907            .expect("a gemma4 forced tool_choice is served");
8908        assert!(
8909            params.grammar.is_some(),
8910            "a forced tool_choice must arrive as the generation's grammar"
8911        );
8912    }
8913
8914    /// A grammar that does not parse is refused before any work, and
8915    /// the refusal names the field and the parser's own diagnostic.
8916    #[test]
8917    fn an_unparseable_grammar_on_the_chat_wire_is_a_400() {
8918        let req = chat_request(serde_json::json!({
8919            "model": "m",
8920            "messages": [{"role": "user", "content": "hi"}],
8921            "grammar": "root ::= \"a",
8922        }));
8923        let (status, Json(body)) = req
8924            .validate_supported_fields()
8925            .expect_err("this does not parse");
8926        assert_eq!(status, StatusCode::BAD_REQUEST);
8927        assert_eq!(body["error"]["param"], "grammar");
8928        assert!(
8929            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
8930                .is_err(),
8931            "and again at params time"
8932        );
8933    }
8934
8935    /// `response_format: json_schema` used to be a 501 naming the
8936    /// missing converter. It is served now, and the request-level
8937    /// evidence is that the schema reaches `generation_params` as a
8938    /// grammar -- there is exactly one place a `response_format` is
8939    /// decided, so a route that validated it and then forgot to apply
8940    /// it is the failure this asserts against.
8941    #[test]
8942    fn response_format_json_schema_becomes_the_requests_grammar() {
8943        let req = chat_request(serde_json::json!({
8944            "model": "m",
8945            "messages": [{"role": "user", "content": "hi"}],
8946            "response_format": {
8947                "type": "json_schema",
8948                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
8949            },
8950        }));
8951        req.validate_supported_fields()
8952            .expect("a boolean schema converts");
8953        let params = req
8954            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8955            .expect("and compiles");
8956        let grammar = params.grammar.expect("the schema is the grammar");
8957        let mut g = (*grammar).clone();
8958        g.accept_token(0, b"true").expect("a boolean is accepted");
8959        assert!(g.allows_eog(), "and completes the parse");
8960        assert!(
8961            !params.json_object,
8962            "a schema is not the json_object character-class mask"
8963        );
8964    }
8965
8966    /// A schema the converter will not compile is a 400 naming the
8967    /// keyword, at both the validation and the params seam -- never a
8968    /// 500, and never a grammar that is approximately the schema.
8969    #[test]
8970    fn an_unconvertible_response_format_schema_is_a_400_naming_the_keyword() {
8971        let req = chat_request(serde_json::json!({
8972            "model": "m",
8973            "messages": [{"role": "user", "content": "hi"}],
8974            "response_format": {
8975                "type": "json_schema",
8976                "json_schema": {"name": "x", "schema": {"type": "integer", "minimum": 3}},
8977            },
8978        }));
8979        let (status, Json(body)) = req
8980            .validate_supported_fields()
8981            .expect_err("minimum has no grammar in this port");
8982        assert_eq!(status, StatusCode::BAD_REQUEST);
8983        assert!(
8984            body["error"]["message"]
8985                .as_str()
8986                .expect("a message")
8987                .contains("minimum"),
8988            "the refusal must name the keyword: {body}"
8989        );
8990        assert!(
8991            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
8992                .is_err(),
8993            "and again at params time"
8994        );
8995    }
8996
8997    /// A forced `tool_choice` and a `response_format` schema are two
8998    /// constraints on one generation. The refusal used to be spelled
8999    /// against `self.grammar` alone, so the schema spelling walked past
9000    /// it and `generation_params_for_template` overwrote the schema's
9001    /// grammar with the tool-call one.
9002    #[test]
9003    fn a_forced_tool_choice_and_a_schema_are_two_constraints() {
9004        let req = chat_request(serde_json::json!({
9005            "model": "m",
9006            "messages": [{"role": "user", "content": "hi"}],
9007            "tool_choice": "required",
9008            "tools": [{
9009                "type": "function",
9010                "function": {"name": "f", "parameters": {"type": "object"}},
9011            }],
9012            "response_format": {
9013                "type": "json_schema",
9014                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
9015            },
9016        }));
9017        let (status, Json(body)) = req
9018            .validate_supported_fields()
9019            .expect_err("two constraints, one generation");
9020        assert_eq!(status, StatusCode::BAD_REQUEST);
9021        assert_eq!(body["error"]["param"], "tool_choice");
9022    }
9023
9024    /// A chat client that omits `max_tokens` wants an answer, not
9025    /// OpenAI's legacy 16-token completion fragment.
9026    #[test]
9027    fn an_omitted_output_budget_is_a_whole_answer_not_sixteen_tokens() {
9028        let req = chat_request(serde_json::json!({
9029            "model": "m",
9030            "messages": [{"role": "user", "content": "hi"}],
9031        }));
9032        assert_eq!(req.max_tokens, DEFAULT_CHAT_MAX_TOKENS);
9033    }
9034
9035    /// A knob the wire accepts must reach the sampler. Serde declaring
9036    /// `min_p` is only half of it: the field spent two commits resolved
9037    /// to a hardcoded `0.0` on both routes, which is exactly the
9038    /// silently-dropped-parameter bug, just one layer further in.
9039    #[test]
9040    fn min_p_reaches_the_sampler_from_the_chat_wire() {
9041        let asked = chat_request(serde_json::json!({
9042            "model": "m",
9043            "messages": [{"role": "user", "content": "hi"}],
9044            "min_p": 0.07,
9045        }));
9046        assert_eq!(
9047            asked
9048                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
9049                .expect("knobs")
9050                .min_p,
9051            0.07
9052        );
9053
9054        let silent = chat_request(serde_json::json!({
9055            "model": "m",
9056            "messages": [{"role": "user", "content": "hi"}],
9057        }));
9058        assert_eq!(
9059            silent
9060                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
9061                .expect("knobs")
9062                .min_p,
9063            0.0,
9064            "an unset min_p must be off, not llama.cpp's CLI default"
9065        );
9066    }
9067
9068    /// The whole-response cache is keyed on the sampler settings, and a
9069    /// setting left OUT of that key means two requests differing only in
9070    /// it share one answer: the second caller silently gets output
9071    /// computed under the first caller's parameters.
9072    ///
9073    /// Every knob the wire accepts is checked, not just the new one --
9074    /// this is the assertion that would have caught `min_p` being added
9075    /// to the sampler and forgotten here.
9076    #[test]
9077    fn no_sampler_knob_is_missing_from_the_cache_key() {
9078        let base = serde_json::json!({
9079            "model": "m",
9080            "messages": [{"role": "user", "content": "hi"}],
9081            "seed": 1,
9082        });
9083        let key_for = |body: serde_json::Value| {
9084            let req = chat_request(body);
9085            let params = req
9086                .generation_params(crate::sampling_knobs::SamplerModel::absent())
9087                .expect("params");
9088            req.cache_key("prompt", &params)
9089        };
9090        let baseline = key_for(base.clone());
9091        for (knob, value) in [
9092            ("temperature", serde_json::json!(0.5)),
9093            ("top_p", serde_json::json!(0.9)),
9094            ("min_p", serde_json::json!(0.05)),
9095            ("top_k", serde_json::json!(40)),
9096            ("repetition_penalty", serde_json::json!(1.1)),
9097            ("presence_penalty", serde_json::json!(0.3)),
9098            ("frequency_penalty", serde_json::json!(0.3)),
9099            (
9100                "samplers",
9101                serde_json::json!(["penalties", "top_p", "top_k", "min_p", "temperature"]),
9102            ),
9103        ] {
9104            let mut body = base.clone();
9105            body[knob] = value;
9106            assert_ne!(
9107                key_for(body),
9108                baseline,
9109                "`{knob}` is not in the cache key: two requests differing \
9110                 only in it would share one cached answer"
9111            );
9112        }
9113    }
9114
9115    /// The sampler half's twin, for the constraints. Each of these
9116    /// changes the answer and changes NOTHING about the rendered
9117    /// prompt, so an omission is invisible until a caller compares two
9118    /// answers it never sees side by side (#35).
9119    ///
9120    /// `grammar` here is the wire field; `response_format:
9121    /// {"type":"json_schema"}` and a forced `tool_choice` compile to a
9122    /// grammar through the same `GenerationParams::grammar`, so they are
9123    /// keyed by the same field being keyed at all.
9124    #[test]
9125    fn no_constraint_is_missing_from_the_cache_key() {
9126        let base = serde_json::json!({
9127            "model": "m",
9128            "messages": [{"role": "user", "content": "pick one"}],
9129        });
9130        let key_for = |body: serde_json::Value| {
9131            let req = chat_request(body);
9132            let params = req
9133                .generation_params(crate::sampling_knobs::SamplerModel::absent())
9134                .expect("params");
9135            req.cache_key("prompt", &params)
9136        };
9137        let baseline = key_for(base.clone());
9138        for (field, value) in [
9139            ("grammar", serde_json::json!("root ::= \"yes\" | \"no\"")),
9140            (
9141                "response_format",
9142                serde_json::json!({"type": "json_object"}),
9143            ),
9144            (
9145                "response_format",
9146                serde_json::json!({"type": "json_schema", "json_schema": {
9147                    "name": "answer",
9148                    "schema": {"type": "object", "properties": {"a": {"type": "string"}}}
9149                }}),
9150            ),
9151            ("ignore_eos", serde_json::json!(true)),
9152            ("stop", serde_json::json!(["\n"])),
9153            ("max_tokens", serde_json::json!(7)),
9154        ] {
9155            let mut body = base.clone();
9156            body[field] = value.clone();
9157            assert_ne!(
9158                key_for(body),
9159                baseline,
9160                "`{field}: {value}` is not in the cache key: two requests \
9161                 differing only in it would share one cached answer"
9162            );
9163        }
9164    }
9165
9166    /// Serde already tells absent from zero -- an absent field became
9167    /// the default -- so a 0 here is one the caller wrote, and a
9168    /// zero-token budget is a request that can never become decodable.
9169    #[test]
9170    fn an_explicit_zero_output_budget_is_a_client_error() {
9171        let req = chat_request(serde_json::json!({
9172            "model": "m",
9173            "messages": [{"role": "user", "content": "hi"}],
9174            "max_tokens": 0,
9175        }));
9176        let (status, body) = req.validate_supported_fields().expect_err("rejected");
9177        assert_eq!(status, StatusCode::BAD_REQUEST);
9178        assert_eq!(body["error"]["param"], serde_json::json!("max_tokens"));
9179    }
9180
9181    /// The direction that had no wire path at all before: every request
9182    /// rendered in thinking mode because only the ON branch existed.
9183    #[test]
9184    fn a_request_can_turn_thinking_off() {
9185        let template = graded_template();
9186        for body in [
9187            serde_json::json!({
9188                "model": "m",
9189                "messages": [{"role": "user", "content": "hi"}],
9190                "reasoning_effort": "none",
9191            }),
9192            serde_json::json!({
9193                "model": "m",
9194                "messages": [{"role": "user", "content": "hi"}],
9195                "thinking": {"type": "disabled"},
9196            }),
9197        ] {
9198            let kwargs = chat_request(body).resolve_template_kwargs(&template);
9199            assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
9200            assert_eq!(kwargs["thinking_mode"], serde_json::json!("disabled"));
9201            // And `none` must not have been rounded onto a real gear on
9202            // the way: "do not think" is not "think a little".
9203            assert!(!kwargs.contains_key("reasoning_effort"));
9204        }
9205    }
9206
9207    /// The switch is what the caller reached for last; the gear is what
9208    /// they would have used had thinking been on.
9209    #[test]
9210    fn a_disabled_switch_beats_an_effort_in_the_same_request() {
9211        let template = graded_template();
9212        let kwargs = chat_request(serde_json::json!({
9213            "model": "m",
9214            "messages": [{"role": "user", "content": "hi"}],
9215            "reasoning_effort": "high",
9216            "thinking": {"type": "disabled"},
9217        }))
9218        .resolve_template_kwargs(&template);
9219        assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
9220        assert!(!kwargs.contains_key("reasoning_effort"));
9221    }
9222
9223    /// Read as "on", a misspelled switch silently serves the opposite
9224    /// of what was asked for.
9225    #[test]
9226    fn an_unrecognized_thinking_switch_is_refused_rather_than_read_as_on() {
9227        let req = chat_request(serde_json::json!({
9228            "model": "m",
9229            "messages": [{"role": "user", "content": "hi"}],
9230            "thinking": {"type": "disable"},
9231        }));
9232        let (status, _) = req.validate_supported_fields().expect_err("rejected");
9233        assert_eq!(status, StatusCode::BAD_REQUEST);
9234    }
9235
9236    /// A caller who steered the template themselves has said what they
9237    /// want; merging a protocol default in would let it contradict them.
9238    #[test]
9239    fn an_explicit_template_kwarg_stands_the_protocol_knobs_down() {
9240        let template = graded_template();
9241        let kwargs = chat_request(serde_json::json!({
9242            "model": "m",
9243            "messages": [{"role": "user", "content": "hi"}],
9244            "reasoning_effort": "none",
9245            "chat_template_kwargs": {"enable_thinking": true},
9246        }))
9247        .resolve_template_kwargs(&template);
9248        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
9249    }
9250
9251    /// The acceptance criterion for effort plumbing: an off-vocabulary
9252    /// value is quantized onto the nearest gear the checkpoint really
9253    /// grades, and the request renders instead of failing.
9254    #[test]
9255    fn an_off_vocabulary_reasoning_effort_is_quantized_rather_than_interpolated() {
9256        let template = graded_template();
9257        let req = chat_request(serde_json::json!({
9258            "model": "m",
9259            "messages": [{"role": "user", "content": "hi"}],
9260            "reasoning_effort": "minimal",
9261        }));
9262        let kwargs = req.resolve_template_kwargs(&template);
9263        assert_eq!(kwargs["reasoning_effort"], serde_json::json!("low"));
9264        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
9265        assert!(prompt.starts_with("E:low|"), "{prompt}");
9266    }
9267
9268    /// The other half of the same rule: a value no gear is close enough
9269    /// to is dropped, so the checkpoint's own default applies rather
9270    /// than an unknown string reaching the prompt.
9271    #[test]
9272    fn an_effort_with_no_near_gear_is_dropped_so_the_template_default_applies() {
9273        let template = graded_template();
9274        let req = chat_request(serde_json::json!({
9275            "model": "m",
9276            "messages": [{"role": "user", "content": "hi"}],
9277            "chat_template_kwargs": {"reasoning_effort": "none"},
9278        }));
9279        let kwargs = req.resolve_template_kwargs(&template);
9280        assert!(!kwargs.contains_key("reasoning_effort"));
9281        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
9282        assert_eq!(prompt, "hi");
9283    }
9284
9285    /// `chat_template_kwargs` is the specific spelling and wins over the
9286    /// top-level one, which is what a caller who wrote both meant.
9287    #[test]
9288    fn chat_template_kwargs_wins_over_the_top_level_reasoning_effort() {
9289        let template = graded_template();
9290        let req = chat_request(serde_json::json!({
9291            "model": "m",
9292            "messages": [{"role": "user", "content": "hi"}],
9293            "reasoning_effort": "low",
9294            "chat_template_kwargs": {"reasoning_effort": "high"},
9295        }));
9296        assert_eq!(
9297            req.resolve_template_kwargs(&template)["reasoning_effort"],
9298            serde_json::json!("high")
9299        );
9300    }
9301
9302    /// Offering tools turns thinking on even when the caller asked for
9303    /// nothing: some encoders emit well-formed calls only in thinking
9304    /// mode.
9305    #[test]
9306    fn offering_tools_turns_thinking_on_by_itself() {
9307        let template = graded_template();
9308        let quiet = chat_request(serde_json::json!({
9309            "model": "m",
9310            "messages": [{"role": "user", "content": "hi"}],
9311        }));
9312        assert!(!quiet
9313            .resolve_template_kwargs(&template)
9314            .contains_key("enable_thinking"));
9315
9316        let with_tools = chat_request(serde_json::json!({
9317            "model": "m",
9318            "messages": [{"role": "user", "content": "hi"}],
9319            "tools": [{"type": "function", "function": {"name": "get_weather"}}],
9320        }));
9321        let kwargs = with_tools.resolve_template_kwargs(&template);
9322        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
9323        let prompt =
9324            prompt_from_messages(&with_tools.messages, &template, &[], kwargs).expect("renders");
9325        assert!(prompt.starts_with("THINK|"), "{prompt}");
9326    }
9327
9328    /// The reason `force_reasoning` could only ever be `false` before:
9329    /// no template could open a block in the prompt, because no kwargs
9330    /// reached one. Now that they do, the parser has to start inside it
9331    /// -- and the evidence is the rendered prompt, not the model name.
9332    #[test]
9333    fn a_prompt_that_opens_the_reasoning_block_makes_the_first_token_reasoning() {
9334        let opener = chat_template::PromptTemplate::from_gguf_metadata(
9335            Some("{{ messages[0].content }}{% if enable_thinking %}<think>{% endif %}"),
9336            Some("qwen3"),
9337            false,
9338            true,
9339            None,
9340            None,
9341        );
9342        let req = chat_request(serde_json::json!({
9343            "model": "m",
9344            "messages": [{"role": "user", "content": "hi"}],
9345            "chat_template_kwargs": {"enable_thinking": true},
9346        }));
9347        let kwargs = req.resolve_template_kwargs(&opener);
9348        let prompt = prompt_from_messages(&req.messages, &opener, &[], kwargs).expect("renders");
9349        assert!(prompt.ends_with("<think>"), "{prompt}");
9350
9351        // No opening marker will ever arrive, so unparsed this whole
9352        // deliberation would have been served as the answer.
9353        let posture = output::OutputPosture::resolve("Qwen3-8B", &prompt);
9354        let (message, _) = build_response_message(
9355            "weighing it up</think>Paris.".to_string(),
9356            &[],
9357            posture,
9358            "stop",
9359        );
9360        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
9361        assert_eq!(message.content.as_deref(), Some("Paris."));
9362
9363        // Same text, a prompt that did not open the block: the model
9364        // wrote a stray closer and it stays content.
9365        let closed = output::OutputPosture::resolve("Qwen3-8B", "<|im_start|>assistant\n");
9366        let (message, _) = build_response_message(
9367            "weighing it up</think>Paris.".to_string(),
9368            &[],
9369            closed,
9370            "stop",
9371        );
9372        assert_eq!(message.reasoning_content, None);
9373    }
9374
9375    #[test]
9376    fn stop_param_accepts_both_single_string_and_array() {
9377        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
9378            "model": "m",
9379            "messages": [{"role": "user", "content": "hi"}],
9380            "stop": "END",
9381        }))
9382        .unwrap();
9383        assert_eq!(req.stop_sequences(), vec!["END".to_string()]);
9384
9385        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
9386            "model": "m",
9387            "messages": [{"role": "user", "content": "hi"}],
9388            "stop": ["A", "B"],
9389        }))
9390        .unwrap();
9391        assert_eq!(req.stop_sequences(), vec!["A".to_string(), "B".to_string()]);
9392    }
9393
9394    #[test]
9395    fn run_generation_rejects_out_of_vocab_tokens_instead_of_panicking() {
9396        let model = test_model();
9397        let result = run_generation(
9398            &model,
9399            "hello",
9400            &greedy_params(4),
9401            None,
9402            None,
9403            None,
9404            None,
9405            None,
9406            None,
9407        );
9408        assert!(matches!(
9409            result,
9410            Err(generate::DecodeError::TokenOutOfVocab { .. })
9411        ));
9412    }
9413
9414    /// A pool that *could* serve this request but is momentarily fully
9415    /// held is the server being behind: 503, and retrying is honest
9416    /// advice because the blocks really do come back.
9417    #[test]
9418    fn run_generation_honors_an_exhausted_kv_pool_and_maps_it_to_a_503() {
9419        let model = test_model(); // 2 layers -> 2 blocks
9420        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9421        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
9422
9423        let holder_pool = Arc::clone(&pool);
9424        let holder = std::thread::spawn(move || {
9425            let mut held = frink_core::cache::KvCache::with_pool(1, 1, holder_pool, 0).unwrap();
9426            held.push(&[0.0], &[0.0]).unwrap(); // crosses into the second block
9427            std::thread::sleep(Duration::from_millis(200));
9428            drop(held);
9429        });
9430        std::thread::sleep(Duration::from_millis(15));
9431
9432        let config = generate::KvPoolConfig {
9433            pool,
9434            queue_wait: Duration::ZERO,
9435        };
9436        let result = run_generation(
9437            &model,
9438            &prompt,
9439            &greedy_params(4),
9440            Some(&config),
9441            None,
9442            None,
9443            None,
9444            None,
9445            None,
9446        );
9447        assert!(matches!(
9448            result,
9449            Err(generate::DecodeError::KvPoolExhausted)
9450        ));
9451
9452        let (status, _body) = decode_error_response(result.unwrap_err());
9453        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
9454        holder.join().unwrap();
9455    }
9456
9457    /// The same endpoint, the same pool size, a request too big for the
9458    /// *whole* pool: a 400 rather than a 503, because an idle server
9459    /// refuses it identically and `Retry-After` would be a promise
9460    /// nothing can keep.
9461    ///
9462    /// Confirmed to FAIL when `generate`'s `pool_immovable_refusal`
9463    /// check is removed: the status comes back 503.
9464    #[test]
9465    fn a_request_too_big_for_the_whole_pool_is_a_400_not_a_retryable_503() {
9466        let model = test_model(); // 2 layers
9467        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9468        // One block, two layers: no schedule ever serves this.
9469        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 1)));
9470        let config = generate::KvPoolConfig {
9471            pool,
9472            queue_wait: Duration::ZERO,
9473        };
9474
9475        let result = run_generation(
9476            &model,
9477            &prompt,
9478            &greedy_params(4),
9479            Some(&config),
9480            None,
9481            None,
9482            None,
9483            None,
9484            None,
9485        );
9486        let err = result.expect_err("one block cannot hold two layers' caches");
9487        assert!(
9488            matches!(
9489                &err,
9490                generate::DecodeError::KvBudgetExceeded { binding, .. }
9491                    if *binding == frink_models::Ceiling::DeviceMemory.code()
9492            ),
9493            "expected an immovable device-memory refusal, got {err:?}"
9494        );
9495        let (status, _body) = decode_error_response(err);
9496        assert_eq!(status, StatusCode::BAD_REQUEST);
9497    }
9498
9499    /// A full admission queue is the server being behind, not the
9500    /// client being wrong: 503, with the wait hint in the body (and the
9501    /// `Retry-After` header stamped by `limits::retry_after`) and the
9502    /// depth and cap named so an operator can tell a retry storm from a
9503    /// single oversized request.
9504    #[test]
9505    fn decode_error_response_maps_a_full_queue_to_a_retryable_503() {
9506        let (status, Json(body)) = decode_error_response(generate::DecodeError::QueueFull {
9507            queued: 512,
9508            cap: 512,
9509        });
9510        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
9511        assert_eq!(body["error"]["retry_after_seconds"], 1);
9512        let message = body["error"]["message"].as_str().expect("message");
9513        assert!(message.contains("512"), "{message}");
9514    }
9515
9516    #[test]
9517    fn decode_error_response_omits_a_retry_hint_for_an_unretryable_error() {
9518        let (_status, Json(body)) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
9519            token: 99,
9520            vocab_size: 32,
9521        });
9522        assert!(
9523            body["error"]["retry_after_seconds"].is_null(),
9524            "retrying a prompt this model cannot tokenize never helps"
9525        );
9526    }
9527
9528    #[test]
9529    fn decode_error_response_maps_token_out_of_vocab_to_bad_request() {
9530        let (status, _body) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
9531            token: 99,
9532            vocab_size: 32,
9533        });
9534        assert_eq!(status, StatusCode::BAD_REQUEST);
9535    }
9536
9537    #[test]
9538    fn run_generation_succeeds_and_releases_blocks_when_the_pool_has_room() {
9539        let model = test_model(); // 2 layers
9540        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9541        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
9542        let config = generate::KvPoolConfig {
9543            pool: pool.clone(),
9544            queue_wait: Duration::ZERO,
9545        };
9546
9547        let produced = run_generation(
9548            &model,
9549            &prompt,
9550            &greedy_params(4),
9551            Some(&config),
9552            None,
9553            None,
9554            None,
9555            None,
9556            None,
9557        )
9558        .unwrap();
9559        assert_eq!(produced.choices[0].finish, FinishReason::Length);
9560        assert_eq!(
9561            pool.lock().unwrap().free_blocks(),
9562            2,
9563            "a completed request must return its blocks to the pool"
9564        );
9565    }
9566
9567    /// The core concurrency claim: two requests using the *same* `Arc<Model>`
9568    /// must be able to run their (independent, per-call) KV caches
9569    /// concurrently without interfering with each other or needing any
9570    /// shared lock around the model itself.
9571    #[tokio::test]
9572    async fn concurrent_requests_against_the_same_model_do_not_interfere() {
9573        let model = Arc::new(test_model());
9574        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9575
9576        let mut handles = Vec::new();
9577        for _ in 0..8 {
9578            let model = Arc::clone(&model);
9579            let prompt = prompt.clone();
9580            handles.push(tokio::task::spawn_blocking(move || {
9581                run_generation(
9582                    &model,
9583                    &prompt,
9584                    &greedy_params(6),
9585                    None,
9586                    None,
9587                    None,
9588                    None,
9589                    None,
9590                    None,
9591                )
9592                .unwrap()
9593            }));
9594        }
9595
9596        let mut results = Vec::new();
9597        for h in handles {
9598            results.push(h.await.unwrap());
9599        }
9600        // Same prompt, same seed, same (greedy) sampling, same
9601        // immutable model -> every concurrent run must produce
9602        // identical output, proving no request's KV cache leaked into
9603        // another's.
9604        for r in &results[1..] {
9605            // `.0` is the per-choice `(finish_reason, text)` list and
9606            // `.1` the usage, so this one comparison covers both the
9607            // text and the reason it stopped.
9608            assert_eq!(r.choices, results[0].choices, "choices must match");
9609            assert_eq!(
9610                r.usage.prompt_tokens, results[0].usage.prompt_tokens,
9611                "prompt token count must match"
9612            );
9613            assert_eq!(
9614                r.usage.completion_tokens, results[0].usage.completion_tokens,
9615                "completion token count must match"
9616            );
9617        }
9618    }
9619
9620    /// A real, minimal safetensors shard: JSON header (name -> real
9621    /// dtype/shape/`data_offsets`) followed by the concatenated raw
9622    /// F32 bytes -- exactly the format `ShardedSafetensors::open_index`
9623    /// parses, hand-built here rather than depending on
9624    /// `frink-models::kimi_loader`'s own private test helpers (not
9625    /// visible across the crate boundary).
9626    fn write_safetensors_shard(tensors: &[(String, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
9627        let mut header_entries = Vec::new();
9628        let mut data = Vec::new();
9629        for (name, shape, values) in tensors {
9630            let start = data.len();
9631            for v in values {
9632                data.extend_from_slice(&v.to_le_bytes());
9633            }
9634            let end = data.len();
9635            let shape_str = shape
9636                .iter()
9637                .map(|d| d.to_string())
9638                .collect::<Vec<_>>()
9639                .join(",");
9640            header_entries.push(format!(
9641                "\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{shape_str}],\"data_offsets\":[{start},{end}]}}"
9642            ));
9643        }
9644        let header = format!("{{{}}}", header_entries.join(","));
9645        let header_bytes = header.as_bytes();
9646        let mut out = Vec::with_capacity(8 + header_bytes.len() + data.len());
9647        out.extend_from_slice(&(header_bytes.len() as u64).to_le_bytes());
9648        out.extend_from_slice(header_bytes);
9649        out.extend_from_slice(&data);
9650        out
9651    }
9652
9653    /// Builds a small but completely real Kimi K3 checkpoint directory
9654    /// on disk (real `model.safetensors.index.json` + shard bytes +
9655    /// `tiktoken.model`, the exact file layout `frink-cli`'s
9656    /// `run-kimi` command expects) and loads it through
9657    /// `model::load_kimi_checkpoint_with_config` (the same real loading
9658    /// logic `model::load()` uses for `FRINK_MODEL_PATH` pointing at a
9659    /// directory, parametrized here only so the checkpoint can be small
9660    /// -- see that function's doc comment). Shared by every test that
9661    /// needs a real, loaded `KimiLoaded` rather than duplicating this
9662    /// setup per test.
9663    fn build_synthetic_kimi_loaded() -> model::KimiLoaded {
9664        use frink_models::config::{AttentionKind, KdaConfig, KimiHybridAttention, MlaConfig};
9665        use frink_models::kimi_loader::KimiRealHparams;
9666        use frink_moe::{GatingFunction, MoeLayerConfig};
9667
9668        let hidden_dim = 8;
9669        let kda_num_heads = 2;
9670        let kda_head_dim = 3;
9671        let kda_proj = kda_num_heads * kda_head_dim;
9672        let conv_kernel = 4;
9673        let dense_intermediate = 5;
9674        // One token per byte value -- enough to round-trip a simple
9675        // ASCII prompt through the real tiktoken-format vocab below,
9676        // matching `kimi_generate`'s own test convention.
9677        let vocab_size = 256;
9678        let mla_num_heads = 1;
9679        let mla_q_lora_rank = 2;
9680        let mla_kv_lora_rank = 2;
9681        let mla_qk_nope_head_dim = 2;
9682        let mla_qk_rope_head_dim = 2;
9683        let mla_v_head_dim = 2;
9684
9685        let model_cfg = frink_models::ModelConfig {
9686            rope_layers: frink_models::rope_layers::RopeLayers::All,
9687            layer_shapes: frink_models::layer_shapes::LayerShapes::Uniform,
9688            name: "synthetic-kimi-server-test",
9689            n_layers: 1,
9690            n_mtp_blocks: 0,
9691            hidden_dim,
9692            n_heads: 1,
9693            n_kv_heads: 1,
9694            head_dim: 4,
9695            v_head_dim: None,
9696            vocab_size,
9697            rope_theta: 10000.0,
9698            rms_norm_eps: 1e-5,
9699            post_norm_eps: 1e-5,
9700            sliding_window: None,
9701            moe: MoeLayerConfig {
9702                expert_weights_scale: 1.0,
9703                routed_weight_before_ffn: false,
9704                n_experts: 1,
9705                n_experts_active: 1,
9706                n_shared_experts: 0,
9707                hidden_dim,
9708                expert_ffn_dim: 4,
9709                gating: GatingFunction::Sigmoid,
9710                norm_topk_prob: true,
9711                expert_group_count: None,
9712                expert_group_used_count: None,
9713            },
9714            // Layer 0 is the sole dense leading layer, using KDA
9715            // attention (real Kimi K3's own layer-0 shape) -- the
9716            // 1-indexed `kda_layers`/`full_attn_layers` convention is
9717            // `ModelConfig::layer_attention_kind`'s, not this test's.
9718            n_dense_leading_layers: 1,
9719            moe_interleave_step: None,
9720            norm_function: frink_models::norm::NormFunction::Rms,
9721            attention: AttentionKind::KimiHybrid(KimiHybridAttention {
9722                kda_layers: vec![1],
9723                full_attn_layers: vec![],
9724                mla: MlaConfig {
9725                    num_heads: mla_num_heads,
9726                    q_lora_rank: mla_q_lora_rank,
9727                    kv_lora_rank: mla_kv_lora_rank,
9728                    qk_nope_head_dim: mla_qk_nope_head_dim,
9729                    qk_rope_head_dim: mla_qk_rope_head_dim,
9730                    v_head_dim: mla_v_head_dim,
9731                    use_output_gate: true,
9732                    rope: None,
9733                },
9734                kda: KdaConfig {
9735                    num_heads: kda_num_heads,
9736                    head_dim: kda_head_dim,
9737                    short_conv_kernel_size: conv_kernel,
9738                    gate_lower_bound: -5.0,
9739                    use_full_rank_gate: true,
9740                },
9741            }),
9742            rope_freqs: None,
9743            rope_attn_factor: 1.0,
9744            rope_dim: None,
9745            rope_dim_swa: None,
9746            rope_freqs_long: None,
9747            rope_freqs_short: None,
9748            rope_orig_ctx: None,
9749            rope_layout: frink_models::config::RopeLayout::Neox,
9750            qk_norm_style: frink_models::capability::QkNormStyle::WholeVector,
9751            swa_layers: frink_models::swa_layers::SwaLayers::All,
9752            attn_logit_softcap: None,
9753            final_logit_softcap: None,
9754            embedding_scale: None,
9755            residual_scale: None,
9756            normed_residual_scale: None,
9757            clamp_kqv: None,
9758            attn_temperature: None,
9759            router_input: frink_models::router_input::RouterInput::NormedFfnInput,
9760            block_sub_norms: false,
9761            parallel_residual: false,
9762            learned_positions: false,
9763            attn_value_scale: None,
9764            alibi_max_bias: None,
9765            layer_loops: None,
9766            skip_stream: false,
9767            parallel_ssm: false,
9768            swa_chunked: false,
9769            weightless_qk_norm: false,
9770            logit_multiplier: None,
9771            attention_scale: None,
9772            rope_theta_swa: None,
9773            ffn_activation: frink_models::config::FfnActivation::Swiglu,
9774            best_effort_fields: &["synthetic test config, not a real preset"],
9775        };
9776        let hp = KimiRealHparams {
9777            hidden_dim,
9778            kda_num_heads,
9779            kda_head_dim,
9780            mla_num_heads,
9781            mla_q_lora_rank,
9782            mla_kv_lora_rank,
9783            mla_qk_nope_head_dim,
9784            mla_qk_rope_head_dim,
9785            mla_v_head_dim,
9786            dense_intermediate_dim: dense_intermediate,
9787            moe_hidden_dim: hidden_dim,
9788            moe_intermediate_dim: 4,
9789            n_experts: 1,
9790            num_shared_experts: 0,
9791        };
9792
9793        // Every real tensor name `kimi_loader::load_kimi_layer` (dense
9794        // FFN + KDA attention + block residual) and
9795        // `load_kimi_checkpoint` (top-level) actually read.
9796        let prefix = "language_model.model.layers.0";
9797        let mut tensors: Vec<(String, Vec<usize>, Vec<f32>)> = Vec::new();
9798        let push = |tensors: &mut Vec<(String, Vec<usize>, Vec<f32>)>,
9799                    name: String,
9800                    shape: Vec<usize>,
9801                    n: usize| {
9802            tensors.push((name, shape, vec![0.01f32; n]));
9803        };
9804        push(
9805            &mut tensors,
9806            format!("{prefix}.input_layernorm.weight"),
9807            vec![hidden_dim],
9808            hidden_dim,
9809        );
9810        push(
9811            &mut tensors,
9812            format!("{prefix}.post_attention_layernorm.weight"),
9813            vec![hidden_dim],
9814            hidden_dim,
9815        );
9816        push(
9817            &mut tensors,
9818            format!("{prefix}.self_attention_res_norm.weight"),
9819            vec![hidden_dim],
9820            hidden_dim,
9821        );
9822        push(
9823            &mut tensors,
9824            format!("{prefix}.self_attention_res_proj.weight"),
9825            vec![1, hidden_dim],
9826            hidden_dim,
9827        );
9828        push(
9829            &mut tensors,
9830            format!("{prefix}.mlp_res_norm.weight"),
9831            vec![hidden_dim],
9832            hidden_dim,
9833        );
9834        push(
9835            &mut tensors,
9836            format!("{prefix}.mlp_res_proj.weight"),
9837            vec![1, hidden_dim],
9838            hidden_dim,
9839        );
9840        push(
9841            &mut tensors,
9842            format!("{prefix}.self_attn.q_proj.weight"),
9843            vec![kda_proj, hidden_dim],
9844            kda_proj * hidden_dim,
9845        );
9846        push(
9847            &mut tensors,
9848            format!("{prefix}.self_attn.k_proj.weight"),
9849            vec![kda_proj, hidden_dim],
9850            kda_proj * hidden_dim,
9851        );
9852        push(
9853            &mut tensors,
9854            format!("{prefix}.self_attn.v_proj.weight"),
9855            vec![kda_proj, hidden_dim],
9856            kda_proj * hidden_dim,
9857        );
9858        push(
9859            &mut tensors,
9860            format!("{prefix}.self_attn.q_conv1d.weight"),
9861            vec![kda_proj, 1, conv_kernel],
9862            kda_proj * conv_kernel,
9863        );
9864        push(
9865            &mut tensors,
9866            format!("{prefix}.self_attn.k_conv1d.weight"),
9867            vec![kda_proj, 1, conv_kernel],
9868            kda_proj * conv_kernel,
9869        );
9870        push(
9871            &mut tensors,
9872            format!("{prefix}.self_attn.v_conv1d.weight"),
9873            vec![kda_proj, 1, conv_kernel],
9874            kda_proj * conv_kernel,
9875        );
9876        push(
9877            &mut tensors,
9878            format!("{prefix}.self_attn.A_log"),
9879            vec![kda_num_heads],
9880            kda_num_heads,
9881        );
9882        push(
9883            &mut tensors,
9884            format!("{prefix}.self_attn.f_a_proj.weight"),
9885            vec![kda_head_dim, hidden_dim],
9886            kda_head_dim * hidden_dim,
9887        );
9888        push(
9889            &mut tensors,
9890            format!("{prefix}.self_attn.f_b_proj.weight"),
9891            vec![kda_proj, kda_head_dim],
9892            kda_proj * kda_head_dim,
9893        );
9894        push(
9895            &mut tensors,
9896            format!("{prefix}.self_attn.dt_bias"),
9897            vec![kda_proj],
9898            kda_proj,
9899        );
9900        push(
9901            &mut tensors,
9902            format!("{prefix}.self_attn.b_proj.weight"),
9903            vec![kda_num_heads, hidden_dim],
9904            kda_num_heads * hidden_dim,
9905        );
9906        push(
9907            &mut tensors,
9908            format!("{prefix}.self_attn.g_proj.weight"),
9909            vec![kda_proj, hidden_dim],
9910            kda_proj * hidden_dim,
9911        );
9912        push(
9913            &mut tensors,
9914            format!("{prefix}.self_attn.o_norm.weight"),
9915            vec![kda_head_dim],
9916            kda_head_dim,
9917        );
9918        push(
9919            &mut tensors,
9920            format!("{prefix}.self_attn.o_proj.weight"),
9921            vec![hidden_dim, kda_proj],
9922            hidden_dim * kda_proj,
9923        );
9924        push(
9925            &mut tensors,
9926            format!("{prefix}.mlp.gate_proj.weight"),
9927            vec![dense_intermediate, hidden_dim],
9928            dense_intermediate * hidden_dim,
9929        );
9930        push(
9931            &mut tensors,
9932            format!("{prefix}.mlp.up_proj.weight"),
9933            vec![dense_intermediate, hidden_dim],
9934            dense_intermediate * hidden_dim,
9935        );
9936        push(
9937            &mut tensors,
9938            format!("{prefix}.mlp.down_proj.weight"),
9939            vec![hidden_dim, dense_intermediate],
9940            hidden_dim * dense_intermediate,
9941        );
9942        push(
9943            &mut tensors,
9944            "language_model.model.embed_tokens.weight".to_string(),
9945            vec![vocab_size, hidden_dim],
9946            vocab_size * hidden_dim,
9947        );
9948        push(
9949            &mut tensors,
9950            "language_model.lm_head.weight".to_string(),
9951            vec![vocab_size, hidden_dim],
9952            vocab_size * hidden_dim,
9953        );
9954        push(
9955            &mut tensors,
9956            "language_model.model.norm.weight".to_string(),
9957            vec![hidden_dim],
9958            hidden_dim,
9959        );
9960        push(
9961            &mut tensors,
9962            "language_model.model.output_attn_res_norm.weight".to_string(),
9963            vec![hidden_dim],
9964            hidden_dim,
9965        );
9966        push(
9967            &mut tensors,
9968            "language_model.model.output_attn_res_proj.weight".to_string(),
9969            vec![1, hidden_dim],
9970            hidden_dim,
9971        );
9972
9973        // Unique per CALL, not per (pid, vocab_size). Both callers of
9974        // this helper use the same `vocab_size`, so keying on it gave
9975        // the two tests one directory -- and `fs::write` opens with
9976        // `O_TRUNC`, so one test rewriting the shard truncated it to
9977        // zero while the other's `frink-safetensors` MMAP of that
9978        // exact file was live. Touching a mapping past the end of its
9979        // file is SIGBUS, which kills the whole test binary rather than
9980        // failing one test, and only when the two happen to overlap --
9981        // so it showed up as an occasional unexplained CI crash.
9982        //
9983        // A counter and not a thread id: the harness reuses threads
9984        // across tests, so two sequential tests can share one.
9985        static FIXTURE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
9986        let dir = std::env::temp_dir().join(format!(
9987            "frink_server_kimi_e2e_test_{}_{}",
9988            std::process::id(),
9989            FIXTURE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
9990        ));
9991        std::fs::create_dir_all(&dir).unwrap();
9992        let shard_bytes = write_safetensors_shard(&tensors);
9993        std::fs::write(dir.join("shard0.safetensors"), &shard_bytes).unwrap();
9994        let map_entries: Vec<String> = tensors
9995            .iter()
9996            .map(|(name, ..)| format!("\"{name}\":\"shard0.safetensors\""))
9997            .collect();
9998        let index = format!("{{\"weight_map\":{{{}}}}}", map_entries.join(","));
9999        std::fs::write(dir.join("model.safetensors.index.json"), &index).unwrap();
10000
10001        // A real tiktoken-format vocab file: one base64-encoded byte
10002        // plus its rank per line -- enough to round-trip an ASCII
10003        // prompt without needing the real 163584-entry Kimi K3 vocab.
10004        use base64::Engine;
10005        let vocab_lines: Vec<String> = (0..vocab_size as u32)
10006            .map(|b| {
10007                let b64 = base64::engine::general_purpose::STANDARD.encode([b as u8]);
10008                format!("{b64} {b}")
10009            })
10010            .collect();
10011        std::fs::write(dir.join("tiktoken.model"), vocab_lines.join("\n")).unwrap();
10012
10013        let loaded = model::load_kimi_checkpoint_with_config(dir.to_str().unwrap(), model_cfg, hp)
10014            .expect("must load the synthetic Kimi checkpoint end to end");
10015        std::fs::remove_dir_all(&dir).ok();
10016        loaded
10017    }
10018
10019    /// The real end-to-end proof for Kimi-through-the-server: a real
10020    /// synthetic Kimi K3 checkpoint served through the exact same
10021    /// `run_generation` entry point the HTTP handlers call for the
10022    /// GGUF path. Proves the whole new plumbing end to end: directory-
10023    /// shaped checkpoint loading, `KimiEngine`/`KimiTokenizer` wired
10024    /// through the `Model` enum, and `generate::generate_engine`
10025    /// producing real, bounded generated text.
10026    #[test]
10027    fn kimi_model_serves_real_text_end_to_end_via_run_generation() {
10028        let loaded = build_synthetic_kimi_loaded();
10029        let state = build_app_state(
10030            StartupModels {
10031                loaded: model::LoadedModel::Kimi(loaded),
10032                embedding: None,
10033            },
10034            None,
10035            None,
10036            None,
10037            false,
10038            None,
10039            Arc::new(health::Detection::ready(health::probe_backends())),
10040        );
10041        let active = state.active().expect("a freshly built state has a model");
10042        assert_eq!(active.tokenizer_kind(), "kimi-tiktoken-bpe");
10043        assert!(!active.is_synthetic());
10044
10045        let produced = run_generation(
10046            active.generative().unwrap(),
10047            "hi",
10048            &greedy_params(5),
10049            None,
10050            None,
10051            None,
10052            None,
10053            None,
10054            None,
10055        )
10056        .expect("a real Kimi checkpoint must generate without error");
10057        assert!(matches!(
10058            produced.choices[0].finish,
10059            FinishReason::Length | FinishReason::Stop
10060        ));
10061    }
10062
10063    /// The THIRD decode path: `generate_engine`, which serves every
10064    /// model that is not a `Decoder`.
10065    ///
10066    /// This is where a constraint gets dropped without anyone noticing.
10067    /// JSON mode was honoured on the `Decoder` path and silently not on
10068    /// this one, because this path had no tokenizer to hand the mask.
10069    /// A grammar must reach it too, and this checkpoint's vocabulary is
10070    /// one token per byte value, so `root ::= "a"+` has exactly one
10071    /// legal token (97) and the answer is decidable: all `a`, however
10072    /// the random weights would otherwise have decoded.
10073    ///
10074    /// The unconstrained run beside it is the vacuity check.
10075    #[test]
10076    fn a_grammar_constrains_the_engine_decode_path() {
10077        let loaded = build_synthetic_kimi_loaded();
10078        let state = build_app_state(
10079            StartupModels {
10080                loaded: model::LoadedModel::Kimi(loaded),
10081                embedding: None,
10082            },
10083            None,
10084            None,
10085            None,
10086            false,
10087            None,
10088            Arc::new(health::Detection::ready(health::probe_backends())),
10089        );
10090        let active = state.active().expect("a freshly built state has a model");
10091
10092        let run = |grammar: Option<&str>| {
10093            let mut params = greedy_params(6);
10094            params.grammar = grammar.map(|src| {
10095                Arc::new(
10096                    frink_models::grammar::Grammar::from_str_with_root(src, "root")
10097                        .expect("test grammar parses"),
10098                )
10099            });
10100            run_generation(
10101                active.generative().unwrap(),
10102                "hi",
10103                &params,
10104                None,
10105                None,
10106                None,
10107                None,
10108                None,
10109                None,
10110            )
10111        };
10112
10113        let produced = run(None).expect("the unconstrained run must serve");
10114        let unconstrained = produced.choices[0].text.clone();
10115        assert!(
10116            unconstrained.chars().any(|c| c != 'a'),
10117            "the unconstrained run produced only `a` ({unconstrained:?}), so the \
10118             constrained run below would prove nothing"
10119        );
10120
10121        let produced =
10122            run(Some(r#"root ::= "a"+"#)).expect("a grammar this vocabulary can spell must serve");
10123        let one = produced.choices.into_iter().next().unwrap();
10124        let (finish, constrained) = (one.finish, one.text);
10125        assert!(
10126            !constrained.is_empty() && constrained.chars().all(|c| c == 'a'),
10127            "the engine decode path served text its grammar forbids ({constrained:?}): \
10128             the constraint was dropped between `generate_engine` and the sampler"
10129        );
10130        assert!(matches!(finish, FinishReason::Length | FinishReason::Stop));
10131    }
10132
10133    /// Explicit proof of the "gate, don't paper over" design decision
10134    /// (see `frink_models::engine`'s module docs): even when an operator configures
10135    /// a KV block pool and/or prefix cache, a Kimi request must never
10136    /// consult either -- `generate_engine`'s signature has no
10137    /// parameter for them at all, so this isn't just an unexercised
10138    /// code path, it's structurally impossible for a Kimi request to
10139    /// touch them. Confirmed here by observing both are completely
10140    /// untouched (pool blocks unchanged, cache stats unchanged) after a
10141    /// real Kimi generation runs alongside both.
10142    #[test]
10143    fn kv_pool_and_prefix_cache_are_never_consulted_for_a_kimi_model() {
10144        let loaded = build_synthetic_kimi_loaded();
10145        let state = build_app_state(
10146            StartupModels {
10147                loaded: model::LoadedModel::Kimi(loaded),
10148                embedding: None,
10149            },
10150            None,
10151            None,
10152            None,
10153            false,
10154            None,
10155            Arc::new(health::Detection::ready(health::probe_backends())),
10156        );
10157
10158        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 4)));
10159        let kv_pool_config = generate::KvPoolConfig {
10160            pool: pool.clone(),
10161            queue_wait: Duration::ZERO,
10162        };
10163        let pc = Mutex::new(PrefixCache::new(4));
10164
10165        run_generation(
10166            state
10167                .active()
10168                .expect("a freshly built state has a model")
10169                .generative()
10170                .unwrap(),
10171            "hi",
10172            &greedy_params(5),
10173            Some(&kv_pool_config),
10174            None,
10175            Some(&pc),
10176            None,
10177            None,
10178            None,
10179        )
10180        .expect("a real Kimi checkpoint must generate without error");
10181
10182        assert_eq!(
10183            pool.lock().unwrap().free_blocks(),
10184            4,
10185            "the KV pool must be completely untouched by a Kimi request"
10186        );
10187        let stats = pc.lock().unwrap().stats();
10188        assert_eq!(
10189            stats.hits + stats.misses,
10190            0,
10191            "the prefix cache must never be consulted for a Kimi request"
10192        );
10193    }
10194}