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_any = |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    // `return_tokens_as_token_ids`: a reported token is spelled by its
2957    // id rather than its text (`crate::logprobs::piece_renderer`).
2958    // Built HERE rather than beside `decode_any` above, because a
2959    // trait object held across the `await` would have to be `Send` and
2960    // this one has nothing to gain from being it.
2961    let render_piece =
2962        crate::logprobs::piece_renderer(req.unimplemented.tokens_as_ids(), &decode_any);
2963    let rendered: Vec<ChatCompletionChoice> = ranked
2964        .into_iter()
2965        .enumerate()
2966        .map(|(index, (finish, text))| {
2967            let (message, finish_reason) =
2968                build_response_message(text, tools, posture, finish.as_str());
2969            ChatCompletionChoice {
2970                index,
2971                message,
2972                finish_reason,
2973                logprobs: n_logprobs.map(|k| {
2974                    crate::logprobs::render_chat(
2975                        generated_logprobs.get(index).unwrap_or(&Vec::new()),
2976                        Some(k),
2977                        render_piece.as_ref(),
2978                    )
2979                }),
2980            }
2981        })
2982        .collect();
2983
2984    state.record_request(stats::Record {
2985        request_id: &request_id,
2986        route: frink_api::routes::V1_CHAT_COMPLETIONS,
2987        // The handle this request decoded against, not `req.model`: a
2988        // swap mid-flight does not change which weights answered.
2989        model: Some(active.name().to_string()),
2990        status: 200,
2991        stream: false,
2992        duration_ms: started.elapsed().as_millis() as u64,
2993        usage: Some(&completion.usage),
2994        attribution: &attribution,
2995    });
2996
2997    Ok(Json(ChatCompletionResponse {
2998        id: request_id.clone(),
2999        request_id,
3000        object: "chat.completion",
3001        model: req.model,
3002        choices: rendered,
3003        usage: completion.usage,
3004        frink_cache: cache_status,
3005    }))
3006}
3007
3008async fn chat_completions_stream(
3009    state: Arc<AppState>,
3010    req: ChatCompletionRequest,
3011    request_id: String,
3012    started: std::time::Instant,
3013    attribution: attribution::Attribution,
3014) -> Result<Response, ApiError> {
3015    // Streaming requests are never served from or written to the response cache.
3016    //
3017    // And they serve one choice. Emitting choice 0 to its end and then
3018    // choice 1 is not what a client reading `choices[].index` expects,
3019    // and interleaving them round-robin needs a sampler that can be
3020    // stepped one token at a time per choice
3021    // (`docs/plans/several-completions-per-request.md`). Refused by
3022    // name rather than silently collapsed to one, which is the whole
3023    // argument of `crate::unimplemented_fields`.
3024    let tools_active = req.tools_active();
3025    // See `chat_completions_full`: the handle is taken once and the
3026    // whole stream runs against it, so a mid-stream model swap cannot
3027    // splice two checkpoints into one completion.
3028    let active = state.require_active()?;
3029    let history = resolve_history(&state, &req);
3030    let template = active.generative()?.chat_template();
3031    let kwargs = req.resolve_template_kwargs(&template);
3032    let prompt = req.render_prompt(&history, &template, &req.tools, kwargs, active.name())?;
3033    let model_name = req.model.clone();
3034    let session_id = req.session_id.clone();
3035    let sessions = state.sessions.clone();
3036
3037    let model = Arc::clone(active.generative()?);
3038    let kv_pool = state.kv_pool.clone();
3039    let paged_kv = state.paged_kv.clone();
3040    let prefix_cache = state.prefix_cache.clone();
3041    let batcher = active.batcher.clone();
3042    let ceiling = active.ceiling.clone();
3043    let metal_private_decode_gate = state.metal_private_decode_gate.clone();
3044    let mut params =
3045        req.generation_params_for_template(&template, active.name(), active.sampler_model())?;
3046    params.lora = lora::resolve_request(active.generative()?, req.lora.as_deref())?;
3047    // A client reading `choices[].index` asked for the choices
3048    // together, so they are decoded a token at a time rather than one
3049    // completion after another (`crate::round_robin`). Set HERE and
3050    // nowhere else: a buffered request collects in an order nobody can
3051    // observe, and the interleaved schedule costs it the drafter.
3052    params.interleave_choices = params.n > 1;
3053    let stats_state = Arc::clone(&state);
3054    // Read now, off the handle this stream will decode against. Read
3055    // later it would name whatever a swap had made current by then.
3056    let served_model = active.name().to_string();
3057    // How to read this stream, fixed before the first token: the family
3058    // from the served checkpoint, and whether the prompt that was
3059    // actually rendered left the model inside a reasoning block.
3060    let posture = output::OutputPosture::resolve_full(
3061        active.reasoning_format(),
3062        active.tool_call_format(),
3063        &prompt,
3064    );
3065    // The offered tools, captured for the terminal parse: the request
3066    // itself does not outlive the closure that consumes it.
3067    let offered_tools: Vec<ToolDef> = if tools_active {
3068        req.tools.clone()
3069    } else {
3070        Vec::new()
3071    };
3072
3073    // Tier two of cancellation: the id is already on the wire, so the
3074    // client can name it. The guard rides with the generation task and
3075    // deregisters however that task ends, panic included -- see the
3076    // `cancel` module.
3077    let (cancel_token, cancel_guard) = state.cancels.register(&request_id);
3078    params.cancel = Some(cancel_token.clone());
3079
3080    // Tool-call detection needs the full stop-bounded text; continuous
3081    // batching returns one string. Both stay buffered. Otherwise each
3082    // decoded chunk is pushed on a channel for overlapped SSE delivery.
3083    // Incremental streaming, including when tools are offered. It used
3084    // to be `!tools_active && ...`: finding a tool call needed the
3085    // whole text. `crate::policy::parser::ToolCallParser` streams prefix-stable
3086    // argument fragments, so that reason is gone, and a coding agent
3087    // now watches an argument arrive instead of waiting for it.
3088    let overlap = true;
3089
3090    // Opt-in replay. Registering a buffer is also what decides whether a
3091    // dropped socket cancels this generation -- see `resume`'s module
3092    // doc for why that is the caller's call and not the server's.
3093    let slot = req
3094        .stream_resumable
3095        .unwrap_or(false)
3096        .then(|| state.streams.register(&request_id));
3097    let emitter = resume::Emitter::new(slot);
3098
3099    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);
3100    // Built here, where the id and model name are still owned by this
3101    // frame: the generation task takes both. Serialized once, because
3102    // it is byte-identical every time it goes out.
3103    let keepalive = sse::keepalive_event(&ChatCompletionChunk {
3104        id: request_id.clone(),
3105        request_id: None,
3106        object: "chat.completion.chunk",
3107        model: model_name.clone(),
3108        choices: vec![ChatCompletionChunkChoice {
3109            index: 0,
3110            delta: ChatCompletionChunkDelta {
3111                role: None,
3112                content: None,
3113                reasoning_content: None,
3114                tool_calls: None,
3115            },
3116            finish_reason: None,
3117        }],
3118        usage: None,
3119    });
3120
3121    tokio::task::spawn_blocking(move || {
3122        // Held for the whole generation; dropping it is what takes the
3123        // id back out of the cancel registry.
3124        let _cancel_guard = cancel_guard;
3125        let tx_chunks = tx.clone();
3126        // The orphan deadline (see `crate::sse`): a client that is
3127        // neither reading nor disconnected must not park this blocking
3128        // thread -- and the model handle and cancel guard it holds --
3129        // for the life of the process.
3130        let orphan_timeout = sse::orphan_timeout_from_env();
3131        let head_request_id = request_id.clone();
3132        // Whether the request id has gone out yet. It names the
3133        // REQUEST, so it rides the first chunk of the whole stream
3134        // rather than the first chunk of each choice.
3135        let announced = std::cell::Cell::new(false);
3136        // One parser set per choice. A streamed `n` interleaves the
3137        // choices a token at a time (`crate::round_robin`), so the
3138        // reasoning split, the tool parser and the opened-call count
3139        // are per COMPLETION rather than per request: two choices can
3140        // be mid-marker in different places.
3141        let emitters: Rc<RefCell<Vec<crate::chat_stream_choice::ChoiceEmitter>>> =
3142            Rc::new(RefCell::new(
3143                (0..params.n.max(1))
3144                    .map(|_| {
3145                        crate::chat_stream_choice::ChoiceEmitter::new(
3146                            posture.reasoning_parser(),
3147                            tools_active.then(|| posture.tool_call_parser(&offered_tools)),
3148                        )
3149                    })
3150                    .collect(),
3151            ));
3152        let emit_choices = Rc::clone(&emitters);
3153        let result = run_generation_emit(
3154            &model,
3155            &prompt,
3156            &params,
3157            kv_pool.as_ref(),
3158            paged_kv.as_ref(),
3159            prefix_cache.as_deref(),
3160            batcher.as_ref(),
3161            ceiling.as_deref(),
3162            metal_private_decode_gate.as_deref(),
3163            |choice, chunk| {
3164                if !overlap || chunk.is_empty() {
3165                    return;
3166                }
3167                let mut held = emit_choices.borrow_mut();
3168                let Some(emitter_state) = held.get_mut(choice) else {
3169                    return;
3170                };
3171                let delta = emitter_state.push(chunk);
3172                if delta.is_empty() {
3173                    return;
3174                }
3175                // The request id rides the first chunk of the whole
3176                // STREAM, not of each choice: it names the request.
3177                let request_id = (!announced.get()).then(|| {
3178                    announced.set(true);
3179                    head_request_id.clone()
3180                });
3181                let wire = delta.into_choice(choice, emitter_state.start());
3182                drop(held);
3183                let payload = ChatCompletionChunk {
3184                    id: head_request_id.clone(),
3185                    request_id,
3186                    object: "chat.completion.chunk",
3187                    model: model_name.clone(),
3188                    choices: vec![wire],
3189                    usage: None,
3190                };
3191                // Tier one of cancellation. A failed send means the SSE
3192                // receiver is gone -- the browser tab closed, the
3193                // client aborted, the connection dropped -- and until
3194                // this was checked the return value was discarded and
3195                // the decode loop happily generated the remaining
3196                // hundreds of tokens into nothing. Flipping the same
3197                // flag `/v1/cancel` sets means there is one stop path,
3198                // not two.
3199                if let Err(why) =
3200                    sse::send_or_orphan(&tx_chunks, Ok(emitter.event(&payload)), orphan_timeout)
3201                {
3202                    if why == sse::SendFailure::Orphaned {
3203                        tracing::warn!(
3204                            "SSE stream {head_request_id} accepted nothing for the orphan \
3205                             deadline; treating it as abandoned"
3206                        );
3207                    }
3208                    // Two features met here and only one of them may
3209                    // win. The orphan deadline exists to stop work
3210                    // nobody is reading. A resumable stream is exactly
3211                    // the case where a gone receiver must NOT stop the
3212                    // work: the client said it may come back, the
3213                    // buffer is still being filled for it, and
3214                    // cancelling would make every reconnect resume into
3215                    // a truncated answer. So the deadline still detects
3216                    // and logs, and only a non-resumable stream is
3217                    // cancelled by it. `POST /v1/cancel` is the stop
3218                    // path for the resumable ones.
3219                    if !emitter.is_resumable() {
3220                        cancel_token.cancel();
3221                    }
3222                }
3223            },
3224        );
3225
3226        // Nothing may have been streamed from the emit closure (the
3227        // buffered tool-call/batching path, or an empty generation), so
3228        // the id may not have gone out yet. `take()` on the way into
3229        // each payload below guarantees it is announced exactly once,
3230        // on whichever chunk really is first.
3231        let mut pending_request_id = (!announced.get()).then(|| request_id.clone());
3232
3233        match result {
3234            Ok(generated) => {
3235                let usage = generated.usage;
3236                let produced: Vec<(generate::FinishReason, String)> = generated
3237                    .choices
3238                    .into_iter()
3239                    .map(|c| (c.finish, c.text))
3240                    .collect();
3241                assert!(
3242                    !produced.is_empty(),
3243                    "a generation produces at least one choice"
3244                );
3245                // The transcript keeps CHOICE 0. A server-side history
3246                // is one conversation, and appending four assistant
3247                // turns for one question would make the next request's
3248                // prompt a conversation that never happened.
3249                if let Some(id) = &session_id {
3250                    sessions.store_reply(
3251                        id,
3252                        ChatMessage {
3253                            role: "assistant".to_string(),
3254                            content: Some(MessageContent::Text(produced[0].1.clone())),
3255                            tool_calls: None,
3256                            tool_call_id: None,
3257                            reasoning_content: None,
3258                        },
3259                    );
3260                }
3261                for (index, (finish, full_text)) in produced.iter().enumerate() {
3262                    let (finish, full_text) = (finish.clone(), full_text.as_str());
3263                    // Both parsers may still be holding a run that could
3264                    // have become a marker and did not. It is ordinary
3265                    // output; dropping it would truncate every answer whose
3266                    // tail happens to look like the start of a `</think>`
3267                    // or a `<tool_call>`.
3268                    let mut streamed_finish: Option<&'static str> = None;
3269                    if overlap {
3270                        let (tail, first, opened) = {
3271                            let mut held = emitters.borrow_mut();
3272                            let state = &mut held[index];
3273                            let tail = state.flush();
3274                            (tail, state.start(), state.opened_calls())
3275                        };
3276                        if !tail.is_empty() {
3277                            let payload = ChatCompletionChunk {
3278                                id: request_id.clone(),
3279                                request_id: pending_request_id.take(),
3280                                object: "chat.completion.chunk",
3281                                model: model_name.clone(),
3282                                choices: vec![tail.into_choice(index, first)],
3283                                usage: None,
3284                            };
3285                            let _ = sse::send_or_orphan(
3286                                &tx,
3287                                Ok(emitter.event(&payload)),
3288                                orphan_timeout,
3289                            );
3290                        }
3291                        if opened > 0 {
3292                            streamed_finish = Some("tool_calls");
3293                        }
3294                    } else {
3295                        // The batched path had no incremental stream to
3296                        // ride on, so the whole answer goes out at once.
3297                        let parsed = output::parse_output(full_text, &offered_tools, posture);
3298                        let tool_calls: Vec<ToolCallDelta> = parsed
3299                            .calls
3300                            .iter()
3301                            .enumerate()
3302                            .map(|(index, call)| {
3303                                ToolCallDelta::whole(
3304                                    index,
3305                                    call.name.clone(),
3306                                    call.arguments.clone(),
3307                                )
3308                            })
3309                            .collect();
3310                        if !tool_calls.is_empty() {
3311                            streamed_finish = Some("tool_calls");
3312                        }
3313                        if !tool_calls.is_empty()
3314                            || !parsed.content.is_empty()
3315                            || parsed.reasoning.is_some()
3316                        {
3317                            let payload = ChatCompletionChunk {
3318                                id: request_id.clone(),
3319                                request_id: pending_request_id.take(),
3320                                object: "chat.completion.chunk",
3321                                model: model_name.clone(),
3322                                choices: vec![ChatCompletionChunkChoice {
3323                                    index,
3324                                    delta: ChatCompletionChunkDelta {
3325                                        role: Some("assistant"),
3326                                        content: (!parsed.content.is_empty()
3327                                            && tool_calls.is_empty())
3328                                        .then(|| parsed.content.clone()),
3329                                        reasoning_content: parsed.reasoning.clone(),
3330                                        tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
3331                                    },
3332                                    finish_reason: None,
3333                                }],
3334                                usage: None,
3335                            };
3336                            let _ = sse::send_or_orphan(
3337                                &tx,
3338                                Ok(emitter.event(&payload)),
3339                                orphan_timeout,
3340                            );
3341                        }
3342                    }
3343                    // A truncated generation is `length` even if it managed
3344                    // to open a call: the client must not treat a
3345                    // half-written call as one it should execute.
3346                    let final_finish_reason = match streamed_finish {
3347                        Some(reason) if finish.as_str() != "length" => reason,
3348                        _ => finish.as_str(),
3349                    };
3350                    // The usage block rides the LAST choice's terminal
3351                    // chunk, because it is the request's total and there is
3352                    // exactly one of it.
3353                    let last = index + 1 == produced.len();
3354                    let final_payload = ChatCompletionChunk {
3355                        id: request_id.clone(),
3356                        request_id: pending_request_id.take(),
3357                        object: "chat.completion.chunk",
3358                        model: model_name.clone(),
3359                        choices: vec![ChatCompletionChunkChoice {
3360                            index,
3361                            delta: ChatCompletionChunkDelta {
3362                                role: None,
3363                                content: None,
3364                                reasoning_content: None,
3365                                tool_calls: None,
3366                            },
3367                            finish_reason: Some(final_finish_reason),
3368                        }],
3369                        usage: last.then(|| usage.clone()),
3370                    };
3371                    let _ =
3372                        sse::send_or_orphan(&tx, Ok(emitter.event(&final_payload)), orphan_timeout);
3373                }
3374                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3375                // Recorded here rather than where the handler returned:
3376                // the handler returns as soon as the SSE headers go out,
3377                // which is before a single token exists, so timing it
3378                // there would report every stream as instant.
3379                stats_state.record_request(stats::Record {
3380                    request_id: &request_id,
3381                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3382                    model: Some(served_model.clone()),
3383                    status: 200,
3384                    stream: true,
3385                    duration_ms: started.elapsed().as_millis() as u64,
3386                    usage: Some(&usage),
3387                    attribution: &attribution,
3388                });
3389            }
3390            Err(e) => {
3391                tracing::warn!("decode error on streamed request {request_id}: {e}");
3392                // The socket carried 200 -- SSE headers precede the
3393                // first token -- but the request produced no completion.
3394                // The monitor records outcomes, and a 200 row with zero
3395                // tokens would read as a successful empty answer, so the
3396                // failure is stated as 500 here and only here.
3397                stats_state.record_request(stats::Record {
3398                    request_id: &request_id,
3399                    route: frink_api::routes::V1_CHAT_COMPLETIONS,
3400                    model: Some(served_model.clone()),
3401                    status: 500,
3402                    stream: true,
3403                    duration_ms: started.elapsed().as_millis() as u64,
3404                    usage: None,
3405                    attribution: &attribution,
3406                });
3407                let payload = ChatCompletionChunk {
3408                    id: request_id.clone(),
3409                    request_id: pending_request_id.take(),
3410                    object: "chat.completion.chunk",
3411                    model: model_name,
3412                    choices: vec![ChatCompletionChunkChoice {
3413                        index: 0,
3414                        delta: ChatCompletionChunkDelta {
3415                            role: Some("assistant"),
3416                            content: Some(format!("[error: {e}]")),
3417                            reasoning_content: None,
3418                            tool_calls: None,
3419                        },
3420                        finish_reason: Some("stop"),
3421                    }],
3422                    usage: None,
3423                };
3424                let _ = sse::send_or_orphan(&tx, Ok(emitter.event(&payload)), orphan_timeout);
3425                let _ = sse::send_or_orphan(&tx, Ok(emitter.done()), orphan_timeout);
3426            }
3427        }
3428        // The buffer is closed by dropping `emitter` here -- including
3429        // on a panic, which is the case an explicit call would miss.
3430        // See `resume::Emitter`'s `Drop`.
3431        drop(emitter);
3432    });
3433
3434    let stream = sse::with_keepalive(rx, keepalive, sse::KEEPALIVE_INTERVAL);
3435    // `X-Accel-Buffering: no` is the one header that actually reaches
3436    // the problem the plan names: nginx (and the proxies that copied
3437    // its convention) buffer `text/event-stream` by default, which
3438    // turns a token-by-token stream into one silent wait followed by
3439    // the whole answer at once -- indistinguishable, from the browser,
3440    // from a hung backend. axum already sets `Cache-Control: no-cache`
3441    // on an `Sse` response, so that half is covered.
3442    //
3443    // The keepalive every 15s is the other half: it gives an
3444    // idle-but-healthy stream something to send, so a client's stall
3445    // timeout measures the *connection* rather than the model's
3446    // time-to-first-token on a long prompt.
3447    //
3448    // **Not `Sse::keep_alive`.** axum's keepalive is an SSE COMMENT,
3449    // and a comment does not reach a client's event handler -- codex's
3450    // 300s stream-idle timeout only resets on a data frame, so a
3451    // comment-kept stream is reconnected mid-answer on a long prefill.
3452    // `sse::with_keepalive` sends a real `chat.completion.chunk` with
3453    // an empty delta instead: a concatenating client adds nothing, and
3454    // the transport sees traffic. It also covers the silence BEFORE
3455    // the first token, which is exactly the queue-wait and long-prefill
3456    // window where this matters most.
3457    Ok((
3458        [(
3459            axum::http::HeaderName::from_static("x-accel-buffering"),
3460            axum::http::HeaderValue::from_static("no"),
3461        )],
3462        Sse::new(stream),
3463    )
3464        .into_response())
3465}
3466
3467/// The axum pattern for one of the published path templates.
3468///
3469/// `frink_api::routes` writes placeholders in the OpenAPI style
3470/// because it is imported by clients that have never heard of this
3471/// server's router; axum 0.7 wants `:name`. Converting here keeps one
3472/// published spelling and one router spelling, and the test below fails
3473/// if they ever stop describing the same path.
3474///
3475/// This rewrites EVERY `{name}` it finds rather than one known
3476/// placeholder. The narrow version took `{request_id}` only, so the two
3477/// Responses templates were mounted with their braces intact and axum
3478/// read `{response_id}` as a literal segment: `GET /v1/responses/abc`
3479/// matched no route and got axum's bodiless 404 instead of the
3480/// handler's, and the one path that did match would have panicked on
3481/// `MissingPathParams`. Anything with a placeholder must go through
3482/// here.
3483/// Every route that sits behind `FRINK_API_KEY`, as ONE list.
3484///
3485/// Extracted because there were two of these: this one and a
3486/// hand-written copy in the test module, which had already drifted --
3487/// the test router was missing `/metrics`, `/cache/stats`, both rerank
3488/// spellings and half of `/admin`, so an HTTP test could pass against a
3489/// route the real server does not serve, or 404 on one it does. That is
3490/// this repo's dominant bug shape (two structures that must agree, with
3491/// nothing enforcing it) sitting inside the test harness, where it is
3492/// worst: it makes the tests agree with themselves.
3493///
3494/// `/health` is deliberately NOT here. It is the one route that must
3495/// stay reachable without a key, and it is registered separately for
3496/// that reason.
3497fn protected_routes() -> Router<Arc<AppState>> {
3498    use frink_api::routes;
3499
3500    Router::new()
3501        .route(routes::V1_MODELS, get(list_models))
3502        // The Responses surface decodes tokens, so it sits behind the
3503        // same key as `/v1/chat/completions`: it must cost what
3504        // decoding tokens costs.
3505        .route(routes::V1_RESPONSES, post(responses::responses))
3506        .route(
3507            &axum_path(routes::V1_RESPONSE),
3508            get(responses::responses_get),
3509        )
3510        .route(
3511            &axum_path(routes::V1_RESPONSE_CANCEL),
3512            post(responses::responses_cancel),
3513        )
3514        .route(&axum_path(routes::SLOTS_ID), post(slots::post_slot))
3515        .route(routes::V1_STATS, get(serving_stats))
3516        .route(routes::V1_REQUESTS, get(recent_requests))
3517        .route(routes::V1_CACHE_STATUS, get(cache_admin::cache_status))
3518        .route(routes::V1_CACHE_REBUILD, post(cache_admin::cache_rebuild))
3519        .route(routes::ADMIN_PREPARE_STOP, post(cache_admin::prepare_stop))
3520        .route(
3521            routes::LORA_ADAPTERS,
3522            get(lora::get_lora_adapters).post(lora::post_lora_adapters),
3523        )
3524        .route(routes::V1_CHAT_COMPLETIONS, post(chat_completions))
3525        // Behind the same key as the endpoint that started the work:
3526        // an unauthenticated caller must not be able to stop someone
3527        // else's generation by guessing at request ids.
3528        .route(routes::V1_CANCEL, post(cancel_generation))
3529        // Reconnect and the polling fallback, both behind the same key
3530        // as the request that filled the buffer: the replay window holds
3531        // the model's output, so reading it must cost what producing it
3532        // cost.
3533        .route(&axum_path(routes::V1_STREAM), get(resume::resume))
3534        .route(&axum_path(routes::V1_STREAM_POLL), get(resume::poll))
3535        .route(routes::V1_MESSAGES, post(anthropic::messages))
3536        .route(
3537            routes::V1_MESSAGES_COUNT_TOKENS,
3538            post(anthropic::count_tokens),
3539        )
3540        .route(routes::V1_COMPLETIONS, post(openai_extra::completions))
3541        // llama.cpp's NATIVE completion endpoint, under both spellings
3542        // it mounts. Not an alias of the line above: different request
3543        // fields, a different response object, and a stream that ends
3544        // without `[DONE]`. See `crate::completion`.
3545        .route(routes::COMPLETION, post(completion::completion))
3546        .route(routes::COMPLETIONS, post(completion::completion))
3547        .route(routes::V1_TOKENIZE, post(openai_extra::tokenize))
3548        .route(routes::V1_DETOKENIZE, post(openai_extra::detokenize))
3549        // llama.cpp's unprefixed spelling of the same two, on the SAME
3550        // handlers -- not copies. The `/v1/` prefix was frink's
3551        // invention (OpenAI has no tokenize endpoint), so every
3552        // llama.cpp client was getting a 404 that named nothing. Behind
3553        // the key with their twins: they read the loaded vocabulary.
3554        .route(routes::TOKENIZE, post(openai_extra::tokenize))
3555        .route(routes::DETOKENIZE, post(openai_extra::detokenize))
3556        .route(routes::V1_EMBEDDINGS, post(embeddings::embeddings))
3557        // Cross-encoder reranking, under the `/v1` spelling Cohere and
3558        // Jina clients use and the unprefixed one llama.cpp mounts.
3559        // Same handler: this really is an alias, not a second dialect.
3560        .route(routes::V1_RERANK, post(rerank::rerank))
3561        .route(routes::RERANK, post(rerank::rerank))
3562        .route(routes::CACHE_STATS, get(cache_stats))
3563        .route(routes::METRICS, get(metrics))
3564        // The control surface. Registered inside `protected` on
3565        // purpose: these routes change what the server serves and write
3566        // to disk, so they get the same FRINK_API_KEY gate as /v1/*
3567        // and never the unauthenticated treatment /health has.
3568        .route(routes::ADMIN_MODELS, get(admin::models))
3569        .route(routes::ADMIN_MODELS_LOAD, post(admin::load_model))
3570        .route(routes::ADMIN_MODELS_UNLOAD, post(admin::unload_model))
3571        // Not under `/admin`: a scheduler that puts a server to sleep
3572        // between jobs is not administering it, and vLLM's own routes
3573        // are at the root.
3574        .route(routes::SLEEP, post(admin::sleep))
3575        .route(routes::WAKE_UP, post(admin::wake_up))
3576        .route(routes::IS_SLEEPING, get(admin::is_sleeping))
3577        .route(routes::ADMIN_DOWNLOAD, post(admin::download))
3578        .route(routes::ADMIN_TASKS, get(admin::tasks))
3579        .route(&admin::cancel_route(), post(admin::cancel_task))
3580        .route(routes::ADMIN_STATS, get(admin::stats))
3581        // Server-side conversation storage, mounted here so it inherits
3582        // the same key gate as the endpoint that generated the text it
3583        // stores. Routes and store both live in `conversations`.
3584        .merge(conversations::router())
3585}
3586
3587fn axum_path(template: &str) -> String {
3588    let mut out = String::with_capacity(template.len());
3589    let mut rest = template;
3590    while let Some(open) = rest.find('{') {
3591        let Some(close) = rest[open..].find('}').map(|c| open + c) else {
3592            break;
3593        };
3594        out.push_str(&rest[..open]);
3595        out.push(':');
3596        out.push_str(&rest[open + 1..close]);
3597        rest = &rest[close + 1..];
3598    }
3599    out.push_str(rest);
3600    out
3601}
3602
3603/// `POST /v1/cancel` -- the explicit half of two-tier cancellation.
3604///
3605/// Answers `200` when a live generation was signalled and `404` when
3606/// the id names nothing that is running. That difference is the whole
3607/// point of the endpoint returning a body at all: "already finished"
3608/// and "stopped it" are both fine outcomes, but only one of them saved
3609/// any work, and a UI told `ok: true` for both will claim it stopped
3610/// something it did not.
3611async fn cancel_generation(
3612    State(state): State<Arc<AppState>>,
3613    Json(req): Json<frink_api::CancelGenerationRequest>,
3614) -> Response {
3615    let cancelled = state.cancels.cancel(&req.request_id);
3616    let status = if cancelled {
3617        StatusCode::OK
3618    } else {
3619        StatusCode::NOT_FOUND
3620    };
3621    let detail = if cancelled {
3622        "the generation was asked to stop; it ends at its next token".to_string()
3623    } else {
3624        "no generation with that request_id is running -- it has already \
3625         finished, was never issued, or was served by a path that does \
3626         not register for cancellation"
3627            .to_string()
3628    };
3629    (
3630        status,
3631        Json(frink_api::CancelGenerationResponse {
3632            request_id: req.request_id,
3633            cancelled,
3634            detail,
3635        }),
3636    )
3637        .into_response()
3638}
3639
3640/// What a freshly loaded checkpoint becomes when it is published as the
3641/// active model: the model itself, its optional continuous-batching
3642/// worker, and the context ceiling both decode paths admit on.
3643type Activated = (
3644    Loaded,
3645    Option<serving::batch::ContinuousBatcher>,
3646    Option<Arc<budget::ContextCeiling>>,
3647);
3648
3649/// The scheduler config for a freshly loaded GGUF, with the ceilings an
3650/// operator did not configure *derived* from the checkpoint instead of
3651/// left absent.
3652///
3653/// This is the server half of `mem-preload-kv-budget`: `frink run`
3654/// already priced weights + `n_ctx * per_token_kv` + headroom against
3655/// the device budget before loading, while `frink-server` admitted on
3656/// whatever `FRINK_CB_*` happened to be set and otherwise on nothing.
3657///
3658/// Precedence is one-directional and deliberate: an explicit
3659/// `FRINK_CB_MAX_CONTEXT` / `FRINK_CB_KV_BLOCKS` is never overridden,
3660/// because an operator who names a number has information this
3661/// arithmetic does not. Derivation only ever fills an *absent* ceiling,
3662/// where the alternative is no ceiling at all.
3663///
3664/// `path` is `None` for the synthetic-weights fallback, which has no
3665/// checkpoint on disk to price.
3666fn price_batcher_config(path: Option<&str>) -> serving::batch::BatcherConfig {
3667    let mut batcher = serving::batch::BatcherConfig::from_env();
3668    if batcher.max_context.is_some() && batcher.kv_blocks.is_some() {
3669        // Nothing left to derive, and pricing the checkpoint would only
3670        // print arithmetic that decides nothing.
3671        return batcher;
3672    }
3673    let Some(path) = path else {
3674        return batcher;
3675    };
3676    // `frink_core::cache::KvCache` is `Vec<f32>` on both decode paths,
3677    // so f32 is the width really kept, even under Metal attention where
3678    // the *device* also holds an f16 copy. Budgeting the host store is
3679    // the conservative reading: it over-charges KV and therefore
3680    // under-states the context that fits.
3681    let priced = budget::price_gguf(path, frink_models::KvElem::F32, 1);
3682    let Some((priced, gguf_ctx, source)) = priced else {
3683        return batcher;
3684    };
3685    let Some(derived) = budget::derive_limits(&priced, gguf_ctx, batcher.kv_block_size) else {
3686        // See `budget`'s module doc: a fit of zero tokens is not a
3687        // ceiling of zero, it is an estimate saying this model should
3688        // not have loaded -- and it did. Say so and admit as before.
3689        tracing::warn!(
3690            "this checkpoint's weights leave no room for KV inside the {source}: {} weight \
3691             bytes against a {} byte budget. Serving with no derived context ceiling -- set \
3692             FRINK_DEVICE_BUDGET_BYTES if the probe is wrong, or FRINK_CB_MAX_CONTEXT to \
3693             admit on a number you choose.",
3694            priced.weights_bytes,
3695            priced.device_budget_bytes,
3696        );
3697        return batcher;
3698    };
3699    tracing::info!("{source}");
3700    tracing::info!("{}", derived.fit);
3701    let adopted = budget::apply_derived(&mut batcher, &derived);
3702    if adopted.max_context {
3703        tracing::info!(
3704            "derived per-request context ceiling: {} token positions (prompt + max_tokens); \
3705             override with FRINK_CB_MAX_CONTEXT",
3706            derived.max_context
3707        );
3708    }
3709    if adopted.kv_blocks {
3710        tracing::info!(
3711            "derived KV block budget: {} blocks x {} positions; override with FRINK_CB_KV_BLOCKS",
3712            derived.kv_blocks,
3713            batcher.kv_block_size
3714        );
3715    }
3716    if let Some(narrowed) = adopted.max_context_narrowed {
3717        tracing::info!(
3718            "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",
3719            batcher.kv_blocks.unwrap_or_default(),
3720            batcher.kv_block_size
3721        );
3722    }
3723    batcher
3724}
3725
3726/// Turns a freshly loaded checkpoint into the parts that get published
3727/// as the active model.
3728///
3729/// Extracted from `build_app_state` so `/admin/models/load` builds its
3730/// replacement exactly the way startup builds the first one -- a second
3731/// copy of this match would be a second place for a new engine variant
3732/// to be forgotten, and the difference would only show up as a model
3733/// that silently loses continuous batching after a swap.
3734pub(crate) fn activate_loaded_model(
3735    loaded: model::LoadedModel,
3736    enable_continuous_batching: bool,
3737    path: Option<&str>,
3738    paged_kv: Option<&generate::PagedKvConfig>,
3739) -> Activated {
3740    match loaded {
3741        model::LoadedModel::Gguf(g) => {
3742            let decoder = Arc::new(g.decoder);
3743            let tokenizer = Arc::new(g.tokenizer);
3744            let config = price_batcher_config(path);
3745            // Prefill is still a per-token `forward_token` loop on both
3746            // paths (see `sched-chunked-prefill`: chunking bought
3747            // fairness, not a batched prefill kernel), so a sliding
3748            // layer really does need only `window + 1 - 1` positions
3749            // live. `chunk = 1` here is the truth, not a simplification.
3750            let shape =
3751                frink_models::KvShape::from_config(&decoder.config, frink_models::KvElem::F32);
3752            let ceiling = Arc::new(budget::ContextCeiling::new(config.max_context, shape));
3753            let batcher = if enable_continuous_batching {
3754                tracing::info!(
3755                    "continuous batching enabled: decode steps share Decoder::forward_multi_seq \
3756                     (stop sequences use the same pending-buffer trim as the private generate loop)"
3757                );
3758                let tok = Arc::clone(&tokenizer);
3759                let decode = Arc::new(move |ids: &[usize]| tok.decode_bytes(ids));
3760                Some(serving::batch::ContinuousBatcher::spawn_with_ceiling(
3761                    Arc::clone(&decoder),
3762                    decode,
3763                    config,
3764                    Arc::clone(&ceiling),
3765                    paged_kv.cloned(),
3766                ))
3767            } else {
3768                None
3769            };
3770            (
3771                Loaded::Generative(Arc::new(Model::Gguf(GgufModel {
3772                    decoder,
3773                    tokenizer,
3774                    stop_tokens: g.stop_tokens,
3775                    bos_id: g.bos_id,
3776                    is_synthetic: g.is_synthetic,
3777                    chat_template: g.chat_template,
3778                }))),
3779                batcher,
3780                Some(ceiling),
3781            )
3782        }
3783        model::LoadedModel::Kimi(k) => (
3784            Loaded::Generative(Arc::new(Model::Kimi(KimiModel {
3785                engine: k.engine,
3786                tokenizer: k.tokenizer,
3787                stop_tokens: k.stop_tokens,
3788                chat_template: k.chat_template,
3789            }))),
3790            None,
3791            None,
3792        ),
3793        model::LoadedModel::Mla(m) => (
3794            Loaded::Generative(Arc::new(Model::Mla(MlaModel {
3795                engine: m.engine,
3796                tokenizer: m.tokenizer,
3797                stop_tokens: m.stop_tokens,
3798                bos_id: m.bos_id,
3799                name: m.name,
3800                chat_template: m.chat_template,
3801            }))),
3802            None,
3803            None,
3804        ),
3805        model::LoadedModel::Gemma4(m) => (
3806            Loaded::Generative(Arc::new(Model::Gemma4(Gemma4Model {
3807                engine: m.engine,
3808                tokenizer: m.tokenizer,
3809                stop_tokens: m.stop_tokens,
3810                bos_id: m.bos_id,
3811                name: m.name,
3812                chat_template: m.chat_template,
3813            }))),
3814            None,
3815            None,
3816        ),
3817        model::LoadedModel::Glm52(g) => (
3818            Loaded::Generative(Arc::new(Model::Glm52(Glm52Model {
3819                engine: g.engine,
3820                tokenizer: g.tokenizer,
3821                stop_tokens: g.stop_tokens,
3822                bos_id: g.bos_id,
3823                name: g.name,
3824                chat_template: g.chat_template,
3825            }))),
3826            None,
3827            None,
3828        ),
3829        // No batcher and no ceiling, and neither is an omission: an
3830        // encoder has no decode step to share between requests and no
3831        // KV cache to price a context against. Handing it either would
3832        // be pricing a cost it does not have.
3833        model::LoadedModel::Encoder(e) => (Loaded::Encoder(e), None, None),
3834    }
3835}
3836
3837/// The models a server starts with: the generation model, and the
3838/// embedding model when `FRINK_EMBEDDING_MODEL_PATH` names one.
3839///
3840/// One struct rather than two parameters because they are chosen
3841/// together at startup and are the only two things `build_app_state`
3842/// takes that are a *model*.
3843struct StartupModels {
3844    loaded: model::LoadedModel,
3845    embedding: Option<Arc<frink_models::EmbeddingModel>>,
3846}
3847
3848fn continuous_batching_env() -> Option<bool> {
3849    match std::env::var("FRINK_CONTINUOUS_BATCHING")
3850        .ok()
3851        .map(|v| v.trim().to_ascii_lowercase())
3852        .as_deref()
3853    {
3854        None => None,
3855        Some("1" | "true" | "yes" | "on") => Some(true),
3856        Some("0" | "false" | "no" | "off") => Some(false),
3857        _ => None,
3858    }
3859}
3860
3861fn metal_private_decode_active() -> bool {
3862    #[cfg(feature = "metal")]
3863    {
3864        BUILT_WITH_METAL
3865            && frink_metal::attn::metal_attn_enabled()
3866            && std::env::var("FRINK_METAL").ok().as_deref() != Some("0")
3867    }
3868    #[cfg(not(feature = "metal"))]
3869    {
3870        false
3871    }
3872}
3873
3874fn continuous_batching_compatible(
3875    loaded: &model::LoadedModel,
3876    kv_pool: &Option<generate::KvPoolConfig>,
3877    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3878    paged_kv: &Option<generate::PagedKvConfig>,
3879) -> bool {
3880    matches!(loaded, model::LoadedModel::Gguf(_))
3881        && (paged_kv.is_some() || (kv_pool.is_none() && prefix_cache.is_none()))
3882}
3883
3884fn resolve_continuous_batching_enabled(
3885    loaded: &model::LoadedModel,
3886    kv_pool: &Option<generate::KvPoolConfig>,
3887    prefix_cache: &Option<Arc<Mutex<PrefixCache>>>,
3888    paged_kv: &Option<generate::PagedKvConfig>,
3889) -> bool {
3890    if !continuous_batching_compatible(loaded, kv_pool, prefix_cache, paged_kv) {
3891        return false;
3892    }
3893    match continuous_batching_env() {
3894        Some(true) => true,
3895        Some(false) => false,
3896        None => metal_private_decode_active(),
3897    }
3898}
3899
3900fn acquire_metal_private_decode_gate(
3901    gate: Option<&std::sync::Mutex<()>>,
3902    used_batcher: bool,
3903) -> Option<std::sync::MutexGuard<'_, ()>> {
3904    if used_batcher {
3905        None
3906    } else {
3907        gate.map(|g| g.lock().unwrap_or_else(|p| p.into_inner()))
3908    }
3909}
3910
3911fn build_app_state(
3912    models: StartupModels,
3913    kv_pool: Option<generate::KvPoolConfig>,
3914    paged_kv: Option<generate::PagedKvConfig>,
3915    prefix_cache: Option<Arc<Mutex<PrefixCache>>>,
3916    enable_continuous_batching: bool,
3917    mcp: Option<mcp::LoadedMcpConfig>,
3918    detection: Arc<health::Detection>,
3919) -> AppState {
3920    let StartupModels { loaded, embedding } = models;
3921    let configured_path = std::env::var("FRINK_MODEL_PATH").ok();
3922    let (loaded, batcher, ceiling) = activate_loaded_model(
3923        loaded,
3924        enable_continuous_batching,
3925        configured_path.as_deref(),
3926        paged_kv.as_ref(),
3927    );
3928    // The startup model's admin id is whichever discovered entry sits
3929    // at the configured path; `None` when it was not discovered (the
3930    // synthetic fallback, or a path outside the scanned directories),
3931    // in which case `/admin/models` reports nothing as active rather
3932    // than inventing an id no `load` request could name.
3933    let id = startup_model_id();
3934    let metal_private_decode_gate = if enable_continuous_batching || !metal_private_decode_active()
3935    {
3936        None
3937    } else {
3938        tracing::info!(
3939            "Metal private-loop decode will serialize concurrent requests until \
3940             continuous batching is enabled (FRINK_CONTINUOUS_BATCHING=1 or --cont-batching)"
3941        );
3942        Some(Arc::new(std::sync::Mutex::new(())))
3943    };
3944    AppState {
3945        slept: Mutex::new(None),
3946        embedding,
3947        active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
3948            id,
3949            loaded,
3950            batcher,
3951            ceiling,
3952            checkpoint_path: configured_path.as_deref().map(PathBuf::from),
3953        }))),
3954        paged_kv,
3955        load_in_progress: std::sync::atomic::AtomicBool::new(false),
3956        tasks: Arc::new(tasks::TaskRegistry::new()),
3957        cancels: Arc::new(cancel::CancelRegistry::new()),
3958        stats: stats::Stats::new(),
3959        streams: resume::StreamRegistry::new(),
3960        model_dir: admin::model_dirs().into_iter().next(),
3961        response_cache: Mutex::new(ResponseCache::new(1000, Duration::from_secs(3600))),
3962        kv_pool,
3963        prefix_cache,
3964        sessions: session::SessionStore::new(),
3965        requests_total: std::sync::atomic::AtomicU64::new(0),
3966        request_errors_total: std::sync::atomic::AtomicU64::new(0),
3967        started_at: std::time::Instant::now(),
3968        last_request_ms: std::sync::atomic::AtomicU64::new(0),
3969        detection,
3970        mcp,
3971        continuous_batching_enabled: enable_continuous_batching,
3972        metal_private_decode_gate,
3973        loading_model: Mutex::new(None),
3974        last_load_error: Mutex::new(None),
3975        serving: Mutex::new(crate::stats::ServingStats::default()),
3976        maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
3977        footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
3978        started_unix: unix_now(),
3979    }
3980}
3981
3982/// Builds the `/v1/embeddings` encoder from
3983/// `FRINK_EMBEDDING_MODEL_PATH`, or `None` when the variable is unset.
3984///
3985/// A failure here is fatal rather than deferred: a server that starts
3986/// with a misspelt path and then answers embedding requests out of the
3987/// *decoder* would be handing back vectors from the wrong model with
3988/// nothing in the response saying so.
3989fn load_embedding_model() -> anyhow::Result<Option<Arc<frink_models::EmbeddingModel>>> {
3990    let Ok(path) = std::env::var("FRINK_EMBEDDING_MODEL_PATH") else {
3991        return Ok(None);
3992    };
3993    let model = frink_models::EmbeddingModel::from_gguf_path(&path)
3994        .map_err(|e| anyhow::anyhow!("FRINK_EMBEDDING_MODEL_PATH={path}: {e}"))?;
3995    tracing::info!(
3996        "loaded embedding model '{}' ({}, {} dims, pooling {}, max {} tokens)",
3997        model.name(),
3998        model.architecture(),
3999        model.n_embd(),
4000        model.pooling_type().name(),
4001        model.n_ctx_train(),
4002    );
4003    Ok(Some(Arc::new(model)))
4004}
4005
4006/// Seconds since the epoch, or zero on a machine whose clock is set
4007/// before it. Only ever used to make an id distinct between process
4008/// generations, so a nonsense clock costs distinctness and nothing
4009/// else.
4010fn unix_now() -> u64 {
4011    std::time::SystemTime::now()
4012        .duration_since(std::time::UNIX_EPOCH)
4013        .map(|d| d.as_secs())
4014        .unwrap_or(0)
4015}
4016
4017/// The `/admin/models` id of the checkpoint `FRINK_MODEL_PATH` names,
4018/// when discovery finds it. Matching on the resolved path rather than
4019/// on the filename keeps two same-named files in different directories
4020/// from claiming each other's id.
4021fn startup_model_id() -> Option<String> {
4022    let configured = std::env::var("FRINK_MODEL_PATH").ok()?;
4023    let configured = std::fs::canonicalize(&configured).ok()?;
4024    admin::discover(&admin::model_dirs())
4025        .into_iter()
4026        .find(|d| {
4027            std::fs::canonicalize(&d.path)
4028                .map(|p| p == configured)
4029                .unwrap_or(false)
4030        })
4031        .map(|d| d.id)
4032}
4033
4034/// Builds the global rayon pool up front, on the main thread, with an
4035/// explicit width and QoS (see [`frink_core::threads`]).
4036///
4037/// Doing this from `main` rather than letting rayon build lazily is the
4038/// point: the first rayon call inside this server happens on a Tokio
4039/// `spawn_blocking` thread, so the workers used to inherit that thread's
4040/// QoS class -- which on macOS decides whether they land on performance
4041/// or efficiency cores.
4042fn init_cpu_pool() {
4043    match frink_core::threads::init_cpu_pool() {
4044        Some(n) => eprintln!(
4045            "frink-server: rayon pool {n} threads (perf cores {}; override with FRINK_CPU_THREADS)",
4046            frink_core::threads::perf_core_count()
4047        ),
4048        None => eprintln!("frink-server: global rayon pool already built; leaving it alone"),
4049    }
4050}
4051
4052/// Prints the machine-readable ready line (see `frink_api::lifecycle`)
4053/// on stdout and flushes it.
4054///
4055/// This one line is what makes `--port 0` usable, and it deletes a whole
4056/// feature from any supervising process: no "is the port free" probe, no
4057/// `lsof` to work out whether an existing listener is a stale copy of
4058/// ourselves or a stranger's server, no dialog to explain the result.
4059/// The kernel picks the port and the child says what it got.
4060///
4061/// Shares stdout with the tracing subscriber on purpose -- a parent
4062/// reads stdout line by line and ignores anything that is not the ready
4063/// event, which `ServerReady::from_line` does for it.
4064fn announce_ready(addr: SocketAddr, scheme: &str) {
4065    use std::io::Write;
4066    let ready =
4067        frink_api::ServerReady::new(addr, scheme, env!("CARGO_PKG_VERSION"), std::process::id());
4068    let mut stdout = std::io::stdout().lock();
4069    let _ = writeln!(stdout, "{}", ready.to_line());
4070    let _ = stdout.flush();
4071}
4072
4073/// Resolves when the server should stop serving.
4074///
4075/// Stdin-close is the one orphan-prevention mechanism that behaves
4076/// identically on macOS, Windows and Linux and survives a parent that
4077/// dies rather than exiting cleanly: the kernel closes the pipe either
4078/// way. The POSIX alternative -- a signal handler plus an exit hook plus
4079/// a reaper -- has no Windows equivalent at all, since there is no
4080/// SIGTERM there.
4081///
4082/// When disabled this future never resolves, which is exactly the
4083/// previous behaviour: serve until the process is stopped externally.
4084async fn shutdown_signal(exit_on_stdin_close: bool) {
4085    if !exit_on_stdin_close {
4086        std::future::pending::<()>().await;
4087        return;
4088    }
4089    let _ = tokio::task::spawn_blocking(|| {
4090        use std::io::Read;
4091        let mut sink = [0u8; 256];
4092        let mut stdin = std::io::stdin().lock();
4093        loop {
4094            match stdin.read(&mut sink) {
4095                // EOF: the parent is gone, or closed the pipe.
4096                Ok(0) => break,
4097                // Input on stdin is not a protocol here; drain it.
4098                Ok(_) => continue,
4099                Err(e) => {
4100                    tracing::warn!("stdin read failed ({e}); treating it as closed");
4101                    break;
4102                }
4103            }
4104        }
4105    })
4106    .await;
4107    tracing::info!("stdin closed; shutting down");
4108}
4109
4110/// Tokio worker threads. The default is one per logical core, which on a
4111/// 10-core M2 Pro means 10 async workers oversubscribing the same cores
4112/// the rayon decode pool needs. Serving work here is almost entirely I/O
4113/// plus `spawn_blocking` handoff, so a small fixed pool is enough.
4114fn tokio_worker_threads() -> usize {
4115    std::env::var("FRINK_TOKIO_WORKERS")
4116        .ok()
4117        .and_then(|v| v.trim().parse::<usize>().ok())
4118        .filter(|n| *n > 0)
4119        .unwrap_or(2)
4120}
4121
4122/// Parses llama-server-style options and applies their environment
4123/// overrides before creating Tokio or Rayon worker threads. It then
4124/// brackets the async server lifecycle with journal records.
4125/// Install rustls' `ring` crypto provider as the process default.
4126///
4127/// `axum-server` is built with `tls-rustls-no-provider`, which
4128/// deliberately does NOT pick a backend -- see the comment on the
4129/// dependency in `Cargo.toml`. rustls then has no default provider, and
4130/// building a `ServerConfig` without one fails at ACCEPT time rather
4131/// than at compile time, which is the worst place for it to surface: a
4132/// server that started cleanly and refuses every TLS connection.
4133///
4134/// So this runs unconditionally at startup, not lazily in the TLS arm.
4135/// `install_default` returns `Err` if a provider is already installed,
4136/// which is not a failure -- it means something else got there first
4137/// and the invariant we care about (there IS a provider) already holds.
4138fn install_ring_crypto_provider() {
4139    let _ = rustls::crypto::ring::default_provider().install_default();
4140}
4141
4142/// Runs the server to completion.
4143///
4144/// Takes already-parsed arguments so the same library backs both the
4145/// `frink-server` binary and frink-cli's optional `serve` feature,
4146/// and neither front end can drift into its own startup logic.
4147pub fn run_server(args: ServerArgs) -> anyhow::Result<()> {
4148    if args.list_devices {
4149        frink_models::devices::print_available_devices();
4150        return Ok(());
4151    }
4152    apply_cli_overrides(&args)?;
4153
4154    // Before the model is loaded and before the port is bound: refuse
4155    // to be the second process holding weights on this host. Held for
4156    // the life of the process -- dropping it deregisters us.
4157    let _instance = {
4158        use frink_core::instance::{register, InstancePolicy};
4159        let policy = if args.allow_multiple_instances {
4160            InstancePolicy::Multi
4161        } else {
4162            InstancePolicy::from_env_or(InstancePolicy::Single)
4163        };
4164        let model = std::env::var("FRINK_MODEL_PATH").ok();
4165        register(
4166            "server",
4167            model.as_deref(),
4168            frink_core::instance::current_backend(),
4169            policy,
4170        )
4171        .map_err(|conflict| anyhow::anyhow!("{conflict}"))?
4172    };
4173
4174    let journal = journal::Journal::from_env();
4175    eprintln!(
4176        "frink-server: process lifecycle journal at {:?} (override with FRINK_JOURNAL_PATH)",
4177        journal.path()
4178    );
4179    journal.append(&journal::Record::session_start(
4180        env!("CARGO_PKG_VERSION"),
4181        std::process::id(),
4182    ));
4183    journal::install_panic_hook(journal.clone());
4184
4185    let mcp_config_path = args.mcp_config.clone();
4186    let exit_on_stdin_close = args.exit_on_stdin_close
4187        || std::env::var("FRINK_EXIT_ON_STDIN_CLOSE")
4188            .map(|v| v == "1")
4189            .unwrap_or(false);
4190
4191    // Before Tokio exists, so the decode pool's threads are not spawned
4192    // from (and do not inherit the QoS of) a blocking-pool thread.
4193    // SAFETY: still single-threaded here.
4194    unsafe { frink_core::weight_matrix::default_cpu_int_dot_on() };
4195    init_cpu_pool();
4196
4197    let runtime = tokio::runtime::Builder::new_multi_thread()
4198        .worker_threads(tokio_worker_threads())
4199        .enable_all()
4200        .build()?;
4201    let result = runtime.block_on(run(mcp_config_path, exit_on_stdin_close));
4202
4203    let reason = match &result {
4204        Ok(()) => "normal".to_string(),
4205        Err(e) => e.to_string(),
4206    };
4207    journal.append(&journal::Record::session_exit(reason));
4208
4209    // Dropping the runtime instead would wait for blocking tasks, and
4210    // the stdin watcher parks in a blocking read that may never return
4211    // (a terminal keeps stdin open forever). The serving future has
4212    // already finished by here, so nothing useful is being abandoned.
4213    runtime.shutdown_background();
4214
4215    result
4216}
4217
4218async fn run(mcp_config_path: Option<PathBuf>, exit_on_stdin_close: bool) -> anyhow::Result<()> {
4219    // `try_init`, not `init`. As a library this runs inside a process
4220    // that may already have a subscriber: frink-cli installs one
4221    // before it dispatches, so `frink serve` would panic on startup
4222    // with "a global default trace dispatcher has already been set".
4223    // Losing the race is not an error, it means logging is configured.
4224    let _ = tracing_subscriber::fmt::try_init();
4225
4226    // Fail-closed listener check, before anything else (including
4227    // loading the model, so a misconfigured bind fails fast rather than
4228    // after however long that takes): refuse to start bound to a
4229    // non-loopback address with no API key configured, unless the
4230    // operator has explicitly opted into that via
4231    // FRINK_ALLOW_UNAUTHENTICATED_REMOTE=1 -- see
4232    // `security::check_bind_authorization`'s doc comment for why an
4233    // address that doesn't even parse as loopback is treated the same
4234    // as a confirmed non-loopback one.
4235    let addr = std::env::var("FRINK_ADDR").unwrap_or_else(|_| "127.0.0.1:8383".to_string());
4236    let api_key_configured = std::env::var("FRINK_API_KEY").is_ok();
4237    let allow_unauthenticated_remote = std::env::var("FRINK_ALLOW_UNAUTHENTICATED_REMOTE")
4238        .map(|v| v == "1")
4239        .unwrap_or(false);
4240    if let Err(msg) =
4241        security::check_bind_authorization(&addr, api_key_configured, allow_unauthenticated_remote)
4242    {
4243        anyhow::bail!(msg);
4244    }
4245
4246    // Loaded before the generation model, so a bad path fails the
4247    // start rather than the first `/v1/embeddings` request. This is the
4248    // SIDE-CAR: a second checkpoint beside a generative one. An encoder
4249    // at `FRINK_MODEL_PATH` needs none of this -- it goes through
4250    // `model::load()` below like any other checkpoint and becomes the
4251    // active model.
4252    let embedding_model = load_embedding_model()?;
4253
4254    let mut loaded = model::load()?;
4255    match &loaded {
4256        model::LoadedModel::Gguf(g) => tracing::info!(
4257            "loaded GGUF model '{}' (synthetic={}, tokenizer={})",
4258            g.decoder.config.name,
4259            g.is_synthetic,
4260            g.tokenizer.kind()
4261        ),
4262        model::LoadedModel::Kimi(k) => tracing::info!(
4263            "loaded Kimi K3 checkpoint (tokenizer={} base tokens)",
4264            k.tokenizer.vocab_size()
4265        ),
4266        model::LoadedModel::Mla(m) => tracing::info!(
4267            "loaded MLA GGUF '{}' (tokenizer={})",
4268            m.name,
4269            m.tokenizer.kind()
4270        ),
4271        model::LoadedModel::Gemma4(m) => tracing::info!(
4272            "loaded Gemma4 GGUF '{}' (tokenizer={})",
4273            m.name,
4274            m.tokenizer.kind()
4275        ),
4276        model::LoadedModel::Glm52(g) => tracing::info!(
4277            "loaded GLM-5.2 GGUF '{}' (tokenizer={})",
4278            g.name,
4279            g.tokenizer.kind()
4280        ),
4281        // `model::load_encoder_checkpoint` has already logged the
4282        // dimensions, the pooling rule and which endpoint serves it.
4283        model::LoadedModel::Encoder(_) => {}
4284    }
4285    // Opt-in VRAM budget for GPU-resident MoE experts. When unset but
4286    // Metal is active, default to a large budget so routed experts that
4287    // have Metal-capable quants run via `run_expert_placed` (Metal
4288    // matvec) instead of staying on CPU after Metal attention. Explicit
4289    // `FRINK_GPU_VRAM_BUDGET_BYTES=0` keeps the historical all-CPU MoE
4290    // placement. CUDA builds still require an explicit budget (Vast /
4291    // multi-GPU hosts vary too much for a safe default).
4292    let metal_default_moe_budget = {
4293        #[cfg(feature = "metal")]
4294        {
4295            frink_core::metal_dense_enabled()
4296                && std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES").is_err()
4297        }
4298        #[cfg(not(feature = "metal"))]
4299        {
4300            false
4301        }
4302    };
4303    if let Ok(budget_str) = std::env::var("FRINK_GPU_VRAM_BUDGET_BYTES") {
4304        let budget: u64 = budget_str
4305            .parse()
4306            .expect("FRINK_GPU_VRAM_BUDGET_BYTES must be a non-negative integer");
4307        match &mut loaded {
4308            model::LoadedModel::Gguf(g) => {
4309                tracing::info!(
4310                    "GPU expert placement enabled: {budget} byte VRAM budget for routed experts \
4311                     (CUDA and/or Metal matvecs when built with the matching feature)"
4312                );
4313                g.decoder.gpu_vram_budget_bytes = Some(budget);
4314            }
4315            model::LoadedModel::Kimi(_) => {
4316                tracing::warn!(
4317                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Kimi K3 -- not \
4318                     supported yet (its MoE stack isn't wired to PlacementPlan), ignoring"
4319                );
4320            }
4321            model::LoadedModel::Mla(_) => {
4322                tracing::warn!(
4323                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is MLA -- dense \
4324                     FFN path only today; ignoring expert VRAM budget"
4325                );
4326            }
4327            model::LoadedModel::Gemma4(_) => {
4328                tracing::warn!(
4329                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is Gemma4 -- \
4330                     ignoring expert VRAM budget"
4331                );
4332            }
4333            model::LoadedModel::Glm52(_) => {
4334                tracing::warn!(
4335                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is GLM-5.2 DSA -- \
4336                     GPU expert placement not wired yet; ignoring"
4337                );
4338            }
4339            model::LoadedModel::Encoder(_) => {
4340                tracing::warn!(
4341                    "FRINK_GPU_VRAM_BUDGET_BYTES is set but the loaded model is an encoder -- \
4342                     it has no routed experts to place; ignoring"
4343                );
4344            }
4345        }
4346    } else if metal_default_moe_budget {
4347        // ~64 GiB sentinel: place as many experts as the planner allows;
4348        // Metal unified memory makes a hard VRAM split less meaningful
4349        // than on discrete CUDA cards.
4350        const METAL_DEFAULT_MOE_BUDGET: u64 = 64 * 1024 * 1024 * 1024;
4351        if let model::LoadedModel::Gguf(g) = &mut loaded {
4352            tracing::info!(
4353                "Metal MoE expert placement default-on ({METAL_DEFAULT_MOE_BUDGET} byte budget); \
4354                 set FRINK_GPU_VRAM_BUDGET_BYTES=0 to force CPU experts"
4355            );
4356            g.decoder.gpu_vram_budget_bytes = Some(METAL_DEFAULT_MOE_BUDGET);
4357        }
4358    }
4359    #[cfg(feature = "cuda")]
4360    {
4361        if frink_core::cuda_dense_enabled() {
4362            tracing::info!(
4363                "CUDA dense matvec enabled for WeightMatrix::apply \
4364                 (FRINK_CUDA=0|cpu forces CPU; weight buffers stay resident after first upload)"
4365            );
4366        } else {
4367            tracing::info!(
4368                "CUDA dense matvec disabled (FRINK_CUDA); dense decode uses CPU or Metal"
4369            );
4370        }
4371    }
4372    #[cfg(feature = "metal")]
4373    {
4374        if frink_core::metal_dense_enabled() {
4375            tracing::info!(
4376                "Metal dense matvec enabled for WeightMatrix::apply \
4377                 (FRINK_METAL=0|cpu forces CPU; weight buffers stay resident after first upload)"
4378            );
4379            match std::env::var("FRINK_METAL_ATTN").ok().as_deref() {
4380                Some("1") | Some("true") | Some("on") | Some("attn") => {
4381                    tracing::info!(
4382                        "Metal fused attention requested (FRINK_METAL_ATTN): \
4383                         QKV→RoPE→GQA→O on-GPU for Norm/NeoX decode without QKV bias/QK-norm"
4384                    );
4385                }
4386                _ => {}
4387            }
4388            tracing::info!(
4389                "Metal greedy GPU argmax: temperature<=0 folds \
4390                 final_norm+lm_head+argmax into the dense stack"
4391            );
4392        } else {
4393            tracing::info!("Metal dense matvec disabled (FRINK_METAL); dense decode uses CPU");
4394        }
4395    }
4396    // Both env vars are required together to enable pooling; unset ->
4397    // caches keep their original unbounded-per-request growth. This
4398    // mirrors the FRINK_API_KEY / FRINK_RATE_LIMIT_PER_MINUTE
4399    // pattern below: opt-in, off by default.
4400    //
4401    // Block count can be set explicitly (`FRINK_KV_POOL_BLOCKS` +
4402    // `FRINK_KV_POOL_BLOCK_SIZE`) or derived from a byte budget
4403    // (`FRINK_KV_BYTE_BUDGET` + `FRINK_KV_POOL_BLOCK_SIZE`, GGUF
4404    // models only). `FRINK_KV_POOL_BLOCKS` and
4405    // `FRINK_KV_BYTE_BUDGET` are mutually exclusive.
4406    let blocks_env = std::env::var("FRINK_KV_POOL_BLOCKS");
4407    let block_size_env = std::env::var("FRINK_KV_POOL_BLOCK_SIZE");
4408    let byte_budget_env = std::env::var("FRINK_KV_BYTE_BUDGET");
4409    if blocks_env.is_ok() && byte_budget_env.is_ok() {
4410        panic!(
4411            "FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive \
4412             (set one block-count source plus FRINK_KV_POOL_BLOCK_SIZE, or neither to disable)"
4413        );
4414    }
4415    let kv_pool = match (blocks_env, block_size_env, byte_budget_env) {
4416        (Ok(blocks), Ok(block_size), Err(_)) => {
4417            let total_blocks: usize = blocks
4418                .parse()
4419                .expect("FRINK_KV_POOL_BLOCKS must be a positive integer");
4420            let block_size: usize = block_size
4421                .parse()
4422                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4423            // Optional and independent of the two above: how long a
4424            // request retries before giving up when the pool is
4425            // momentarily exhausted, instead of rejecting on the very
4426            // first failed attempt. Zero (the default if unset)
4427            // preserves the original reject-immediately behavior.
4428            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4429                .ok()
4430                .map(|v| {
4431                    v.parse()
4432                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4433                })
4434                .unwrap_or(0);
4435            tracing::info!(
4436                "KV cache block pool enabled: {total_blocks} blocks x {block_size} positions \
4437                 each, shared across all concurrent requests, {queue_wait_ms}ms admission queue wait"
4438            );
4439            Some(generate::KvPoolConfig {
4440                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4441                queue_wait: Duration::from_millis(queue_wait_ms),
4442            })
4443        }
4444        (Err(_), Ok(block_size), Ok(byte_budget)) => {
4445            let block_size: usize = block_size
4446                .parse()
4447                .expect("FRINK_KV_POOL_BLOCK_SIZE must be a positive integer");
4448            let budget: u64 = byte_budget
4449                .parse()
4450                .expect("FRINK_KV_BYTE_BUDGET must be a positive integer");
4451            let cfg = match &loaded {
4452                model::LoadedModel::Gguf(g) => &g.decoder.config,
4453                model::LoadedModel::Kimi(_)
4454                | model::LoadedModel::Mla(_)
4455                | model::LoadedModel::Gemma4(_)
4456                | model::LoadedModel::Glm52(_)
4457                | model::LoadedModel::Encoder(_) => {
4458                    panic!(
4459                        "FRINK_KV_BYTE_BUDGET requires a GGUF decoder model \
4460                         (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4461                    );
4462                }
4463            };
4464            let bytes_per_block = block_size
4465                * cfg.kv_heads_all_layers()
4466                * (cfg.head_dim + cfg.v_head_dim())
4467                * std::mem::size_of::<f32>();
4468            assert!(
4469                bytes_per_block > 0,
4470                "derived KV block byte size must be positive (check model config and block size)"
4471            );
4472            let total_blocks = (budget as usize / bytes_per_block).max(1);
4473            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4474                .ok()
4475                .map(|v| {
4476                    v.parse()
4477                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4478                })
4479                .unwrap_or(0);
4480            tracing::info!(
4481                "KV cache block pool enabled from byte budget: {budget} bytes / \
4482                 {bytes_per_block} bytes per block ({block_size} positions x {} layers) -> \
4483                 {total_blocks} blocks, {queue_wait_ms}ms admission queue wait",
4484                cfg.n_layers
4485            );
4486            Some(generate::KvPoolConfig {
4487                pool: Arc::new(Mutex::new(KvBlockPool::new(block_size, total_blocks))),
4488                queue_wait: Duration::from_millis(queue_wait_ms),
4489            })
4490        }
4491        (Err(_), Err(_), Err(_)) => None,
4492        (Err(_), Ok(_), Err(_)) => panic!(
4493            "FRINK_KV_POOL_BLOCK_SIZE requires FRINK_KV_POOL_BLOCKS or FRINK_KV_BYTE_BUDGET \
4494             (or unset all three to disable KV cache pooling)"
4495        ),
4496        (Ok(_), Ok(_), Ok(_)) => {
4497            unreachable!("FRINK_KV_POOL_BLOCKS and FRINK_KV_BYTE_BUDGET are mutually exclusive")
4498        }
4499        (Ok(_), Err(_), _) | (Err(_), Err(_), Ok(_)) => panic!(
4500            "FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET and FRINK_KV_POOL_BLOCK_SIZE must be \
4501             set together (or neither, to disable KV cache pooling)"
4502        ),
4503    };
4504    // Paged KV: per-layer shared page storage rather than a private
4505    // contiguous buffer per request. Refused alongside the pool and the
4506    // prefix cache rather than silently preferred over either -- an
4507    // operator who set two of these meant one of them, and picking for
4508    // them is how a deployment ends up not running what it thinks.
4509    let paged_kv = match (
4510        std::env::var("FRINK_PAGED_KV_BLOCKS"),
4511        std::env::var("FRINK_PAGED_KV_BLOCK_SIZE"),
4512    ) {
4513        (Ok(blocks), Ok(block_size)) => {
4514            assert!(
4515                kv_pool.is_none(),
4516                "FRINK_PAGED_KV_BLOCKS and FRINK_KV_POOL_BLOCKS/FRINK_KV_BYTE_BUDGET are \
4517                 mutually exclusive: both bound the same KV memory, by different means. \
4518                 Set one."
4519            );
4520            // Paged KV used to be refused here on any GPU backend,
4521            // because it returned fluent wrong tokens on Metal: the
4522            // prefill left K/V on the device and filled the host cache
4523            // with `KvCache::advance_len` placeholders, and the paged
4524            // prefill then copied those placeholders into the page
4525            // store. The decode that followed attended over a prompt
4526            // the model never saw.
4527            //
4528            // Fixed in `frink_models::Decoder`, which now downloads
4529            // the real rows for the caller that reads them, and pinned
4530            // on hardware by `paged_metal_parity` -- greedy ids
4531            // identical between paged and contiguous KV on a dense
4532            // model, an MoE model and a sliding-window model.
4533            let blocks_per_layer: usize = blocks
4534                .parse()
4535                .expect("FRINK_PAGED_KV_BLOCKS must be a positive integer");
4536            let block_size: usize = block_size
4537                .parse()
4538                .expect("FRINK_PAGED_KV_BLOCK_SIZE must be a positive integer");
4539            let gguf = match &loaded {
4540                model::LoadedModel::Gguf(g) => g,
4541                _ => panic!(
4542                    "FRINK_PAGED_KV_BLOCKS requires a GGUF decoder model \
4543                     (set FRINK_MODEL_PATH to a generic-decoder .gguf file)"
4544                ),
4545            };
4546            let cfg = &gguf.decoder.config;
4547            let queue_wait_ms: u64 = std::env::var("FRINK_KV_POOL_QUEUE_TIMEOUT_MS")
4548                .ok()
4549                .map(|v| {
4550                    v.parse()
4551                        .expect("FRINK_KV_POOL_QUEUE_TIMEOUT_MS must be a non-negative integer")
4552                })
4553                .unwrap_or(0);
4554            tracing::info!(
4555                "Paged KV enabled: {blocks_per_layer} blocks x {block_size} positions per \
4556                 layer across {} layers, shared by all concurrent requests, \
4557                 {queue_wait_ms}ms admission queue wait",
4558                cfg.n_layers
4559            );
4560            // Prefix sharing rides on the same switch: paged KV is
4561            // what makes it possible at all, since sharing means two
4562            // sequences pointing at one page rather than one of them
4563            // holding a copy.
4564            let radix = Some(Arc::new(Mutex::new(
4565                crate::policy::radix::SaltedRadix::new(block_size),
4566            )));
4567            // The anchor: the position an agentic turn will come back
4568            // to. Resolved ONCE here, from the served checkpoint's own
4569            // family and its own tokenizer, because it has to be a
4570            // single token id for the slide to recognize it on the hot
4571            // path for nothing. A checkpoint whose opener is more than
4572            // one token, or whose family has no opener at all (harmony
4573            // opens a call with an ordinary channel header), simply gets
4574            // no anchors and the slide follows the cursor.
4575            let anchor_token = crate::policy::anchor::resolve_anchor_token(
4576                crate::policy::parser::ToolCallFormat::infer(
4577                    &std::env::var("FRINK_MODEL_PATH").unwrap_or_default(),
4578                )
4579                .opener(),
4580                |text| {
4581                    gguf.tokenizer
4582                        .encode(text, SpecialTokens::Parse)
4583                        .into_iter()
4584                        .map(|t| t as u32)
4585                        .collect()
4586                },
4587            );
4588            if let Some(id) = anchor_token {
4589                tracing::info!(
4590                    "Paged KV window slide: tool-call anchor is token {id}, so a turn's \
4591                     window stops short of where its next turn rejoins"
4592                );
4593            }
4594            let slide_interval: usize = std::env::var("FRINK_PAGED_KV_SLIDE_INTERVAL")
4595                .ok()
4596                .map(|v| {
4597                    v.parse()
4598                        .expect("FRINK_PAGED_KV_SLIDE_INTERVAL must be a positive integer")
4599                })
4600                .unwrap_or(crate::policy::pool_budget::DEFAULT_SWA_EVICTION_INTERVAL);
4601            if let Some(window) = cfg.uniform_sliding_window() {
4602                tracing::info!(
4603                    "Paged KV window slide enabled: every layer slides by {window} every \
4604                     {slide_interval} decode steps, so a request holds its prompt and a \
4605                     window rather than its whole context"
4606                );
4607            } else if cfg.kv_block_window().is_some() {
4608                tracing::info!(
4609                    "Paged KV window slide NOT enabled: this model has full-attention layers, \
4610                     and a page group holds one block in every layer"
4611                );
4612            }
4613            Some(generate::PagedKvConfig {
4614                // Per layer, because a per-layer-shape model's layers do
4615                // not all cache the same width (`layer_shapes`).
4616                store: Arc::new(cfg.new_paged_kv(block_size, blocks_per_layer)),
4617                queue_wait: Duration::from_millis(queue_wait_ms),
4618                radix,
4619                anchor_token,
4620                slide_interval,
4621            })
4622        }
4623        (Err(_), Err(_)) => None,
4624        _ => panic!(
4625            "FRINK_PAGED_KV_BLOCKS and FRINK_PAGED_KV_BLOCK_SIZE must be set together \
4626             (or neither, to disable paged KV)"
4627        ),
4628    };
4629    // Mutually exclusive with kv_pool (see generate::generate's doc
4630    // comment on why a pool-backed cache can't safely be restored from
4631    // a prefix-cache clone): if both are set, the KV pool wins and
4632    // prefix caching is simply never consulted -- generate() already
4633    // enforces this per-request, so this is a heads-up for the
4634    // operator, not a hard failure.
4635    let prefix_cache = std::env::var("FRINK_PREFIX_CACHE_ENTRIES").ok().map(|v| {
4636        let max_entries: usize = v
4637            .parse()
4638            .expect("FRINK_PREFIX_CACHE_ENTRIES must be a positive integer");
4639        if kv_pool.is_some() {
4640            tracing::warn!(
4641                "FRINK_PREFIX_CACHE_ENTRIES is set but so is the KV pool -- prefix \
4642                     caching will never be consulted while a KV pool is configured"
4643            );
4644        }
4645        // A hard refusal rather than the warning above, because the
4646        // outcome is worse than "never consulted": `PrefixCache` stores
4647        // `Vec<KvCache>` snapshots, and a paged request has none to
4648        // give, so every store would be skipped and every lookup miss.
4649        // An operator would see a prefix cache configured, reporting
4650        // zero hits forever, with nothing saying why.
4651        assert!(
4652            paged_kv.is_none(),
4653            "FRINK_PREFIX_CACHE_ENTRIES and FRINK_PAGED_KV_BLOCKS are mutually exclusive: \
4654             the prefix cache stores contiguous KV snapshots, which a paged request does not \
4655             produce, so the cache could never hit. Set one."
4656        );
4657        tracing::info!(
4658            "KV-prefix cache enabled: up to {max_entries} stored prefixes, shared across \
4659                 all requests"
4660        );
4661        Arc::new(Mutex::new(PrefixCache::new(max_entries)))
4662    });
4663    if matches!(
4664        loaded,
4665        model::LoadedModel::Kimi(_) | model::LoadedModel::Mla(_) | model::LoadedModel::Glm52(_)
4666    ) && (kv_pool.is_some() || prefix_cache.is_some())
4667    {
4668        tracing::warn!(
4669            "KV pool / prefix cache are configured but the loaded model is Kimi, MLA, or GLM-5.2 -- \
4670             neither is consulted for those engines (state shapes differ from Decoder KV); see \
4671             frink_models::engine's module docs"
4672        );
4673    }
4674    let enable_cb =
4675        resolve_continuous_batching_enabled(&loaded, &kv_pool, &prefix_cache, &paged_kv);
4676    if enable_cb && continuous_batching_env().is_none() && metal_private_decode_active() {
4677        tracing::info!(
4678            "continuous batching enabled by default on Metal for safe parallel serving \
4679             (set FRINK_CONTINUOUS_BATCHING=0 or --no-cont-batching to use the private path)"
4680        );
4681    }
4682    if continuous_batching_env() == Some(true)
4683        && !continuous_batching_compatible(&loaded, &kv_pool, &prefix_cache, &paged_kv)
4684        && (kv_pool.is_some() || prefix_cache.is_some())
4685    {
4686        tracing::warn!(
4687            "FRINK_CONTINUOUS_BATCHING=1 ignored while KV pool or prefix cache is configured \
4688             (those modes keep the private generate path)"
4689        );
4690    }
4691    if let Ok(n) = std::env::var("FRINK_CHUNKED_PREFILL") {
4692        if let Ok(chunk) = n.parse::<usize>() {
4693            if chunk > 0 {
4694                tracing::info!("chunked prefill enabled: {chunk} tokens per forward_batch chunk");
4695            }
4696        }
4697    }
4698    if matches!(
4699        std::env::var("FRINK_CPU_KV_OFFLOAD").ok().as_deref(),
4700        Some("1")
4701    ) {
4702        tracing::warn!(
4703            "FRINK_CPU_KV_OFFLOAD=1: syncing Metal KV to host after each decode step \
4704             (minimal spill; full layer offload still planned)"
4705        );
4706    }
4707
4708    let mcp = match mcp_config_path {
4709        Some(path) => {
4710            let loaded = mcp::load_mcp_config(&path)?;
4711            tracing::info!(
4712                "MCP config loaded from {} ({} server(s); invocation not wired yet)",
4713                loaded.path,
4714                loaded.servers.len()
4715            );
4716            Some(loaded)
4717        }
4718        None => None,
4719    };
4720
4721    // Started before the router is built so the probe overlaps with
4722    // binding the port: by the time a client can ask, it has usually
4723    // already landed.
4724    let detection = health::Detection::spawn();
4725
4726    let state = Arc::new(build_app_state(
4727        StartupModels {
4728            loaded,
4729            embedding: embedding_model,
4730        },
4731        kv_pool,
4732        paged_kv,
4733        prefix_cache,
4734        enable_cb,
4735        mcp,
4736        detection,
4737    ));
4738
4739    // Paths come from `frink_api::routes` rather than string literals
4740    // so the UI, `frink chat` and this router cannot disagree about
4741    // what the surface is.
4742    use frink_api::routes;
4743
4744    // Frink Studio is a separate app served by its own dev/static
4745    // server (see `ui/` at the repository root); it reaches this
4746    // process over the public HTTP API like any other client, so there
4747    // is nothing to mount here and `/` stays a 404.
4748    let public = Router::new().route(routes::HEALTH, get(health));
4749
4750    let mut protected = protected_routes();
4751
4752    // Both off by default; set the corresponding env var to enable.
4753    // route_layer (not layer) so these apply only to the routes above,
4754    // never to /health, which stays reachable for liveness/readiness
4755    // probes regardless of auth or rate-limit configuration.
4756    if let Ok(key) = std::env::var("FRINK_API_KEY") {
4757        tracing::info!("API key auth enabled");
4758        let auth = limits::AuthConfig {
4759            api_key: Arc::new(key),
4760        };
4761        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4762            auth,
4763            limits::require_api_key,
4764        ));
4765    }
4766    if let Ok(rpm) = std::env::var("FRINK_RATE_LIMIT_PER_MINUTE") {
4767        let rpm: u32 = rpm
4768            .parse()
4769            .expect("FRINK_RATE_LIMIT_PER_MINUTE must be a positive integer");
4770        tracing::info!("rate limiting enabled: {rpm} requests/minute (global)");
4771        let limiter = Arc::new(limits::RateLimiter::per_minute(rpm));
4772        protected = protected.route_layer(axum::middleware::from_fn_with_state(
4773            limiter,
4774            limits::rate_limit,
4775        ));
4776    }
4777    // Off by default; set FRINK_CORS_ORIGINS (comma-separated exact
4778    // origins) to enable. No wildcard support by design -- see
4779    // `security::parse_cors_origins`'s doc comment. Added last (so it's
4780    // the outermost route_layer, run before auth/rate-limiting): a CORS
4781    // preflight (OPTIONS) request carries no Authorization header and
4782    // is answered directly by `CorsLayer` itself, so it must not be
4783    // blocked by the auth/rate-limit layers underneath.
4784    if let Ok(spec) = std::env::var("FRINK_CORS_ORIGINS") {
4785        let origins = security::parse_cors_origins(&spec)
4786            .unwrap_or_else(|e| panic!("FRINK_CORS_ORIGINS: {e}"));
4787        tracing::info!(
4788            "CORS enabled: {} allow-listed origin(s) ({})",
4789            origins.len(),
4790            spec
4791        );
4792        let cors = tower_http::cors::CorsLayer::new()
4793            .allow_origin(tower_http::cors::AllowOrigin::list(origins))
4794            .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
4795            .allow_headers([
4796                axum::http::header::CONTENT_TYPE,
4797                axum::http::header::AUTHORIZATION,
4798                // The self-declared client label the monitor records
4799                // (see `attribution`). A custom header makes every
4800                // cross-origin call preflighted, so omitting it here
4801                // would not merely drop the label -- it would fail the
4802                // request outright.
4803                axum::http::HeaderName::from_static(attribution::CLIENT_HEADER),
4804                // Set by hand rather than by `EventSource`, because
4805                // this API needs POST and a bearer token. Same
4806                // consequence if it is missing.
4807                axum::http::HeaderName::from_static("last-event-id"),
4808            ]);
4809        protected = protected.route_layer(cors);
4810    }
4811
4812    // Outermost on purpose: every 503 this server can emit -- from a
4813    // handler, from `require_active`, or from the batch scheduler's
4814    // queue cap -- leaves with a `Retry-After` a client can act on.
4815    let app = public
4816        .merge(protected)
4817        .layer(axum::middleware::from_fn(limits::retry_after))
4818        .with_state(state);
4819
4820    // TLS is off by default -- set FRINK_TLS_CERT and FRINK_TLS_KEY
4821    // together to serve HTTPS instead of plain HTTP; unset (either or
4822    // both) preserves the original plain-HTTP behavior exactly. See
4823    // `security::tls_paths_from_env`'s doc comment for why this can't
4824    // be meaningfully unit-tested here.
4825    let tls_paths = security::tls_paths_from_env().unwrap_or_else(|e| panic!("{e}"));
4826    install_ring_crypto_provider();
4827    // Both arms bind first and read the address back off the socket
4828    // rather than trusting the requested one: with `--port 0` the
4829    // requested port is a lie by construction, and the ready line has
4830    // to carry what the kernel actually handed out.
4831    match tls_paths {
4832        Some(paths) => {
4833            let config =
4834                axum_server::tls_rustls::RustlsConfig::from_pem_file(&paths.cert, &paths.key)
4835                    .await
4836                    .map_err(|e| {
4837                        anyhow::anyhow!(
4838                            "failed to load TLS cert/key ({:?}, {:?}): {e}",
4839                            paths.cert,
4840                            paths.key
4841                        )
4842                    })?;
4843            let socket_addr: std::net::SocketAddr = addr
4844                .parse()
4845                .map_err(|e| anyhow::anyhow!("invalid FRINK_ADDR {addr:?} for TLS: {e}"))?;
4846            let listener = std::net::TcpListener::bind(socket_addr)?;
4847            // Tokio panics outright when handed a BLOCKING socket
4848            // ("Registering a blocking socket with the tokio runtime is
4849            // unsupported"), and axum-server registers this one
4850            // internally. Without this the TLS arm binds, prints its
4851            // ready line, and then panics on the first accept -- so the
4852            // failure looks like a healthy start followed by a server
4853            // that answers nothing.
4854            listener.set_nonblocking(true)?;
4855            let bound = listener.local_addr()?;
4856            tracing::info!("TLS enabled: frink-server listening on https://{bound}");
4857            announce_ready(bound, "https");
4858
4859            let handle = axum_server::Handle::new();
4860            let shutdown_handle = handle.clone();
4861            tokio::spawn(async move {
4862                shutdown_signal(exit_on_stdin_close).await;
4863                shutdown_handle.graceful_shutdown(Some(Duration::from_secs(5)));
4864            });
4865            axum_server::from_tcp_rustls(listener, config)?
4866                .handle(handle)
4867                .serve(app.into_make_service())
4868                .await?;
4869        }
4870        None => {
4871            let listener = tokio::net::TcpListener::bind(&addr).await?;
4872            let bound = listener.local_addr()?;
4873            tracing::info!("frink-server listening on {bound}");
4874            announce_ready(bound, "http");
4875            axum::serve(listener, app)
4876                .with_graceful_shutdown(shutdown_signal(exit_on_stdin_close))
4877                .await?;
4878        }
4879    }
4880    Ok(())
4881}
4882
4883#[cfg(test)]
4884pub(crate) mod tests {
4885    use super::*;
4886    use frink_models::config::test_dense_fixture;
4887
4888    #[test]
4889    fn the_ready_line_round_trips_through_a_parent_reading_stdout() {
4890        let addr: SocketAddr = "127.0.0.1:51999".parse().unwrap();
4891        let ready = frink_api::ServerReady::new(addr, "http", "0.5.0", std::process::id());
4892        let parsed = frink_api::ServerReady::from_line(&ready.to_line()).unwrap();
4893        assert_eq!(parsed.port, 51999);
4894        assert_eq!(parsed.base_url(), "http://127.0.0.1:51999");
4895        // A parent reads stdout line by line; tracing shares the stream.
4896        assert!(frink_api::ServerReady::from_line("INFO frink-server listening").is_none());
4897    }
4898
4899    fn test_model() -> Model {
4900        // Tiny vocab (32): raw byte ids ≥32 (e.g. ASCII "hello") are OOV.
4901        // HTTP/chat-template tests that need full ASCII use
4902        // `test_model_full_byte_vocab` instead.
4903        let cfg = test_dense_fixture();
4904        Model::Gguf(GgufModel {
4905            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 32)),
4906            tokenizer: Arc::new(ServerTokenizer::Byte),
4907            stop_tokens: StopTokens::default(),
4908            bos_id: None,
4909            is_synthetic: true,
4910            chat_template: chat_template::PromptTemplate::plain(),
4911        })
4912    }
4913
4914    fn greedy_params(max_tokens: usize) -> GenerationParams {
4915        GenerationParams {
4916            cache_salt: None,
4917            prompt_logprobs: None,
4918            wants_logprobs: false,
4919            n: 1,
4920            interleave_choices: false,
4921            keep_special_tokens: false,
4922            truncate_prompt_tokens: None,
4923            token_mask: crate::token_mask::TokenMask::default(),
4924            reasoning: None,
4925            max_tokens,
4926            sampling: SamplingParams::default(),
4927            seed: 1,
4928            stop: Vec::new(),
4929            stop_token_ids: Vec::new(),
4930            json_object: false,
4931            grammar: None,
4932            cancel: None,
4933            ignore_eos: false,
4934            reasoning_budget: crate::reasoning_budget::ReasoningBudget::Unrestricted,
4935            lora: None,
4936        }
4937    }
4938
4939    /// Declares a full 0..255 byte-compatible vocab so HTTP-level tests
4940    /// that render chat templates (ASCII role names) do not spuriously
4941    /// reject their own prompt prefixes.
4942    fn test_model_full_byte_vocab() -> Model {
4943        test_model_full_byte_vocab_with_eos(None)
4944    }
4945
4946    /// [`test_model_full_byte_vocab`] with an end-of-generation id, so a
4947    /// test can tell a turn the MODEL ended from one that merely ran out
4948    /// of budget -- which is the only way `ignore_eos` is observable.
4949    ///
4950    /// Parameterised rather than copied: a second `Model` literal here
4951    /// is one more place a field has to be remembered.
4952    fn test_model_full_byte_vocab_with_eos(eos: Option<usize>) -> Model {
4953        test_byte_model(eos, /* synthetic = */ true)
4954    }
4955
4956    /// The byte-vocabulary fixture, with the two things that vary.
4957    ///
4958    /// `synthetic` replaces the returned TEXT with a banner, which is
4959    /// right for tests about plumbing and wrong for any test that
4960    /// reads the answer. `eos` is what lets a turn the MODEL ended be
4961    /// told from one that ran out of budget.
4962    fn test_byte_model(eos: Option<usize>, synthetic: bool) -> Model {
4963        let mut cfg = test_dense_fixture();
4964        cfg.vocab_size = 256;
4965        Model::Gguf(GgufModel {
4966            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
4967            tokenizer: Arc::new(ServerTokenizer::Byte),
4968            stop_tokens: StopTokens::from_eos(eos),
4969            bos_id: None,
4970            is_synthetic: synthetic,
4971            chat_template: chat_template::PromptTemplate::plain(),
4972        })
4973    }
4974
4975    /// One `AppState` for the HTTP-level tests, so a new field on the
4976    /// struct is added in one place rather than in every test that
4977    /// builds one.
4978    pub(crate) fn test_state(model: Model, response_cache: ResponseCache) -> AppState {
4979        test_state_at(model, response_cache, None)
4980    }
4981
4982    /// [`test_state`] with a checkpoint path on record, which is what
4983    /// makes a model SLEEPABLE: `/sleep` refuses one it could not
4984    /// bring back, and the plain fixture is deliberately that case.
4985    pub(crate) fn test_state_at(
4986        model: Model,
4987        response_cache: ResponseCache,
4988        checkpoint_path: Option<std::path::PathBuf>,
4989    ) -> AppState {
4990        AppState {
4991            slept: Mutex::new(None),
4992            embedding: None,
4993            paged_kv: None,
4994            active: std::sync::RwLock::new(Some(Arc::new(ActiveModel {
4995                id: None,
4996                loaded: Loaded::Generative(Arc::new(model)),
4997                batcher: None,
4998                ceiling: None,
4999                checkpoint_path,
5000            }))),
5001            load_in_progress: std::sync::atomic::AtomicBool::new(false),
5002            tasks: Arc::new(tasks::TaskRegistry::new()),
5003            cancels: Arc::new(cancel::CancelRegistry::new()),
5004            stats: stats::Stats::new(),
5005            streams: resume::StreamRegistry::new(),
5006            model_dir: None,
5007            response_cache: Mutex::new(response_cache),
5008            kv_pool: None,
5009            prefix_cache: None,
5010            sessions: session::SessionStore::new(),
5011            requests_total: std::sync::atomic::AtomicU64::new(0),
5012            request_errors_total: std::sync::atomic::AtomicU64::new(0),
5013            started_at: std::time::Instant::now(),
5014            last_request_ms: std::sync::atomic::AtomicU64::new(0),
5015            detection: Arc::new(health::Detection::ready(health::probe_backends())),
5016            mcp: None,
5017            continuous_batching_enabled: false,
5018            metal_private_decode_gate: None,
5019            loading_model: Mutex::new(None),
5020            last_load_error: Mutex::new(None),
5021            serving: Mutex::new(crate::stats::ServingStats::default()),
5022            maintenance: Mutex::new(crate::policy::maintenance::MaintenanceGate::serving()),
5023            footprint: Mutex::new(crate::policy::footprint::ProbeCache::new(FOOTPRINT_TTL_MS)),
5024            started_unix: unix_now(),
5025        }
5026    }
5027
5028    /// A real axum `Router` wired exactly like `main()`'s (minus auth/
5029    /// rate-limiting, which are orthogonal and already covered by
5030    /// `limits`'s own tests), backed by a fresh
5031    /// `test_model_full_byte_vocab()` -- so tool-calling/session tests
5032    /// exercise the real HTTP request/response path (JSON
5033    /// (de)serialization, routing, handler wiring, chat-template
5034    /// rendering) via `tower::ServiceExt::oneshot`, not just the inner
5035    /// functions directly.
5036    pub(crate) fn test_app() -> Router {
5037        test_app_with_state(Arc::new(test_state(
5038            test_model_full_byte_vocab(),
5039            ResponseCache::new(1000, Duration::from_secs(3600)),
5040        )))
5041    }
5042
5043    /// [`test_app`] over a caller-owned state, so a test can reach in
5044    /// and swap or unload the model behind a live router.
5045    pub(crate) fn test_app_with_state(state: Arc<AppState>) -> Router {
5046        // The SAME route list the server builds, not a hand-written
5047        // copy of it. The copy that used to live here had drifted from
5048        // the real one, which is the failure mode that makes an HTTP
5049        // test worthless: it can only ever confirm that the tests agree
5050        // with the tests. See `protected_routes`.
5051        //
5052        // No auth, rate-limit or CORS layer: those are configured from
5053        // the environment in `run`, and a test that set the environment
5054        // would race every other test in the process.
5055        Router::new()
5056            .route(frink_api::routes::HEALTH, get(health))
5057            .merge(protected_routes())
5058            .with_state(state)
5059    }
5060
5061    fn named_test_model(name: &'static str, vocab_size: usize) -> Model {
5062        let mut cfg = test_dense_fixture();
5063        cfg.name = name;
5064        cfg.vocab_size = vocab_size;
5065        Model::Gguf(GgufModel {
5066            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5067            tokenizer: Arc::new(ServerTokenizer::Byte),
5068            stop_tokens: StopTokens::default(),
5069            bos_id: None,
5070            is_synthetic: true,
5071            chat_template: chat_template::PromptTemplate::plain(),
5072        })
5073    }
5074
5075    /// The same model, served through a real checkpoint's template
5076    /// rather than the role-labeled builtin -- so a test can ask what
5077    /// gets advertised for a checkpoint that actually has gears.
5078    fn model_with_template(name: &'static str, source: &str) -> Model {
5079        let mut cfg = test_dense_fixture();
5080        cfg.name = name;
5081        cfg.vocab_size = 256;
5082        Model::Gguf(GgufModel {
5083            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5084            tokenizer: Arc::new(ServerTokenizer::Byte),
5085            stop_tokens: StopTokens::default(),
5086            bos_id: None,
5087            is_synthetic: true,
5088            chat_template: chat_template::PromptTemplate::from_gguf_metadata(
5089                Some(source),
5090                Some("qwen3"),
5091                false,
5092                true,
5093                None,
5094                None,
5095            ),
5096        })
5097    }
5098
5099    /// Once a `200` and `text/event-stream` are on the wire, a
5100    /// rejection can only ride *in* the stream, where several agents
5101    /// render it as an empty response. So the prompt is rendered before
5102    /// the stream is committed, and a template that rejects this
5103    /// particular conversation is an ordinary 400 with a body.
5104    ///
5105    /// Fails if `prompt_from_messages` moves back inside the spawned
5106    /// generation task.
5107    #[tokio::test]
5108    async fn a_template_that_rejects_the_conversation_is_a_400_on_the_streaming_path() {
5109        // Raises on a second user turn, the way a real strict template
5110        // rejects an ordering it was never trained on.
5111        let strict = "{% if messages | length > 1 %}\
5112             {{ raise_exception('this template takes one turn') }}\
5113             {% endif %}{{ messages[0].content }}";
5114        let state = Arc::new(test_state(
5115            model_with_template("strict", strict),
5116            ResponseCache::new(4, Duration::from_secs(60)),
5117        ));
5118        let app = test_app_with_state(state);
5119
5120        let (status, body) = post_json_uri(
5121            &app,
5122            "/v1/chat/completions",
5123            serde_json::json!({
5124                "model": "strict",
5125                "stream": true,
5126                "messages": [
5127                    {"role": "user", "content": "one"},
5128                    {"role": "user", "content": "two"},
5129                ],
5130            }),
5131        )
5132        .await;
5133        assert_eq!(status, StatusCode::BAD_REQUEST);
5134        assert_eq!(body["error"]["param"], serde_json::json!("messages"));
5135        assert!(
5136            body["error"]["message"]
5137                .as_str()
5138                .unwrap()
5139                .contains("one turn"),
5140            "the template's own message must reach the caller: {body}"
5141        );
5142
5143        // And the same template serves a conversation it accepts.
5144        let (status, _) = post_json_uri(
5145            &app,
5146            "/v1/chat/completions",
5147            serde_json::json!({
5148                "model": "strict",
5149                "stream": true,
5150                "max_tokens": 1,
5151                "messages": [{"role": "user", "content": "one"}],
5152            }),
5153        )
5154        .await;
5155        assert_eq!(status, StatusCode::OK);
5156    }
5157
5158    /// A client should not have to guess which gears a checkpoint has.
5159    #[tokio::test]
5160    async fn models_advertises_the_gears_this_checkpoint_actually_has() {
5161        let reasoning = "{% if enable_thinking %}<think>{% endif %}\
5162             {% if reasoning_effort %}\
5163               {% if reasoning_effort not in ['low','medium','high'] %}\
5164                 {{ raise_exception('bad effort') }}\
5165               {% endif %}[{{ reasoning_effort }}]\
5166             {% endif %}{{ messages[0].content }}";
5167        let state = Arc::new(test_state(
5168            model_with_template("thinker", reasoning),
5169            ResponseCache::new(4, Duration::from_secs(60)),
5170        ));
5171        let app = test_app_with_state(state);
5172        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5173        assert_eq!(status, StatusCode::OK);
5174        let entry = &models["data"][0];
5175        assert_eq!(
5176            entry["supported_reasoning_efforts"],
5177            serde_json::json!(["off", "low", "medium", "high"])
5178        );
5179        assert_eq!(entry["default_reasoning_effort"], serde_json::json!("off"));
5180    }
5181
5182    /// The other half of the acceptance criterion: neither field, not
5183    /// an empty one. An empty list would say the question was asked and
5184    /// the answer was "no gears"; absence says it is not that kind of
5185    /// model.
5186    #[tokio::test]
5187    async fn a_checkpoint_with_no_thinking_controls_advertises_neither_field() {
5188        let app = test_app();
5189        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5190        let entry = &models["data"][0];
5191        assert!(entry.get("supported_reasoning_efforts").is_none());
5192        assert!(entry.get("default_reasoning_effort").is_none());
5193    }
5194
5195    fn active_model(state: &AppState, name: &'static str) -> Arc<ActiveModel> {
5196        Arc::new(ActiveModel {
5197            id: Some(name.to_string()),
5198            loaded: Loaded::Generative(Arc::new(named_test_model(name, 256))),
5199            batcher: None,
5200            ceiling: None,
5201            checkpoint_path: None,
5202        })
5203        .tap_into(state)
5204    }
5205
5206    /// Small helper so the swap tests read as "publish this model".
5207    trait TapInto {
5208        fn tap_into(self, state: &AppState) -> Self;
5209    }
5210    impl TapInto for Arc<ActiveModel> {
5211        fn tap_into(self, state: &AppState) -> Self {
5212            state.swap_active(Some(Arc::clone(&self)));
5213            self
5214        }
5215    }
5216
5217    /// The load-order guarantee the whole swap design exists to make:
5218    /// a request that has already taken its handle finishes against the
5219    /// weights it started on, even though a different model has since
5220    /// been published. Anything else would splice two checkpoints into
5221    /// one completion.
5222    #[test]
5223    fn an_in_flight_request_keeps_the_model_it_started_on() {
5224        let state = test_state(
5225            named_test_model("model-a", 256),
5226            ResponseCache::new(4, Duration::from_secs(60)),
5227        );
5228
5229        // A request that has begun: it has cloned the handle and is
5230        // about to decode against it.
5231        let in_flight = state.active().expect("a model is loaded");
5232        assert_eq!(in_flight.name(), "model-a");
5233
5234        active_model(&state, "model-b");
5235
5236        // The swap is visible to anything that asks *now*...
5237        assert_eq!(state.active().unwrap().name(), "model-b");
5238        // ...and completely invisible to the request already running.
5239        assert_eq!(in_flight.name(), "model-a");
5240        let produced = run_generation(
5241            in_flight.generative().unwrap(),
5242            "hi",
5243            &greedy_params(3),
5244            None,
5245            None,
5246            None,
5247            None,
5248            None,
5249            None,
5250        )
5251        .expect("the old model must still decode after being swapped out");
5252        assert!(matches!(
5253            produced.choices[0].finish,
5254            FinishReason::Length | FinishReason::Stop
5255        ));
5256    }
5257
5258    /// The other half of the same guarantee: the old model is not freed
5259    /// at swap time, it is freed when the last holder lets go. A design
5260    /// that dropped it eagerly would free weights out from under a
5261    /// decode loop.
5262    #[test]
5263    fn a_swapped_out_model_lives_until_its_last_holder_releases_it() {
5264        let state = test_state(
5265            named_test_model("model-a", 256),
5266            ResponseCache::new(4, Duration::from_secs(60)),
5267        );
5268        let in_flight = state.active().expect("a model is loaded");
5269        let weights = Arc::clone(in_flight.generative().unwrap());
5270        assert!(Arc::strong_count(&weights) >= 2);
5271
5272        let previous = state.swap_active(Some(Arc::new(ActiveModel {
5273            id: Some("model-b".to_string()),
5274            loaded: Loaded::Generative(Arc::new(named_test_model("model-b", 256))),
5275            batcher: None,
5276            ceiling: None,
5277            checkpoint_path: None,
5278        })));
5279        drop(previous);
5280        // The registry has let go; the in-flight request has not.
5281        assert!(Arc::strong_count(&weights) >= 2);
5282        drop(in_flight);
5283        assert_eq!(Arc::strong_count(&weights), 1);
5284    }
5285
5286    /// Unload is not "keep serving the last thing loaded". A request
5287    /// that arrives afterwards must be told there is no model, not
5288    /// quietly served by a checkpoint the operator dropped.
5289    #[tokio::test]
5290    async fn unloading_answers_503_instead_of_serving_the_dropped_model() {
5291        let state = Arc::new(test_state(
5292            named_test_model("model-a", 256),
5293            ResponseCache::new(4, Duration::from_secs(60)),
5294        ));
5295        let app = test_app_with_state(Arc::clone(&state));
5296
5297        let (status, body) = post_json_uri(
5298            &app,
5299            frink_api::routes::ADMIN_MODELS_UNLOAD,
5300            serde_json::json!({}),
5301        )
5302        .await;
5303        assert_eq!(status, StatusCode::OK);
5304        assert_eq!(body["ok"], true);
5305        assert!(body["active"].is_null());
5306        assert!(state.active().is_none());
5307
5308        let (status, _) = get_json(&app, frink_api::routes::V1_MODELS).await;
5309        assert_eq!(status, StatusCode::OK);
5310        let (_, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
5311        assert_eq!(models["data"].as_array().unwrap().len(), 0);
5312
5313        let (status, body) = post_json_uri(
5314            &app,
5315            "/v1/chat/completions",
5316            serde_json::json!({
5317                "model": "x",
5318                "messages": [{"role": "user", "content": "hi"}]
5319            }),
5320        )
5321        .await;
5322        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5323        assert_eq!(body["error"]["type"], "model_not_loaded");
5324    }
5325
5326    /// `/health` must keep answering with nothing loaded -- a supervisor
5327    /// polls it to decide whether to kill the process, and "no model"
5328    /// is not "no server".
5329    #[tokio::test]
5330    async fn health_reports_the_unloaded_state_rather_than_going_silent() {
5331        let state = Arc::new(test_state(
5332            named_test_model("model-a", 256),
5333            ResponseCache::new(4, Duration::from_secs(60)),
5334        ));
5335        let app = test_app_with_state(Arc::clone(&state));
5336        state.swap_active(None);
5337
5338        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
5339        // Not `ready`: a supervisor reading 200 here would route traffic
5340        // that is guaranteed to 503 on arrival.
5341        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5342        assert_eq!(body["state"], "unavailable");
5343        assert_eq!(body["reason"], "model_not_loaded");
5344        assert!(body["model"].is_null());
5345        let real_weights = body["capabilities"]
5346            .as_array()
5347            .unwrap()
5348            .iter()
5349            .find(|c| c["id"] == "real_weights")
5350            .cloned()
5351            .expect("real_weights is always reported");
5352        assert_eq!(real_weights["available"], false);
5353        assert_eq!(real_weights["reason"], "model_not_loaded");
5354    }
5355
5356    /// The API-monitor contract: a finished request lands in the ring
5357    /// buffer keyed by the id the response carried, with the two
5358    /// durations reported separately.
5359    #[tokio::test]
5360    async fn a_finished_request_lands_in_the_stats_ring_with_both_durations() {
5361        let app = test_app();
5362
5363        let (status, completion) = post_json_uri(
5364            &app,
5365            "/v1/chat/completions",
5366            serde_json::json!({
5367                "model": "x",
5368                "messages": [{"role": "user", "content": "hi"}],
5369                "max_tokens": 4
5370            }),
5371        )
5372        .await;
5373        assert_eq!(status, StatusCode::OK);
5374        let request_id = completion["request_id"].as_str().unwrap().to_string();
5375
5376        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5377        assert_eq!(status, StatusCode::OK);
5378        let recent = stats["recent"].as_array().unwrap();
5379        assert_eq!(recent.len(), 1);
5380        let row = &recent[0];
5381        assert_eq!(row["request_id"], request_id);
5382        assert_eq!(row["route"], frink_api::routes::V1_CHAT_COMPLETIONS);
5383        assert_eq!(row["status"], 200);
5384        assert_eq!(row["stream"], false);
5385        // Separate fields, and the decode phase is a real measurement
5386        // rather than a copy of the total.
5387        assert!(row["duration_ms"].is_number());
5388        assert!(row["decode_ms"].is_number());
5389        assert!(stats["tokens_generated_total"].as_u64().unwrap() > 0);
5390        assert_eq!(
5391            stats["tokens_prompt_total"].as_u64().unwrap(),
5392            row["prompt_tokens"].as_u64().unwrap()
5393        );
5394    }
5395
5396    /// A rejected request is still a request the monitor should show;
5397    /// otherwise the screen quietly omits exactly the traffic someone
5398    /// is debugging.
5399    #[tokio::test]
5400    async fn a_rejected_request_is_recorded_too() {
5401        let state = Arc::new(test_state(
5402            named_test_model("model-a", 256),
5403            ResponseCache::new(4, Duration::from_secs(60)),
5404        ));
5405        let app = test_app_with_state(Arc::clone(&state));
5406        state.swap_active(None);
5407
5408        let (status, _) = post_json_uri(
5409            &app,
5410            "/v1/chat/completions",
5411            serde_json::json!({"model": "x", "messages": [{"role": "user", "content": "hi"}]}),
5412        )
5413        .await;
5414        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
5415
5416        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5417        let recent = stats["recent"].as_array().unwrap();
5418        assert_eq!(recent.len(), 1);
5419        assert_eq!(recent[0]["status"], 503);
5420        assert_eq!(recent[0]["completion_tokens"], 0);
5421        assert!(recent[0]["decode_ms"].is_null());
5422        assert_eq!(stats["errors_total"], 1);
5423    }
5424
5425    /// POSTs with caller-supplied headers, so the attribution tests
5426    /// exercise the same header parsing a real client's request goes
5427    /// through rather than calling `Attribution::from_headers` twice.
5428    async fn post_json_with_headers(
5429        app: &Router,
5430        uri: &str,
5431        body: serde_json::Value,
5432        headers: &[(&str, &str)],
5433    ) -> (StatusCode, serde_json::Value) {
5434        use http_body_util::BodyExt;
5435        use tower::ServiceExt;
5436
5437        let mut builder = axum::http::Request::builder()
5438            .method("POST")
5439            .uri(uri)
5440            .header("content-type", "application/json");
5441        for (name, value) in headers {
5442            builder = builder.header(*name, *value);
5443        }
5444        let response = app
5445            .clone()
5446            .oneshot(
5447                builder
5448                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
5449                    .unwrap(),
5450            )
5451            .await
5452            .unwrap();
5453        let status = response.status();
5454        let bytes = response.into_body().collect().await.unwrap().to_bytes();
5455        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
5456        (status, json)
5457    }
5458
5459    /// The three small endpoints used to be served and never recorded,
5460    /// which made the monitor wrong rather than incomplete: an editor
5461    /// hammering `/v1/embeddings` showed up as an idle server.
5462    #[tokio::test]
5463    async fn tokenize_detokenize_and_embeddings_all_land_in_the_ring() {
5464        let app = test_app();
5465
5466        let (status, _) = post_json_uri(
5467            &app,
5468            frink_api::routes::V1_TOKENIZE,
5469            serde_json::json!({"prompt": "hello"}),
5470        )
5471        .await;
5472        assert_eq!(status, StatusCode::OK);
5473        let (status, _) = post_json_uri(
5474            &app,
5475            frink_api::routes::V1_DETOKENIZE,
5476            serde_json::json!({"tokens": [104, 105]}),
5477        )
5478        .await;
5479        assert_eq!(status, StatusCode::OK);
5480        let (status, _) = post_json_uri(
5481            &app,
5482            frink_api::routes::V1_EMBEDDINGS,
5483            serde_json::json!({"input": "hello"}),
5484        )
5485        .await;
5486        assert_eq!(status, StatusCode::OK);
5487
5488        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
5489        let routes: Vec<&str> = stats["recent"]
5490            .as_array()
5491            .unwrap()
5492            .iter()
5493            .map(|row| row["route"].as_str().unwrap())
5494            .collect();
5495        for expected in [
5496            frink_api::routes::V1_TOKENIZE,
5497            frink_api::routes::V1_DETOKENIZE,
5498            frink_api::routes::V1_EMBEDDINGS,
5499        ] {
5500            assert!(
5501                routes.contains(&expected),
5502                "{expected} is missing: {routes:?}"
5503            );
5504        }
5505
5506        let row = |route: &str| {
5507            stats["recent"]
5508                .as_array()
5509                .unwrap()
5510                .iter()
5511                .find(|r| r["route"] == route)
5512                .cloned()
5513                .unwrap()
5514        };
5515        // Embeddings run a forward pass, so their prompt tokens are
5516        // real prompt tokens. There is no decode loop, so `decode_ms`
5517        // stays null instead of borrowing the total.
5518        let embed = row(frink_api::routes::V1_EMBEDDINGS);
5519        assert!(embed["prompt_tokens"].as_u64().unwrap() > 0);
5520        assert!(embed["decode_ms"].is_null());
5521        assert_eq!(embed["completion_tokens"], 0);
5522        // Tokenizing runs the tokenizer and not the model, so it
5523        // contributes nothing to the token counters those counters
5524        // claim to measure.
5525        assert_eq!(row(frink_api::routes::V1_TOKENIZE)["prompt_tokens"], 0);
5526        assert_eq!(
5527            stats["tokens_prompt_total"].as_u64().unwrap(),
5528            embed["prompt_tokens"].as_u64().unwrap(),
5529            "only the forward pass counted"
5530        );
5531    }
5532
5533    /// A router over a model that is NOT flagged synthetic, so the
5534    /// decode loop actually emits chunks: `run_generation_emit`
5535    /// suppresses `emit` for a synthetic model, and a streaming test
5536    /// against one would see only the terminal frame.
5537    fn streaming_test_app() -> Router {
5538        let mut cfg = test_dense_fixture();
5539        cfg.vocab_size = 256;
5540        let model = Model::Gguf(GgufModel {
5541            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
5542            tokenizer: Arc::new(ServerTokenizer::Byte),
5543            stop_tokens: StopTokens::default(),
5544            bos_id: None,
5545            is_synthetic: false,
5546            chat_template: chat_template::PromptTemplate::plain(),
5547        });
5548        test_app_with_state(Arc::new(test_state(
5549            model,
5550            ResponseCache::new(1000, Duration::from_secs(3600)),
5551        )))
5552    }
5553
5554    /// llama.cpp's native endpoint is a different WIRE, not a shorter
5555    /// path to the OpenAI one. If this ever starts answering `choices`,
5556    /// every llama.cpp client reading `content` breaks silently.
5557    /// Chat logprobs: the CHAT shape (`content[]` with `token`,
5558    /// `logprob`, `bytes` and a nested `top_logprobs`), not the
5559    /// completions wire's parallel arrays, and a request that asks for
5560    /// them must MISS the response cache -- which stores text and
5561    /// finish reasons, never distributions.
5562    #[tokio::test]
5563    async fn chat_logprobs_are_rendered_and_are_never_served_from_cache() {
5564        let app = test_app();
5565        let body = |logprobs: Option<(bool, Option<u32>)>| {
5566            let mut b = serde_json::json!({
5567                "model": "x",
5568                "messages": [{"role": "user", "content": "hi"}],
5569                "max_tokens": 4
5570            });
5571            if let Some((on, top)) = logprobs {
5572                b["logprobs"] = serde_json::json!(on);
5573                if let Some(n) = top {
5574                    b["top_logprobs"] = serde_json::json!(n);
5575                }
5576            }
5577            b
5578        };
5579
5580        // Without: absent, not an empty object.
5581        let (status, plain) =
5582            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(None)).await;
5583        assert_eq!(status, StatusCode::OK, "{plain}");
5584        assert!(plain["choices"][0]["logprobs"].is_null(), "{plain}");
5585
5586        // With: the chat object, and never a cache hit -- twice in a
5587        // row, because the second is exactly when a cacheable request
5588        // would replay.
5589        for attempt in 0..2 {
5590            let (status, with) = post_json_uri(
5591                &app,
5592                frink_api::routes::V1_CHAT_COMPLETIONS,
5593                body(Some((true, Some(2)))),
5594            )
5595            .await;
5596            assert_eq!(status, StatusCode::OK, "{with}");
5597            assert_ne!(
5598                with["frink_cache"], "hit",
5599                "attempt {attempt} replayed a cached answer for a logprobs request: {with}"
5600            );
5601            let lp = &with["choices"][0]["logprobs"];
5602            assert!(lp.is_object(), "attempt {attempt}: {with}");
5603            let content = lp["content"].as_array().expect("content");
5604            // It is the CHAT shape, so there are no parallel arrays.
5605            assert!(lp["tokens"].is_null(), "completions shape leaked: {lp}");
5606            for entry in content {
5607                assert!(entry["token"].is_string(), "{entry}");
5608                assert!(entry["bytes"].is_array(), "{entry}");
5609                let v = entry["logprob"].as_f64().expect("a real number");
5610                assert!(v <= 0.0 && v.is_finite(), "{entry}");
5611                let top = entry["top_logprobs"].as_array().expect("top_logprobs");
5612                assert!(top.len() <= 2, "asked for 2, got {}", top.len());
5613            }
5614        }
5615    }
5616
5617    /// `top_logprobs` without `logprobs: true` is not a valid request
5618    /// upstream, and is refused here rather than read as an implied
5619    /// `true` -- guessing which of two fields the caller meant is how
5620    /// a server answers a question nobody asked. A count above the cap
5621    /// is a 400 on the VALUE, not a 501 on the field.
5622    #[tokio::test]
5623    async fn the_chat_logprobs_pair_is_validated() {
5624        let app = test_app();
5625        for (extra, why) in [
5626            (serde_json::json!({"top_logprobs": 3}), "without logprobs"),
5627            (
5628                serde_json::json!({"logprobs": true, "top_logprobs": 21}),
5629                "above the cap",
5630            ),
5631        ] {
5632            let mut body = serde_json::json!({
5633                "model": "x",
5634                "messages": [{"role": "user", "content": "hi"}],
5635                "max_tokens": 2
5636            });
5637            for (k, v) in extra.as_object().unwrap() {
5638                body[k] = v.clone();
5639            }
5640            let (status, answer) =
5641                post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await;
5642            assert_eq!(status, StatusCode::BAD_REQUEST, "{why}: {answer}");
5643            assert!(
5644                answer["error"]["message"]
5645                    .as_str()
5646                    .is_some_and(|m| m.contains("top_logprobs")),
5647                "{why}: {answer}"
5648            );
5649        }
5650    }
5651
5652    /// **Sleep refuses a model it could not bring back.**
5653    ///
5654    /// A checkpoint with no path on record -- the synthetic fixture,
5655    /// and any model loaded from something this server cannot replay
5656    /// -- would be a one-way door dressed as a round trip. Refusing is
5657    /// the honest answer, and the test server is exactly that case,
5658    /// which is why the state machine below is driven over a state
5659    /// carrying a path instead.
5660    #[tokio::test]
5661    async fn sleep_refuses_a_model_it_could_not_bring_back() {
5662        let app = test_app();
5663        let (status, answer) =
5664            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5665        assert_eq!(status, StatusCode::CONFLICT, "{answer}");
5666        assert_eq!(answer["error"]["type"], "not_reloadable", "{answer}");
5667        // And it stays awake: a refused sleep must not leave the server
5668        // in a state where nothing is loaded.
5669        let (_, still) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5670        assert_eq!(still["is_sleeping"], false, "{still}");
5671        let (status, _) = post_json_uri(
5672            &app,
5673            frink_api::routes::V1_CHAT_COMPLETIONS,
5674            serde_json::json!({
5675                "model": "x",
5676                "messages": [{"role": "user", "content": "hi"}],
5677                "max_tokens": 2
5678            }),
5679        )
5680        .await;
5681        assert_eq!(status, StatusCode::OK, "a refused sleep unloaded the model");
5682    }
5683
5684    /// **Sleep is an unload that REMEMBERS**, and that is the whole
5685    /// difference from `/admin/models/unload`: a slept server can wake
5686    /// itself, where an unloaded one needs a client that knows the id.
5687    ///
5688    /// The state a caller can observe is pinned end to end: asleep is
5689    /// reported by `GET /is_sleeping`, a generation refused while
5690    /// asleep says so with its own error `type` rather than
5691    /// `model_not_loaded`, and sleeping twice is not an error.
5692    #[tokio::test]
5693    async fn sleep_remembers_what_unload_forgets() {
5694        // A path on record is what makes a model sleepable; the plain
5695        // fixture has none and `sleep` refuses that case above.
5696        let state = Arc::new(test_state_at(
5697            test_model_full_byte_vocab(),
5698            ResponseCache::new(1000, Duration::from_secs(3600)),
5699            Some(std::path::PathBuf::from("/nonexistent/fixture.gguf")),
5700        ));
5701        let app = test_app_with_state(Arc::clone(&state));
5702        let ask = || {
5703            let app = app.clone();
5704            async move {
5705                post_json_uri(
5706                    &app,
5707                    frink_api::routes::V1_CHAT_COMPLETIONS,
5708                    serde_json::json!({
5709                        "model": "x",
5710                        "messages": [{"role": "user", "content": "hi"}],
5711                        "max_tokens": 2
5712                    }),
5713                )
5714                .await
5715            }
5716        };
5717
5718        let (status, _) = ask().await;
5719        assert_eq!(status, StatusCode::OK, "the fixture server serves");
5720        let (_, awake) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5721        assert_eq!(awake["is_sleeping"], false, "{awake}");
5722
5723        let (status, slept) =
5724            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5725        assert_eq!(status, StatusCode::OK, "{slept}");
5726        assert_eq!(slept["is_sleeping"], true, "{slept}");
5727        let (_, now) = get_json_uri(&app, frink_api::routes::IS_SLEEPING).await;
5728        assert_eq!(now["is_sleeping"], true, "{now}");
5729
5730        // A generation while asleep names the state, so a client can
5731        // tell "wake me" from "load something".
5732        let (status, refused) = ask().await;
5733        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{refused}");
5734        assert_eq!(
5735            refused["error"]["type"], "server_sleeping",
5736            "an asleep server reported itself as empty: {refused}"
5737        );
5738
5739        // Sleeping twice is not an error and must not lose the record.
5740        let (status, again) =
5741            post_json_uri(&app, frink_api::routes::SLEEP, serde_json::json!({})).await;
5742        assert_eq!(status, StatusCode::OK, "{again}");
5743        assert_eq!(again["is_sleeping"], true, "{again}");
5744    }
5745
5746    /// Waking a server that is not asleep is a conflict rather than a
5747    /// silent no-op: a scheduler that lost track of the state should
5748    /// find out, not be told everything is fine.
5749    #[tokio::test]
5750    async fn waking_a_server_that_is_awake_is_refused() {
5751        let app = test_app();
5752        let (status, answer) =
5753            post_json_uri(&app, frink_api::routes::WAKE_UP, serde_json::json!({})).await;
5754        assert_eq!(status, StatusCode::CONFLICT, "{answer}");
5755        assert_eq!(answer["error"]["type"], "not_sleeping", "{answer}");
5756    }
5757
5758    /// **`cache_salt` isolates one caller's cached prefixes from
5759    /// another's**, end to end: two requests with the same prompt and
5760    /// different salts must not be served each other's answer.
5761    ///
5762    /// The response cache is the visible half -- a hit is reported in
5763    /// `frink_cache`, so a leak is observable from the wire.
5764    #[tokio::test]
5765    async fn a_salt_keeps_one_callers_cached_answer_from_another() {
5766        let app = test_app();
5767        let body = |salt: Option<&str>| {
5768            let mut b = serde_json::json!({
5769                "model": "x",
5770                "messages": [{"role": "user", "content": "the same prompt"}],
5771                "max_tokens": 4,
5772                "seed": 1
5773            });
5774            if let Some(s) = salt {
5775                b["cache_salt"] = serde_json::json!(s);
5776            }
5777            b
5778        };
5779        let post = |b: serde_json::Value| {
5780            let app = app.clone();
5781            async move { post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, b).await }
5782        };
5783
5784        // Caller A warms the cache, then hits it.
5785        let (status, _) = post(body(Some("tenant-a"))).await;
5786        assert_eq!(status, StatusCode::OK);
5787        let (_, again) = post(body(Some("tenant-a"))).await;
5788        assert_eq!(
5789            again["frink_cache"], "hit",
5790            "the owner did not get its own entry back: {again}"
5791        );
5792
5793        // Caller B, same prompt, must NOT.
5794        let (_, other) = post(body(Some("tenant-b"))).await;
5795        assert_ne!(
5796            other["frink_cache"], "hit",
5797            "a different caller was served tenant-a's answer: {other}"
5798        );
5799
5800        // And the shared namespace is its own too.
5801        let (_, shared) = post(body(None)).await;
5802        assert_ne!(
5803            shared["frink_cache"], "hit",
5804            "an unsalted request was served a salted answer: {shared}"
5805        );
5806    }
5807
5808    /// `n` on the chat route: several choices from one prefill, each
5809    /// parsed for tool calls and reasoning in its own right.
5810    #[tokio::test]
5811    async fn chat_serves_several_choices_from_one_prefill() {
5812        let app = test_app();
5813        let body = |n: u32, stream: bool| {
5814            serde_json::json!({
5815                "model": "x",
5816                "messages": [{"role": "user", "content": "hi"}],
5817                "max_tokens": 4,
5818                "temperature": 1.0,
5819                "n": n,
5820                "stream": stream
5821            })
5822        };
5823
5824        let (status, one) =
5825            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(1, false)).await;
5826        assert_eq!(status, StatusCode::OK, "{one}");
5827
5828        let (status, three) =
5829            post_json_uri(&app, frink_api::routes::V1_CHAT_COMPLETIONS, body(3, false)).await;
5830        assert_eq!(status, StatusCode::OK, "{three}");
5831        let choices = three["choices"].as_array().expect("an array");
5832        assert_eq!(choices.len(), 3, "{three}");
5833        for (i, c) in choices.iter().enumerate() {
5834            assert_eq!(c["index"], i);
5835            assert!(c["message"]["role"].is_string(), "{c}");
5836            assert!(c["finish_reason"].is_string(), "{c}");
5837        }
5838        // One prompt, billed once: the prefill was shared.
5839        assert_eq!(
5840            three["usage"]["prompt_tokens"], one["usage"]["prompt_tokens"],
5841            "n = 3 billed the prompt more than once"
5842        );
5843    }
5844
5845    /// **A streamed `n` INTERLEAVES its choices.**
5846    ///
5847    /// The property the route refused for, and the only one that says
5848    /// the schedule is right: a client reading `choices[].index` is
5849    /// handed the choices together. Emitting choice 0 to its end and
5850    /// then choice 1 would satisfy "three indices appear" and satisfy
5851    /// nothing else, so what is asserted is that the FIRST chunk of
5852    /// choice 2 arrives before the LAST chunk of choice 0.
5853    ///
5854    /// Also pinned: exactly one terminal chunk per choice, and exactly
5855    /// one usage block for the request.
5856    #[tokio::test]
5857    async fn a_streamed_n_interleaves_its_choices() {
5858        let app = streaming_test_app();
5859        let raw = post_sse_raw(
5860            &app,
5861            serde_json::json!({
5862                "model": "x",
5863                "messages": [{"role": "user", "content": "hi"}],
5864                "max_tokens": 6,
5865                "temperature": 1.0,
5866                "n": 3,
5867                "stream": true
5868            }),
5869        )
5870        .await;
5871
5872        // The index carried by each chunk, in wire order.
5873        let mut order: Vec<usize> = Vec::new();
5874        let mut finished: Vec<usize> = Vec::new();
5875        let mut usage_blocks = 0usize;
5876        for line in raw.lines() {
5877            let Some(rest) = line.strip_prefix("data: ") else {
5878                continue;
5879            };
5880            if rest.trim() == "[DONE]" {
5881                continue;
5882            }
5883            let v: serde_json::Value = serde_json::from_str(rest).expect(rest);
5884            if v.get("usage").is_some_and(|u| !u.is_null()) {
5885                usage_blocks += 1;
5886            }
5887            let Some(choice) = v["choices"].as_array().and_then(|c| c.first()) else {
5888                continue;
5889            };
5890            let index = choice["index"].as_u64().expect("an index") as usize;
5891            if choice["finish_reason"].is_string() {
5892                finished.push(index);
5893                continue;
5894            }
5895            order.push(index);
5896        }
5897
5898        assert_eq!(
5899            finished,
5900            vec![0, 1, 2],
5901            "one terminal chunk per choice, in index order: {raw}"
5902        );
5903        assert_eq!(usage_blocks, 1, "the usage block is the request's: {raw}");
5904        assert!(
5905            order.contains(&0) && order.contains(&2),
5906            "not every choice streamed: {order:?}"
5907        );
5908        let last_of_zero = order
5909            .iter()
5910            .rposition(|i| *i == 0)
5911            .expect("choice 0 streamed");
5912        let first_of_two = order
5913            .iter()
5914            .position(|i| *i == 2)
5915            .expect("choice 2 streamed");
5916        assert!(
5917            first_of_two < last_of_zero,
5918            "the choices arrived one after another rather than interleaved: {order:?}"
5919        );
5920    }
5921
5922    /// **`skip_special_tokens: false` keeps the marker that ended the
5923    /// answer.**
5924    ///
5925    /// It still ENDS the answer -- the field is about what comes
5926    /// back, not about when to stop -- so both halves are checked: the
5927    /// end token's text is in the string, and the finish reason is
5928    /// still `stop`.
5929    ///
5930    /// `0x77` is the id this model greedily emits SECOND for the
5931    /// prompt below, so the EOS really fires rather than the budget
5932    /// running out, which is the only case the field is about.
5933    #[tokio::test]
5934    async fn skip_special_tokens_false_keeps_the_end_marker() {
5935        // Which id this model emits SECOND is a property of random
5936        // weights, so it is MEASURED rather than hard-coded: a
5937        // constant tuned on one route silently stops firing on
5938        // another, and a test whose EOS never fires passes for the
5939        // wrong reason. `return_tokens_as_token_ids` is what makes the
5940        // ids readable over HTTP, which is the other field in this PR.
5941        let probe = test_app_with_state(Arc::new(test_state(
5942            test_byte_model(None, /* synthetic = */ false),
5943            ResponseCache::new(1000, Duration::from_secs(3600)),
5944        )));
5945        let (_, seen) = post_json_uri(
5946            &probe,
5947            frink_api::routes::V1_COMPLETIONS,
5948            serde_json::json!({
5949                "model": "x",
5950                "prompt": "\u{1}\u{2}",
5951                "max_tokens": 6,
5952                "temperature": 0,
5953                "logprobs": 1,
5954                "return_tokens_as_token_ids": true
5955            }),
5956        )
5957        .await;
5958        let eos: usize = seen["choices"][0]["logprobs"]["tokens"][1]
5959            .as_str()
5960            .and_then(|s| s.strip_prefix("token_id:"))
5961            .and_then(|s| s.parse().ok())
5962            .expect("a second generated token");
5963
5964        let app = test_app_with_state(Arc::new(test_state(
5965            test_byte_model(Some(eos), /* synthetic = */ false),
5966            ResponseCache::new(1000, Duration::from_secs(3600)),
5967        )));
5968        let ask = |skip: bool| {
5969            serde_json::json!({
5970                "model": "x",
5971                "prompt": "\u{1}\u{2}",
5972                "max_tokens": 6,
5973                "temperature": 0,
5974                "skip_special_tokens": skip
5975            })
5976        };
5977
5978        let (status, kept) =
5979            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(false)).await;
5980        assert_eq!(status, StatusCode::OK, "{kept}");
5981        let (status, skipped) =
5982            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(true)).await;
5983        assert_eq!(status, StatusCode::OK, "{skipped}");
5984
5985        // The model has to have ENDED the turn, or neither answer
5986        // carries a marker and this proves nothing.
5987        assert_eq!(
5988            kept["choices"][0]["finish_reason"], "stop",
5989            "the model did not end the turn: {kept}"
5990        );
5991        assert_eq!(
5992            skipped["choices"][0]["finish_reason"], "stop",
5993            "keeping the marker must not change WHEN it stops: {skipped}"
5994        );
5995
5996        let with = kept["choices"][0]["text"].as_str().expect("text");
5997        let without = skipped["choices"][0]["text"].as_str().expect("text");
5998        // A byte tokenizer: the id IS the byte.
5999        let marker = char::from(eos as u8);
6000        assert!(
6001            with.ends_with(marker),
6002            "the end marker was dropped: {with:?}"
6003        );
6004        assert!(
6005            !without.ends_with(marker),
6006            "the default must still skip it: {without:?}"
6007        );
6008        assert_eq!(
6009            with.len(),
6010            without.len() + marker.len_utf8(),
6011            "the two answers differ by more than the marker"
6012        );
6013        // Counted as well as rendered: it is a token the model
6014        // produced.
6015        assert_eq!(
6016            kept["usage"]["completion_tokens"].as_u64().unwrap(),
6017            skipped["usage"]["completion_tokens"].as_u64().unwrap() + 1,
6018            "the kept marker was not counted"
6019        );
6020    }
6021
6022    /// **`return_tokens_as_token_ids` spells a REPORTED token by id.**
6023    ///
6024    /// The completion's own `text` is unchanged: it is the answer
6025    /// rather than a report about it, and a caller who wants the ids
6026    /// of the answer asks `/v1/tokenize`.
6027    #[tokio::test]
6028    async fn return_tokens_as_token_ids_renames_reported_tokens_only() {
6029        let app = streaming_test_app();
6030        let ask = |as_ids: bool| {
6031            serde_json::json!({
6032                "model": "x",
6033                "prompt": "hi",
6034                "max_tokens": 4,
6035                "temperature": 0,
6036                "logprobs": 2,
6037                "return_tokens_as_token_ids": as_ids
6038            })
6039        };
6040
6041        let (status, plain) =
6042            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(false)).await;
6043        assert_eq!(status, StatusCode::OK, "{plain}");
6044        let (status, by_id) =
6045            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(true)).await;
6046        assert_eq!(status, StatusCode::OK, "{by_id}");
6047
6048        let tokens = by_id["choices"][0]["logprobs"]["tokens"]
6049            .as_array()
6050            .expect("tokens");
6051        assert!(!tokens.is_empty(), "nothing was reported: {by_id}");
6052        for t in tokens {
6053            let s = t.as_str().expect("a piece");
6054            assert!(
6055                s.starts_with("token_id:") && s["token_id:".len()..].parse::<usize>().is_ok(),
6056                "reported as text rather than by id: {s:?}"
6057            );
6058        }
6059        // The alternatives are keyed the same way, which is the point:
6060        // two ids can detokenize to one string and a map keyed by text
6061        // loses one of them.
6062        let top = &by_id["choices"][0]["logprobs"]["top_logprobs"][0];
6063        for key in top.as_object().expect("a map").keys() {
6064            assert!(key.starts_with("token_id:"), "{key:?}");
6065        }
6066        // The ANSWER is untouched.
6067        assert_eq!(
6068            by_id["choices"][0]["text"], plain["choices"][0]["text"],
6069            "the completion's text changed, which the field does not do"
6070        );
6071        assert!(
6072            !plain["choices"][0]["logprobs"]["tokens"][0]
6073                .as_str()
6074                .unwrap_or_default()
6075                .starts_with("token_id:"),
6076            "the default already reported ids, so this proved nothing"
6077        );
6078    }
6079
6080    /// **`echo` returns the prompt and the completion as one string,
6081    /// and the logprobs arrays cover both.**
6082    ///
6083    /// The half that is easy to get wrong is `text_offset`: a client
6084    /// slices `text` with it, so an offset computed over the
6085    /// completion alone points into the middle of the echoed prompt.
6086    /// Checked by SLICING the returned text at each offset and
6087    /// comparing it against the token it names.
6088    #[tokio::test]
6089    async fn echo_returns_the_prompt_with_offsets_that_index_it() {
6090        let app = streaming_test_app();
6091        let prompt = "hello";
6092        let (status, body) = post_json_uri(
6093            &app,
6094            frink_api::routes::V1_COMPLETIONS,
6095            serde_json::json!({
6096                "model": "x",
6097                "prompt": prompt,
6098                "max_tokens": 6,
6099                "temperature": 0,
6100                "echo": true,
6101                "logprobs": 2
6102            }),
6103        )
6104        .await;
6105        assert_eq!(status, StatusCode::OK, "{body}");
6106
6107        let text = body["choices"][0]["text"].as_str().expect("text");
6108        assert!(
6109            text.starts_with(prompt),
6110            "the prompt was not echoed: {text:?}"
6111        );
6112        assert!(
6113            text.len() > prompt.len(),
6114            "nothing was generated after the echo: {text:?}"
6115        );
6116
6117        let lp = &body["choices"][0]["logprobs"];
6118        let tokens = lp["tokens"].as_array().expect("tokens");
6119        let offsets = lp["text_offset"].as_array().expect("text_offset");
6120        let scores = lp["token_logprobs"].as_array().expect("token_logprobs");
6121        assert_eq!(tokens.len(), offsets.len());
6122        assert_eq!(tokens.len(), scores.len());
6123        assert!(
6124            tokens.len() > 6,
6125            "the arrays cover only the completion: {}",
6126            tokens.len()
6127        );
6128        // Nothing predicted the first prompt token.
6129        assert!(scores[0].is_null(), "{lp}");
6130        // Every offset names the token that starts there.
6131        for (i, (tok, off)) in tokens.iter().zip(offsets).enumerate() {
6132            let (piece, at) = (
6133                tok.as_str().expect("a piece"),
6134                off.as_u64().unwrap() as usize,
6135            );
6136            assert!(
6137                text[at..].starts_with(piece),
6138                "entry {i}: offset {at} does not start {piece:?} in {text:?}"
6139            );
6140        }
6141    }
6142
6143    /// **`truncate_prompt_tokens` answers the prompt it kept, and
6144    /// `echo` says so.**
6145    ///
6146    /// The field was the most dangerous refusal in the table because
6147    /// IGNORING it answers a different prompt with no error. Serving
6148    /// it has the mirror risk: echoing the caller's full string after
6149    /// truncating would report a prompt the model never saw. Both are
6150    /// pinned here -- the usage counts the kept tokens, and the echo
6151    /// is the kept tokens.
6152    #[tokio::test]
6153    async fn truncate_prompt_tokens_keeps_the_last_k_and_echo_reports_them() {
6154        let app = streaming_test_app();
6155        let prompt = "abcdefghij";
6156        let ask = |k: Option<u32>| {
6157            let mut b = serde_json::json!({
6158                "model": "x",
6159                "prompt": prompt,
6160                "max_tokens": 2,
6161                "temperature": 0,
6162                "echo": true
6163            });
6164            if let Some(k) = k {
6165                b["truncate_prompt_tokens"] = serde_json::json!(k);
6166            }
6167            b
6168        };
6169
6170        let (status, full) =
6171            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(None)).await;
6172        assert_eq!(status, StatusCode::OK, "{full}");
6173        let full_prompt_tokens = full["usage"]["prompt_tokens"].as_u64().expect("usage");
6174        assert!(full_prompt_tokens > 4, "the prompt is too short to cut");
6175
6176        let (status, cut) =
6177            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(Some(4))).await;
6178        assert_eq!(status, StatusCode::OK, "{cut}");
6179        assert_eq!(
6180            cut["usage"]["prompt_tokens"].as_u64(),
6181            Some(4),
6182            "the prompt was not truncated: {cut}"
6183        );
6184        // A byte tokenizer, so four tokens are the last four bytes.
6185        let text = cut["choices"][0]["text"].as_str().expect("text");
6186        assert!(
6187            text.starts_with("ghij"),
6188            "echo reported a prompt the model never saw: {text:?}"
6189        );
6190        assert!(
6191            !text.starts_with(prompt),
6192            "the full prompt was echoed after a truncation: {text:?}"
6193        );
6194    }
6195
6196    /// Zero and negative counts are a 400: the field IS implemented,
6197    /// and asking to keep none of the prompt is not a request any
6198    /// server can serve.
6199    #[tokio::test]
6200    async fn a_truncation_below_one_is_a_bad_request() {
6201        let app = streaming_test_app();
6202        for k in [0i64, -1] {
6203            let (status, body) = post_json_uri(
6204                &app,
6205                frink_api::routes::V1_COMPLETIONS,
6206                serde_json::json!({
6207                    "model": "x",
6208                    "prompt": "hi",
6209                    "max_tokens": 2,
6210                    "truncate_prompt_tokens": k
6211                }),
6212            )
6213            .await;
6214            assert_eq!(status, StatusCode::BAD_REQUEST, "k = {k}: {body}");
6215        }
6216    }
6217
6218    /// **`allowed_token_ids` restricts what can come back.**
6219    ///
6220    /// Byte tokenizer, so a token id IS a byte and the answer can be
6221    /// read directly: restrict to `A` and `B` and every character of
6222    /// the completion must be one of them. A server that dropped the
6223    /// field answers ordinary text and a 200, which is exactly the
6224    /// failure the refusal existed to avoid.
6225    #[tokio::test]
6226    async fn allowed_token_ids_restricts_the_draw() {
6227        let app = streaming_test_app();
6228        let body = |allowed: Option<serde_json::Value>| {
6229            let mut b = serde_json::json!({
6230                "model": "x",
6231                "prompt": "hi",
6232                "max_tokens": 16,
6233                "temperature": 1.0,
6234                "seed": 3
6235            });
6236            if let Some(ids) = allowed {
6237                b["allowed_token_ids"] = ids;
6238            }
6239            b
6240        };
6241
6242        // Unrestricted first, so the restriction below is measured
6243        // against what this model actually says.
6244        let (status, free) =
6245            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, body(None)).await;
6246        assert_eq!(status, StatusCode::OK, "{free}");
6247        let free_text = free["choices"][0]["text"].as_str().unwrap_or_default();
6248
6249        let (status, restricted) = post_json_uri(
6250            &app,
6251            frink_api::routes::V1_COMPLETIONS,
6252            // 'A' and 'B'.
6253            body(Some(serde_json::json!([65, 66]))),
6254        )
6255        .await;
6256        assert_eq!(status, StatusCode::OK, "{restricted}");
6257        let text = restricted["choices"][0]["text"]
6258            .as_str()
6259            .unwrap_or_default();
6260        assert!(!text.is_empty(), "nothing was generated: {restricted}");
6261        assert!(
6262            text.chars().all(|c| c == 'A' || c == 'B'),
6263            "a token outside `allowed_token_ids` was drawn: {text:?}"
6264        );
6265        // The premise: an unrestricted draw is not already all As and
6266        // Bs, or the assertion above holds for free.
6267        assert!(
6268            !free_text.chars().all(|c| c == 'A' || c == 'B'),
6269            "the unrestricted answer was already inside the allowed set: {free_text:?}"
6270        );
6271    }
6272
6273    /// **An empty `allowed_token_ids` is a 400, not a 501.**
6274    ///
6275    /// The field IS implemented; asking to draw from nothing is not a
6276    /// request any server can serve, and honouring it would produce a
6277    /// row of `-inf` and a token that is an artefact of argmax over
6278    /// negative infinity.
6279    #[tokio::test]
6280    async fn an_empty_allowed_token_ids_is_a_bad_request() {
6281        let app = streaming_test_app();
6282        let (status, body) = post_json_uri(
6283            &app,
6284            frink_api::routes::V1_COMPLETIONS,
6285            serde_json::json!({
6286                "model": "x",
6287                "prompt": "hi",
6288                "max_tokens": 4,
6289                "allowed_token_ids": []
6290            }),
6291        )
6292        .await;
6293        assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
6294        assert!(
6295            body["error"]["message"]
6296                .as_str()
6297                .unwrap_or_default()
6298                .contains("allowed_token_ids"),
6299            "{body}"
6300        );
6301    }
6302
6303    /// **`bad_words` steers around a token without ending the answer.**
6304    ///
6305    /// The distinction from `stop`, stated as behaviour: the forbidden
6306    /// byte must not appear, AND the generation must run to its budget
6307    /// rather than stopping the first time the model wanted it.
6308    #[tokio::test]
6309    async fn bad_words_removes_a_token_without_ending_the_generation() {
6310        let app = streaming_test_app();
6311        let ask = |bad: Option<serde_json::Value>| {
6312            let mut b = serde_json::json!({
6313                "model": "x",
6314                "prompt": "hi",
6315                "max_tokens": 24,
6316                "temperature": 1.0,
6317                "seed": 11
6318            });
6319            if let Some(words) = bad {
6320                b["bad_words"] = words;
6321            }
6322            b
6323        };
6324
6325        let (status, free) =
6326            post_json_uri(&app, frink_api::routes::V1_COMPLETIONS, ask(None)).await;
6327        assert_eq!(status, StatusCode::OK, "{free}");
6328        let free_text = free["choices"][0]["text"]
6329            .as_str()
6330            .unwrap_or_default()
6331            .to_string();
6332        // Forbid a character the unrestricted answer really produced,
6333        // or the test proves nothing.
6334        let target = free_text
6335            .chars()
6336            .find(|c| c.is_ascii() && !c.is_control())
6337            .expect("the model produced some ascii");
6338
6339        let (status, steered) = post_json_uri(
6340            &app,
6341            frink_api::routes::V1_COMPLETIONS,
6342            ask(Some(serde_json::json!([target.to_string()]))),
6343        )
6344        .await;
6345        assert_eq!(status, StatusCode::OK, "{steered}");
6346        let text = steered["choices"][0]["text"].as_str().unwrap_or_default();
6347        assert!(
6348            !text.contains(target),
6349            "the forbidden {target:?} came back anyway: {text:?}"
6350        );
6351        // Steered, not stopped: `stop` would have ended the answer at
6352        // the first occurrence.
6353        assert_eq!(
6354            steered["usage"]["completion_tokens"], free["usage"]["completion_tokens"],
6355            "the generation ended early, so `bad_words` acted like `stop`: {steered}"
6356        );
6357    }
6358
6359    /// The three generation routes must agree about every field this
6360    /// server does not implement. They did not: `n: 3` was a 501 on
6361    /// `/v1/chat/completions` and a 200 on `/v1/completions`, measured
6362    /// on a running server, because the chat route hand-wrote its own
6363    /// check and the other two never learned it.
6364    ///
6365    /// This is the test that would have caught that, and it is driven
6366    /// from one list so a field added to `unimplemented_fields` is
6367    /// checked on all three wires at once.
6368    #[tokio::test]
6369    async fn every_route_refuses_the_same_unimplemented_fields() {
6370        let app = test_app();
6371        let fields = [
6372            ("n", serde_json::json!(3)),
6373            ("best_of", serde_json::json!(2)),
6374            ("prompt_logprobs", serde_json::json!(1)),
6375            ("echo", serde_json::json!(true)),
6376            ("use_beam_search", serde_json::json!(true)),
6377            ("truncate_prompt_tokens", serde_json::json!(8)),
6378            ("prompt_embeds", serde_json::json!("AA==")),
6379            ("skip_special_tokens", serde_json::json!(false)),
6380            ("return_tokens_as_token_ids", serde_json::json!(true)),
6381        ];
6382        for (field, value) in fields {
6383            for (uri, base) in [
6384                (
6385                    frink_api::routes::V1_CHAT_COMPLETIONS,
6386                    serde_json::json!({
6387                        "model": "x",
6388                        "messages": [{"role": "user", "content": "hi"}],
6389                        "max_tokens": 2
6390                    }),
6391                ),
6392                (
6393                    frink_api::routes::V1_COMPLETIONS,
6394                    serde_json::json!({"prompt": "hi", "max_tokens": 2}),
6395                ),
6396                (
6397                    frink_api::routes::COMPLETION,
6398                    serde_json::json!({"prompt": "hi", "n_predict": 2}),
6399                ),
6400            ] {
6401                let mut body = base;
6402                body[field] = value.clone();
6403                // `n` is SERVED where the response has a `choices`
6404                // array to carry the answers, which is the one
6405                // per-route exception in the table
6406                // (`unimplemented_fields::SERVES_SEVERAL_CHOICES`).
6407                // `prompt_logprobs` is served on the one wire with a
6408                // field for it, and is not a choices-array question.
6409                if field == "prompt_logprobs" && uri == frink_api::routes::V1_COMPLETIONS {
6410                    let (status, answer) = post_json_uri(&app, uri, body).await;
6411                    assert_eq!(status, StatusCode::OK, "{uri} refused it: {answer}");
6412                    assert!(
6413                        answer["prompt_logprobs"].is_array(),
6414                        "served without the field: {answer}"
6415                    );
6416                    continue;
6417                }
6418                // `echo` is served on the one wire that returns a
6419                // continuation of the prompt, and refused on the two
6420                // that return a message.
6421                if field == "echo" && uri == frink_api::routes::V1_COMPLETIONS {
6422                    let (status, answer) = post_json_uri(&app, uri, body).await;
6423                    assert_eq!(status, StatusCode::OK, "{uri} refused `echo`: {answer}");
6424                    assert!(
6425                        answer["choices"][0]["text"]
6426                            .as_str()
6427                            .unwrap_or_default()
6428                            .starts_with("hi"),
6429                        "served without echoing the prompt: {answer}"
6430                    );
6431                    continue;
6432                }
6433                // Both rendering fields are served on every wire that
6434                // takes them: one changes the text, the other how a
6435                // reported token is spelled.
6436                if field == "skip_special_tokens" || field == "return_tokens_as_token_ids" {
6437                    let (status, answer) = post_json_uri(&app, uri, body).await;
6438                    assert_eq!(status, StatusCode::OK, "{uri} refused `{field}`: {answer}");
6439                    continue;
6440                }
6441                // `truncate_prompt_tokens` is served on every wire that
6442                // tokenizes a prompt here, which is all three.
6443                if field == "truncate_prompt_tokens" {
6444                    let (status, answer) = post_json_uri(&app, uri, body).await;
6445                    assert_eq!(
6446                        status,
6447                        StatusCode::OK,
6448                        "{uri} refused `truncate_prompt_tokens`: {answer}"
6449                    );
6450                    continue;
6451                }
6452                if (field == "n" || field == "best_of")
6453                    && (uri == frink_api::routes::V1_COMPLETIONS
6454                        || uri == frink_api::routes::V1_CHAT_COMPLETIONS)
6455                {
6456                    let (status, answer) = post_json_uri(&app, uri, body).await;
6457                    assert_eq!(
6458                        status,
6459                        StatusCode::OK,
6460                        "{uri} refused a served `{field}`: {answer}"
6461                    );
6462                    // `n: 3` returns three; `best_of: 2` generates two
6463                    // and returns the best ONE, which is the whole
6464                    // difference between the two fields.
6465                    let want = if field == "n" { 3 } else { 1 };
6466                    assert_eq!(
6467                        answer["choices"].as_array().map(Vec::len),
6468                        Some(want),
6469                        "{field}: {answer}"
6470                    );
6471                    continue;
6472                }
6473                let (status, answer) = post_json_uri(&app, uri, body).await;
6474                assert_eq!(
6475                    status,
6476                    StatusCode::NOT_IMPLEMENTED,
6477                    "{uri} served `{field}` instead of refusing it: {answer}"
6478                );
6479                assert!(
6480                    answer["error"]["message"]
6481                        .as_str()
6482                        .is_some_and(|m| m.contains(field)),
6483                    "{uri} refused `{field}` without naming it: {answer}"
6484                );
6485            }
6486        }
6487    }
6488
6489    #[tokio::test]
6490    async fn the_native_completion_wire_is_not_the_openai_one() {
6491        let app = test_app();
6492
6493        let (status, native) = post_json_uri(
6494            &app,
6495            frink_api::routes::COMPLETION,
6496            serde_json::json!({"prompt": "hi", "n_predict": 4}),
6497        )
6498        .await;
6499        assert_eq!(status, StatusCode::OK, "{native}");
6500        assert!(native["content"].is_string(), "{native}");
6501        assert_eq!(native["stop"], true);
6502        assert_eq!(native["stop_type"], "limit");
6503        assert_eq!(native["stopping_word"], "");
6504        assert_eq!(native["truncated"], false);
6505        assert_eq!(native["id_slot"], -1);
6506        assert!(native["timings"]["prompt_n"].is_number(), "{native}");
6507        assert!(native["generation_settings"]["n_predict"] == 4, "{native}");
6508        assert!(
6509            native.get("choices").is_none(),
6510            "the native shape has no `choices`: {native}"
6511        );
6512
6513        let (status, openai) = post_json_uri(
6514            &app,
6515            frink_api::routes::V1_COMPLETIONS,
6516            serde_json::json!({"prompt": "hi", "max_tokens": 4}),
6517        )
6518        .await;
6519        assert_eq!(status, StatusCode::OK);
6520        assert!(openai["choices"][0]["text"].is_string(), "{openai}");
6521        assert!(
6522            openai.get("content").is_none(),
6523            "the OpenAI shape has no top-level `content`: {openai}"
6524        );
6525    }
6526
6527    /// llama.cpp mounts the native endpoint under both spellings
6528    /// (`server.cpp:240-241`), and its own web UI uses the plural. One
6529    /// handler, so the two cannot answer differently.
6530    #[tokio::test]
6531    async fn both_native_spellings_reach_the_same_handler() {
6532        let app = test_app();
6533        for route in [
6534            frink_api::routes::COMPLETION,
6535            frink_api::routes::COMPLETIONS,
6536        ] {
6537            let (status, body) = post_json_uri(
6538                &app,
6539                route,
6540                serde_json::json!({"prompt": "hi", "n_predict": 2, "seed": 1}),
6541            )
6542            .await;
6543            assert_eq!(status, StatusCode::OK, "{route}: {body}");
6544            assert_eq!(body["stop"], true, "{route}");
6545            assert!(body["content"].is_string(), "{route}");
6546        }
6547
6548        // And the ring records which one was called, so the split
6549        // between clients stays visible.
6550        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6551        let routes: Vec<&str> = stats["recent"]
6552            .as_array()
6553            .unwrap()
6554            .iter()
6555            .map(|row| row["route"].as_str().unwrap())
6556            .collect();
6557        assert!(
6558            routes.contains(&frink_api::routes::COMPLETION),
6559            "{routes:?}"
6560        );
6561        assert!(
6562            routes.contains(&frink_api::routes::COMPLETIONS),
6563            "{routes:?}"
6564        );
6565    }
6566
6567    /// The native stream is not OpenAI's. Frames are bare objects with
6568    /// `content` and `stop`, the last one carries `stop: true` and the
6569    /// whole terminal body, and there is **no `[DONE]`** -- a client
6570    /// waiting for one would hang, and one that got it would try to
6571    /// parse it as JSON.
6572    #[tokio::test]
6573    async fn a_native_stream_ends_on_a_stop_frame_with_no_done_sentinel() {
6574        let app = streaming_test_app();
6575        let raw = post_sse_raw_uri(
6576            &app,
6577            frink_api::routes::COMPLETION,
6578            serde_json::json!({"prompt": "hi", "n_predict": 6, "stream": true, "seed": 7}),
6579        )
6580        .await;
6581
6582        assert!(
6583            !raw.contains("[DONE]"),
6584            "llama.cpp's native stream has no sentinel: {raw}"
6585        );
6586        let frames: Vec<serde_json::Value> = raw
6587            .lines()
6588            .filter_map(|line| line.strip_prefix("data: "))
6589            .map(|json| serde_json::from_str(json).expect("every frame is one JSON object"))
6590            .collect();
6591        assert!(frames.len() >= 2, "expected partials then a final: {raw}");
6592
6593        let (last, partials) = frames.split_last().unwrap();
6594        assert_eq!(last["stop"], true, "the last frame closes the stream");
6595        assert!(last["timings"].is_object(), "{last}");
6596        assert!(last["stop_type"].is_string(), "{last}");
6597        for partial in partials {
6598            assert_eq!(partial["stop"], false, "{partial}");
6599            assert!(partial["content"].is_string(), "{partial}");
6600            // Upstream's documented partial carries content/tokens/stop
6601            // and nothing else; the terminal fields belong to the last
6602            // frame only.
6603            assert!(partial.get("timings").is_none(), "{partial}");
6604            assert!(partial.get("generation_settings").is_none(), "{partial}");
6605        }
6606        // The concatenated partials are the answer, so a client that
6607        // streams sees what a client that buffers would get.
6608        let streamed: String = partials
6609            .iter()
6610            .filter_map(|p| p["content"].as_str())
6611            .collect();
6612        assert_eq!(last["content"].as_str().unwrap(), streamed);
6613    }
6614
6615    /// `n_predict: -1` is llama.cpp's default AND its "until the
6616    /// context is full". With no derived ceiling there is no context to
6617    /// be full of, and quietly substituting a small budget would hand a
6618    /// caller a truncated answer it never asked for.
6619    #[tokio::test]
6620    async fn an_unbounded_n_predict_is_refused_rather_than_quietly_shrunk() {
6621        let app = test_app();
6622        for body in [
6623            serde_json::json!({"prompt": "hi"}),
6624            serde_json::json!({"prompt": "hi", "n_predict": -1}),
6625        ] {
6626            let (status, refusal) =
6627                post_json_uri(&app, frink_api::routes::COMPLETION, body.clone()).await;
6628            assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}: {refusal}");
6629            assert!(
6630                refusal["error"]["message"]
6631                    .as_str()
6632                    .unwrap()
6633                    .contains("n_predict"),
6634                "{refusal}"
6635            );
6636        }
6637        // An explicit budget is served, so the refusal is about the
6638        // unbounded case and not about the endpoint.
6639        let (status, _) = post_json_uri(
6640            &app,
6641            frink_api::routes::COMPLETION,
6642            serde_json::json!({"prompt": "hi", "n_predict": 2}),
6643        )
6644        .await;
6645        assert_eq!(status, StatusCode::OK);
6646    }
6647
6648    /// A caller's `stop` must actually reach the sampler, and be named
6649    /// back in llama.cpp's own vocabulary. Dropping it is the dangerous
6650    /// silent failure: the caller believes generation halts at its
6651    /// sentinel and instead gets the whole budget of text past it.
6652    ///
6653    /// Deterministic without depending on what random weights say:
6654    /// generate once with no stop, then take a character out of that
6655    /// answer and demand the second run halt before it.
6656    #[tokio::test]
6657    async fn a_stop_string_halts_the_answer_and_is_named_back() {
6658        let app = streaming_test_app();
6659        let ask = |stop: serde_json::Value| {
6660            let app = app.clone();
6661            async move {
6662                post_json_uri(
6663                    &app,
6664                    frink_api::routes::COMPLETION,
6665                    serde_json::json!({
6666                        "prompt": "hi",
6667                        "n_predict": 64,
6668                        "ignore_eos": true,
6669                        "stop": stop,
6670                    }),
6671                )
6672                .await
6673                .1
6674            }
6675        };
6676
6677        let baseline = ask(serde_json::json!([])).await;
6678        assert_eq!(baseline["stop_type"], "limit");
6679        assert_eq!(baseline["stopping_word"], "");
6680        let text = baseline["content"].as_str().unwrap().to_string();
6681        // Two characters, so the sentinel is more than one token in
6682        // this vocabulary and goes through the output-suffix layer that
6683        // reports WHICH string matched. A single-token stop is caught
6684        // by the token layer, which does not carry the string back --
6685        // see `stop_type`'s note and docs/API.md.
6686        let sentinel: String = text.chars().skip(1).take(2).collect();
6687        assert_eq!(
6688            sentinel.chars().count(),
6689            2,
6690            "the fixture must produce enough output to cut: {text:?}"
6691        );
6692        let cut = text.find(&sentinel).expect("it came out of this text");
6693
6694        let stopped = ask(serde_json::json!([sentinel])).await;
6695        assert_eq!(stopped["stop_type"], "word", "{stopped}");
6696        assert_eq!(stopped["stopping_word"], sentinel);
6697        assert_eq!(
6698            stopped["content"].as_str().unwrap(),
6699            &text[..cut],
6700            "the answer must be cut at the sentinel, not run past it"
6701        );
6702    }
6703
6704    /// llama.cpp mounts these two unprefixed and sends `content`, not
6705    /// `prompt`. frink mounted only the `/v1/` spelling it invented,
6706    /// so every llama.cpp client got a 404 that named nothing. The
6707    /// alias must reach the SAME handler -- identical ids for identical
6708    /// text -- rather than a second implementation of it.
6709    #[tokio::test]
6710    async fn the_llama_cpp_spelling_of_tokenize_reaches_the_same_handler() {
6711        let app = test_app();
6712
6713        let (v1_status, v1) = post_json_uri(
6714            &app,
6715            frink_api::routes::V1_TOKENIZE,
6716            serde_json::json!({"prompt": "hello"}),
6717        )
6718        .await;
6719        let (alias_status, alias) = post_json_uri(
6720            &app,
6721            frink_api::routes::TOKENIZE,
6722            serde_json::json!({"content": "hello"}),
6723        )
6724        .await;
6725        assert_eq!(v1_status, StatusCode::OK);
6726        assert_eq!(alias_status, StatusCode::OK, "{alias}");
6727        assert_eq!(v1["tokens"], alias["tokens"]);
6728        assert!(!alias["tokens"].as_array().unwrap().is_empty());
6729
6730        // And the reverse: frink's own field still works on llama.cpp's
6731        // path, so a client that switches URLs need not switch dialects.
6732        let (status, both_ways) = post_json_uri(
6733            &app,
6734            frink_api::routes::TOKENIZE,
6735            serde_json::json!({"prompt": "hello"}),
6736        )
6737        .await;
6738        assert_eq!(status, StatusCode::OK);
6739        assert_eq!(both_ways["tokens"], v1["tokens"]);
6740    }
6741
6742    /// llama.cpp answers detokenize under `content`
6743    /// (`server-context.cpp:4970`); frink has always answered under
6744    /// `text`. Both keys carry the same string, so neither dialect's
6745    /// client reads a null.
6746    #[tokio::test]
6747    async fn detokenize_answers_under_both_dialects_keys() {
6748        let app = test_app();
6749        for route in [
6750            frink_api::routes::DETOKENIZE,
6751            frink_api::routes::V1_DETOKENIZE,
6752        ] {
6753            let (status, body) =
6754                post_json_uri(&app, route, serde_json::json!({"tokens": [104, 105]})).await;
6755            assert_eq!(status, StatusCode::OK, "{route}");
6756            assert_eq!(body["text"], "hi", "{route}");
6757            assert_eq!(body["content"], body["text"], "{route}");
6758        }
6759    }
6760
6761    /// The alias is one handler, so the ring must not attribute a
6762    /// llama.cpp client's traffic to the frink spelling: the row
6763    /// carries the path that was actually matched.
6764    #[tokio::test]
6765    async fn the_alias_is_recorded_under_the_path_the_client_called() {
6766        let app = test_app();
6767        let (status, _) = post_json_uri(
6768            &app,
6769            frink_api::routes::TOKENIZE,
6770            serde_json::json!({"content": "hello"}),
6771        )
6772        .await;
6773        assert_eq!(status, StatusCode::OK);
6774
6775        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6776        let routes: Vec<&str> = stats["recent"]
6777            .as_array()
6778            .unwrap()
6779            .iter()
6780            .map(|row| row["route"].as_str().unwrap())
6781            .collect();
6782        assert!(
6783            routes.contains(&frink_api::routes::TOKENIZE),
6784            "the alias must be its own row: {routes:?}"
6785        );
6786        assert!(
6787            !routes.contains(&frink_api::routes::V1_TOKENIZE),
6788            "nothing called /v1/tokenize: {routes:?}"
6789        );
6790    }
6791
6792    /// `add_special` is llama.cpp's "prepend BOS". Honoured, and with
6793    /// the id the generation path itself would prepend -- a tokenize
6794    /// endpoint that disagrees with the decoder about the prompt is
6795    /// worse than one that has no such option.
6796    #[tokio::test]
6797    async fn add_special_prepends_the_same_bos_the_decoder_would() {
6798        let mut cfg = test_dense_fixture();
6799        cfg.vocab_size = 256;
6800        let model = Model::Gguf(GgufModel {
6801            decoder: Arc::new(Decoder::new_random_small(cfg, 2, 256)),
6802            tokenizer: Arc::new(ServerTokenizer::Byte),
6803            stop_tokens: StopTokens::default(),
6804            bos_id: Some(7),
6805            is_synthetic: true,
6806            chat_template: chat_template::PromptTemplate::plain(),
6807        });
6808        let app = test_app_with_state(Arc::new(test_state(
6809            model,
6810            ResponseCache::new(1000, Duration::from_secs(3600)),
6811        )));
6812
6813        let (_, plain) = post_json_uri(
6814            &app,
6815            frink_api::routes::TOKENIZE,
6816            serde_json::json!({"content": "hi"}),
6817        )
6818        .await;
6819        let (_, special) = post_json_uri(
6820            &app,
6821            frink_api::routes::TOKENIZE,
6822            serde_json::json!({"content": "hi", "add_special": true}),
6823        )
6824        .await;
6825
6826        assert_eq!(plain["tokens"], serde_json::json!([104, 105]));
6827        assert_eq!(special["tokens"], serde_json::json!([7, 104, 105]));
6828        assert_eq!(special["count"], 3);
6829    }
6830
6831    /// A failed small-endpoint call is still traffic. A 400 that leaves
6832    /// no row is indistinguishable from a request that was never sent.
6833    #[tokio::test]
6834    async fn a_rejected_embeddings_request_is_recorded_with_its_status() {
6835        let app = test_app();
6836        let (status, _) = post_json_uri(
6837            &app,
6838            frink_api::routes::V1_EMBEDDINGS,
6839            serde_json::json!({"input": "hi", "encoding_format": "base64"}),
6840        )
6841        .await;
6842        assert_eq!(status, StatusCode::BAD_REQUEST);
6843
6844        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6845        let recent = stats["recent"].as_array().unwrap();
6846        assert_eq!(recent.len(), 1);
6847        assert_eq!(recent[0]["route"], frink_api::routes::V1_EMBEDDINGS);
6848        assert_eq!(recent[0]["status"], 400);
6849        assert_eq!(
6850            recent[0]["prompt_tokens"], 0,
6851            "a rejected call embedded nothing"
6852        );
6853    }
6854
6855    /// Attribution: which key served a request, and what the caller
6856    /// says it is. The key itself must never appear.
6857    #[tokio::test]
6858    async fn a_row_names_the_key_that_served_it_without_carrying_the_key() {
6859        let app = test_app();
6860        let key = "sk-monitor-secret";
6861        let (status, _) = post_json_with_headers(
6862            &app,
6863            "/v1/chat/completions",
6864            serde_json::json!({
6865                "model": "x",
6866                "messages": [{"role": "user", "content": "hi"}],
6867                "max_tokens": 2
6868            }),
6869            &[
6870                ("authorization", &format!("Bearer {key}")),
6871                ("x-frink-client", "frink-studio"),
6872            ],
6873        )
6874        .await;
6875        assert_eq!(status, StatusCode::OK);
6876
6877        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6878        let row = stats["recent"].as_array().unwrap()[0].clone();
6879        let fingerprint = row["via_api_key"]
6880            .as_str()
6881            .expect("the row names the key that served it")
6882            .to_string();
6883        assert_eq!(fingerprint, attribution::key_fingerprint(key));
6884        assert!(!fingerprint.contains(key));
6885        assert!(
6886            !serde_json::to_string(&stats).unwrap().contains(key),
6887            "the stats payload must not carry the key in any form"
6888        );
6889        assert_eq!(row["client"], "frink-studio");
6890    }
6891
6892    /// Two different keys are two different callers, and no key at all
6893    /// is a third answer -- not a copy of either.
6894    #[tokio::test]
6895    async fn different_keys_are_different_callers_and_no_key_is_null() {
6896        let app = test_app();
6897        let body = serde_json::json!({
6898            "model": "x",
6899            "messages": [{"role": "user", "content": "hi"}],
6900            "max_tokens": 1
6901        });
6902        for headers in [
6903            vec![("authorization", "Bearer key-one")],
6904            vec![("authorization", "Bearer key-two")],
6905            vec![],
6906        ] {
6907            let (status, _) =
6908                post_json_with_headers(&app, "/v1/chat/completions", body.clone(), &headers).await;
6909            assert_eq!(status, StatusCode::OK);
6910        }
6911
6912        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6913        let recent = stats["recent"].as_array().unwrap();
6914        assert_eq!(recent.len(), 3);
6915        let one = recent[0]["via_api_key"].as_str().unwrap();
6916        let two = recent[1]["via_api_key"].as_str().unwrap();
6917        assert_ne!(one, two, "two keys must not collapse into one caller");
6918        assert!(
6919            recent[2]["via_api_key"].is_null(),
6920            "an unauthenticated call is null, not a fingerprint of nothing"
6921        );
6922        assert!(recent[2]["client"].is_null());
6923    }
6924
6925    /// The row names the model that SERVED the request. `req.model` is
6926    /// ignored by this server -- it decodes against whatever is loaded
6927    /// -- so echoing that string back would make the log agree with the
6928    /// caller's belief instead of with what happened.
6929    #[tokio::test]
6930    async fn a_row_names_the_model_that_served_it_not_the_one_requested() {
6931        let state = Arc::new(test_state(
6932            named_test_model("really-loaded", 256),
6933            ResponseCache::new(4, Duration::from_secs(60)),
6934        ));
6935        let app = test_app_with_state(Arc::clone(&state));
6936
6937        let (status, _) = post_json_uri(
6938            &app,
6939            "/v1/chat/completions",
6940            serde_json::json!({
6941                "model": "gpt-4-turbo-that-is-not-here",
6942                "messages": [{"role": "user", "content": "hi"}],
6943                "max_tokens": 2
6944            }),
6945        )
6946        .await;
6947        assert_eq!(status, StatusCode::OK);
6948
6949        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6950        assert_eq!(stats["recent"][0]["model"], "really-loaded");
6951
6952        // Nothing loaded: nothing served it, and the row says so rather
6953        // than repeating what the request asked for.
6954        state.swap_active(None);
6955        let (status, _) = post_json_uri(
6956            &app,
6957            "/v1/chat/completions",
6958            serde_json::json!({
6959                "model": "gpt-4-turbo-that-is-not-here",
6960                "messages": [{"role": "user", "content": "hi"}]
6961            }),
6962        )
6963        .await;
6964        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
6965        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6966        let recent = stats["recent"].as_array().unwrap();
6967        assert!(recent[recent.len() - 1]["model"].is_null());
6968    }
6969
6970    /// A streamed request names its model too, and names the handle it
6971    /// decoded against rather than whatever a swap made current while it
6972    /// was running.
6973    #[tokio::test]
6974    async fn a_streamed_row_names_the_model_it_decoded_against() {
6975        let state = Arc::new(test_state(
6976            named_test_model("model-before", 256),
6977            ResponseCache::new(4, Duration::from_secs(60)),
6978        ));
6979        let app = test_app_with_state(Arc::clone(&state));
6980        let _ = post_sse_raw(&app, resumable_request()).await;
6981        // The stream has finished; a swap now must not rewrite history.
6982        active_model(&state, "model-after");
6983
6984        let (_, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6985        assert_eq!(stats["recent"][0]["model"], "model-before");
6986    }
6987
6988    /// The queue gauge reports a queue that exists or says there is
6989    /// none. `0` would claim an empty queue was measured.
6990    #[tokio::test]
6991    async fn the_queue_gauge_is_null_when_nothing_can_queue() {
6992        let app = test_app();
6993        let (status, stats) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
6994        assert_eq!(status, StatusCode::OK);
6995        assert!(
6996            stats["queue_depth"].is_null(),
6997            "without continuous batching nothing queues, so there is nothing to measure"
6998        );
6999        assert!(stats["queue_rejected_total"].is_null());
7000        assert_eq!(
7001            stats["generating_now"], 0,
7002            "work in progress is measured and really is zero here"
7003        );
7004    }
7005
7006    /// The raw SSE body, so the tests below can assert on the `id:` and
7007    /// `retry:` fields themselves rather than only on the JSON inside
7008    /// `data:`. Those two fields are the whole of the replay contract
7009    /// on the wire.
7010    async fn post_sse_raw(app: &Router, body: serde_json::Value) -> String {
7011        post_sse_raw_uri(app, frink_api::routes::V1_CHAT_COMPLETIONS, body).await
7012    }
7013
7014    /// The same, on any route: `/completion` streams a different
7015    /// protocol over the same transport, and a second copy of this
7016    /// helper would be a second thing to keep in step.
7017    async fn post_sse_raw_uri(app: &Router, uri: &str, body: serde_json::Value) -> String {
7018        use http_body_util::BodyExt;
7019        use tower::ServiceExt;
7020
7021        let response = app
7022            .clone()
7023            .oneshot(
7024                axum::http::Request::builder()
7025                    .method("POST")
7026                    .uri(uri)
7027                    .header("content-type", "application/json")
7028                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7029                    .unwrap(),
7030            )
7031            .await
7032            .unwrap();
7033        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7034        String::from_utf8(bytes.to_vec()).unwrap()
7035    }
7036
7037    async fn get_json_with_headers(
7038        app: &Router,
7039        uri: &str,
7040        headers: &[(&str, &str)],
7041    ) -> (StatusCode, serde_json::Value) {
7042        use http_body_util::BodyExt;
7043        use tower::ServiceExt;
7044
7045        let mut builder = axum::http::Request::builder().method("GET").uri(uri);
7046        for (name, value) in headers {
7047            builder = builder.header(*name, *value);
7048        }
7049        let response = app
7050            .clone()
7051            .oneshot(builder.body(axum::body::Body::empty()).unwrap())
7052            .await
7053            .unwrap();
7054        let status = response.status();
7055        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7056        (
7057            status,
7058            serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({})),
7059        )
7060    }
7061
7062    fn sse_field<'a>(body: &'a str, field: &str) -> Vec<&'a str> {
7063        body.lines()
7064            .filter_map(|line| line.strip_prefix(field))
7065            .map(str::trim)
7066            .collect()
7067    }
7068
7069    fn resumable_request() -> serde_json::Value {
7070        serde_json::json!({
7071            "model": "m",
7072            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
7073            "max_tokens": 4,
7074            "temperature": 0,
7075            "stream": true,
7076            "stream_resumable": true,
7077        })
7078    }
7079
7080    /// The wire half of the replay contract: every event is numbered,
7081    /// the numbers are qualified by the request so a `Last-Event-ID`
7082    /// cannot be mistaken for a position in another stream, and the
7083    /// reconnect delay is stated once.
7084    #[tokio::test]
7085    async fn a_resumable_stream_numbers_every_event_and_states_retry_once() {
7086        let app = test_app();
7087        let body = post_sse_raw(&app, resumable_request()).await;
7088
7089        let request_id = body
7090            .lines()
7091            .find_map(|l| l.strip_prefix("data: "))
7092            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
7093            .and_then(|v| v["request_id"].as_str().map(str::to_string))
7094            .expect("the first chunk names the request");
7095
7096        let ids = sse_field(&body, "id:");
7097        let datas = sse_field(&body, "data:");
7098        assert_eq!(
7099            ids.len(),
7100            datas.len(),
7101            "every event carries an id, or a reconnect cannot name where it stopped"
7102        );
7103        for (i, id) in ids.iter().enumerate() {
7104            assert_eq!(*id, format!("{request_id}:{i}"));
7105        }
7106        let retries = sse_field(&body, "retry:");
7107        assert_eq!(
7108            retries.len(),
7109            1,
7110            "the reconnect delay is stated once, not on every event"
7111        );
7112        assert_eq!(retries[0], "1500");
7113        assert!(
7114            body.contains("data: [DONE]"),
7115            "the end of stream is still stated"
7116        );
7117    }
7118
7119    /// The refusal this feature was written around: an `id:` with no
7120    /// replay buffer behind it tells a client it may reconnect into
7121    /// something that does not exist.
7122    #[tokio::test]
7123    async fn a_plain_stream_carries_no_id_because_nothing_could_replay_it() {
7124        let app = test_app();
7125        let mut request = resumable_request();
7126        request["stream_resumable"] = serde_json::json!(false);
7127        let body = post_sse_raw(&app, request).await;
7128        assert!(!sse_field(&body, "data:").is_empty(), "it still streams");
7129        assert!(
7130            sse_field(&body, "id:").is_empty(),
7131            "an id promises a replay this stream cannot serve"
7132        );
7133        assert!(sse_field(&body, "retry:").is_empty());
7134    }
7135
7136    /// The polling fallback, which is the answer to the proxy that
7137    /// buffers `text/event-stream`: the same events, over a short JSON
7138    /// response nothing can hold back.
7139    #[tokio::test]
7140    async fn the_polling_fallback_serves_exactly_what_the_stream_delivered() {
7141        let app = test_app();
7142        let body = post_sse_raw(&app, resumable_request()).await;
7143        let request_id = sse_field(&body, "id:")[0]
7144            .rsplit_once(':')
7145            .unwrap()
7146            .0
7147            .to_string();
7148        let streamed: Vec<String> = sse_field(&body, "data:")
7149            .iter()
7150            .map(|d| d.to_string())
7151            .collect();
7152
7153        let (status, polled) = get_json(
7154            &app,
7155            &format!("{}?from=0", frink_api::routes::v1_stream_poll(&request_id)),
7156        )
7157        .await;
7158        assert_eq!(status, StatusCode::OK);
7159        let events: Vec<String> = polled["events"]
7160            .as_array()
7161            .unwrap()
7162            .iter()
7163            .map(|e| e["data"].as_str().unwrap().to_string())
7164            .collect();
7165        assert_eq!(
7166            events, streamed,
7167            "the fallback must deliver the same answer, not a re-run of it"
7168        );
7169        assert_eq!(polled["request_id"], request_id);
7170        assert_eq!(
7171            polled["done"], false,
7172            "events were still being handed out, so the client must ask again"
7173        );
7174
7175        // Drained: only now is it done, so a client that stops on
7176        // `done` never discards events it was not given.
7177        let next = polled["next_index"].as_u64().unwrap();
7178        let (_, drained) = get_json(
7179            &app,
7180            &format!(
7181                "{}?from={next}",
7182                frink_api::routes::v1_stream_poll(&request_id)
7183            ),
7184        )
7185        .await;
7186        assert_eq!(drained["done"], true);
7187        assert_eq!(drained["events"].as_array().unwrap().len(), 0);
7188    }
7189
7190    /// A resume returns what was missed and not what was already
7191    /// rendered -- repeating delivered tokens would make replay worse
7192    /// than starting over.
7193    #[tokio::test]
7194    async fn a_resume_continues_after_the_last_event_id_rather_than_repeating() {
7195        let app = test_app();
7196        let body = post_sse_raw(&app, resumable_request()).await;
7197        let ids = sse_field(&body, "id:");
7198        let datas: Vec<String> = sse_field(&body, "data:")
7199            .iter()
7200            .map(|d| d.to_string())
7201            .collect();
7202        assert!(
7203            ids.len() >= 3,
7204            "need a few events to resume into the middle"
7205        );
7206        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
7207
7208        let (status, resumed) = get_json_with_headers(
7209            &app,
7210            &format!("{}/poll", frink_api::routes::v1_stream(&request_id)),
7211            &[],
7212        )
7213        .await;
7214        assert_eq!(status, StatusCode::OK);
7215        assert_eq!(resumed["events"].as_array().unwrap().len(), datas.len());
7216
7217        // Now from the middle, the way a reconnect would.
7218        let (_, tail) = get_json(
7219            &app,
7220            &format!("{}?from=2", frink_api::routes::v1_stream_poll(&request_id)),
7221        )
7222        .await;
7223        let tail_events: Vec<String> = tail["events"]
7224            .as_array()
7225            .unwrap()
7226            .iter()
7227            .map(|e| e["data"].as_str().unwrap().to_string())
7228            .collect();
7229        assert_eq!(tail_events, datas[2..].to_vec());
7230    }
7231
7232    /// Reconnecting over SSE picks up where the last id left off, with
7233    /// the ids still attached so a second drop can be resumed too.
7234    #[tokio::test]
7235    async fn an_sse_reconnect_resumes_from_the_last_event_id() {
7236        use http_body_util::BodyExt;
7237        use tower::ServiceExt;
7238
7239        let app = test_app();
7240        let body = post_sse_raw(&app, resumable_request()).await;
7241        let ids = sse_field(&body, "id:");
7242        let datas: Vec<String> = sse_field(&body, "data:")
7243            .iter()
7244            .map(|d| d.to_string())
7245            .collect();
7246        let request_id = ids[0].rsplit_once(':').unwrap().0.to_string();
7247
7248        let response = app
7249            .clone()
7250            .oneshot(
7251                axum::http::Request::builder()
7252                    .method("GET")
7253                    .uri(frink_api::routes::v1_stream(&request_id))
7254                    .header("last-event-id", format!("{request_id}:0"))
7255                    .body(axum::body::Body::empty())
7256                    .unwrap(),
7257            )
7258            .await
7259            .unwrap();
7260        assert_eq!(response.status(), StatusCode::OK);
7261        assert_eq!(
7262            response
7263                .headers()
7264                .get("x-accel-buffering")
7265                .and_then(|v| v.to_str().ok()),
7266            Some("no"),
7267            "the reconnect needs the same anti-buffering header as the stream"
7268        );
7269        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7270        let resumed = String::from_utf8(bytes.to_vec()).unwrap();
7271        assert_eq!(
7272            sse_field(&resumed, "data:")
7273                .iter()
7274                .map(|d| d.to_string())
7275                .collect::<Vec<_>>(),
7276            datas[1..].to_vec()
7277        );
7278        assert_eq!(sse_field(&resumed, "id:")[0], format!("{request_id}:1"));
7279    }
7280
7281    /// A `Last-Event-ID` from another stream is refused rather than
7282    /// rounded down to zero: replaying a whole different answer would
7283    /// be a silent, confident lie.
7284    #[tokio::test]
7285    async fn a_last_event_id_from_another_stream_is_refused() {
7286        let app = test_app();
7287        let body = post_sse_raw(&app, resumable_request()).await;
7288        let request_id = sse_field(&body, "id:")[0]
7289            .rsplit_once(':')
7290            .unwrap()
7291            .0
7292            .to_string();
7293
7294        let (status, err) = get_json_with_headers(
7295            &app,
7296            &frink_api::routes::v1_stream(&request_id),
7297            &[("last-event-id", "chatcmpl-someone-else:3")],
7298        )
7299        .await;
7300        assert_eq!(status, StatusCode::BAD_REQUEST);
7301        assert_eq!(err["error"]["code"], "bad_last_event_id");
7302    }
7303
7304    /// A stream that was never resumable, or has been forgotten, is a
7305    /// 404 that says which -- not an empty stream that reads as an
7306    /// answer with no tokens in it.
7307    #[tokio::test]
7308    async fn resuming_a_stream_that_was_never_resumable_is_a_404_that_says_why() {
7309        let app = test_app();
7310        let mut request = resumable_request();
7311        request["stream_resumable"] = serde_json::json!(false);
7312        let body = post_sse_raw(&app, request).await;
7313        let request_id = body
7314            .lines()
7315            .find_map(|l| l.strip_prefix("data: "))
7316            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok())
7317            .and_then(|v| v["request_id"].as_str().map(str::to_string))
7318            .unwrap();
7319
7320        let (status, err) = get_json(&app, &frink_api::routes::v1_stream_poll(&request_id)).await;
7321        assert_eq!(status, StatusCode::NOT_FOUND);
7322        assert_eq!(err["error"]["code"], "stream_not_found");
7323        assert!(err["error"]["message"]
7324            .as_str()
7325            .unwrap()
7326            .contains("stream_resumable"));
7327    }
7328
7329    /// The published template and the router's pattern must describe
7330    /// the same path, or a client built from `frink_api::routes` asks
7331    /// for something this server does not serve.
7332    #[test]
7333    fn the_axum_stream_patterns_match_the_published_templates() {
7334        assert_eq!(
7335            axum_path(frink_api::routes::V1_STREAM),
7336            "/v1/stream/:request_id"
7337        );
7338        assert_eq!(
7339            axum_path(frink_api::routes::V1_STREAM_POLL),
7340            "/v1/stream/:request_id/poll"
7341        );
7342        assert_eq!(
7343            frink_api::routes::v1_stream("abc"),
7344            axum_path(frink_api::routes::V1_STREAM).replace(":request_id", "abc")
7345        );
7346    }
7347
7348    /// Every published template goes through the converter, and what
7349    /// comes out has no braces left in it.
7350    ///
7351    /// The two Responses routes were mounted raw, so axum matched the
7352    /// literal segment `{response_id}` and a real id fell through to a
7353    /// bodiless 404. The test router had the same two lines, which is
7354    /// why nothing caught it. This walks the templates instead of
7355    /// naming them, so the next one added is covered without anybody
7356    /// remembering to come back here.
7357    #[test]
7358    fn no_published_template_reaches_the_router_with_its_braces() {
7359        for template in [
7360            frink_api::routes::V1_STREAM,
7361            frink_api::routes::V1_STREAM_POLL,
7362            frink_api::routes::V1_RESPONSE,
7363            frink_api::routes::V1_RESPONSE_CANCEL,
7364            frink_api::routes::ADMIN_TASK_CANCEL,
7365        ] {
7366            assert!(
7367                template.contains('{'),
7368                "{template} is in the template list but has no placeholder"
7369            );
7370            let mounted = axum_path(template);
7371            assert!(
7372                !mounted.contains('{') && !mounted.contains('}'),
7373                "{template} would be mounted as {mounted}, whose braces axum reads as a literal segment"
7374            );
7375            assert!(
7376                mounted.contains(':'),
7377                "{template} lost its placeholder entirely and would match one path only"
7378            );
7379        }
7380    }
7381
7382    /// A real id must reach the handler, not axum's catch-all 404.
7383    ///
7384    /// The distinction is the whole point: axum answers an unmatched
7385    /// path with an empty body, while the handler answers an unknown id
7386    /// with a reasoned JSON error. Asserting on the body rather than
7387    /// the status is what separates "the route is missing" from "the
7388    /// response is not here".
7389    #[tokio::test]
7390    async fn an_unknown_response_id_gets_the_handler_not_a_bare_404() {
7391        let app = test_app();
7392        let (status, body) = get_json(&app, "/v1/responses/resp_nonexistent").await;
7393        assert_eq!(status, StatusCode::NOT_FOUND);
7394        assert!(
7395            !body.is_null(),
7396            "empty body means axum never matched the route, so the id was read as a literal segment"
7397        );
7398    }
7399
7400    /// An empty task list is a list, not a missing key -- the UI renders
7401    /// "no jobs" from it rather than from an error.
7402    #[tokio::test]
7403    async fn the_task_list_starts_empty_rather_than_absent() {
7404        let app = test_app();
7405        let (status, body) = get_json(&app, frink_api::routes::ADMIN_TASKS).await;
7406        assert_eq!(status, StatusCode::OK);
7407        assert_eq!(body["tasks"].as_array().unwrap().len(), 0);
7408    }
7409
7410    /// The slots route exists, is reachable, and refuses by naming the
7411    /// flag that would turn it on -- rather than 404ing, which is what
7412    /// an unregistered route would do and is indistinguishable from
7413    /// "this build has no slots".
7414    ///
7415    /// The condition is reachable by default: `FRINK_SLOT_SAVE_PATH`
7416    /// is unset unless an operator passes `--slot-save-path`, so this
7417    /// is the answer every stock server gives.
7418    #[tokio::test]
7419    async fn the_slots_route_is_registered_and_refuses_by_naming_slot_save_path() {
7420        assert!(
7421            std::env::var("FRINK_SLOT_SAVE_PATH").is_err(),
7422            "this test asserts the unconfigured behaviour"
7423        );
7424        let app = test_app();
7425        let (status, body) = post_json_uri(
7426            &app,
7427            &format!("{}?action=save", frink_api::routes::slots_id(0)),
7428            serde_json::json!({"filename": "sys.fslot", "prompt": "hi"}),
7429        )
7430        .await;
7431        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
7432        assert!(
7433            body["error"]["message"]
7434                .as_str()
7435                .unwrap()
7436                .contains("--slot-save-path"),
7437            "{body}"
7438        );
7439    }
7440
7441    pub(crate) async fn post_json_uri(
7442        app: &Router,
7443        uri: &str,
7444        body: serde_json::Value,
7445    ) -> (StatusCode, serde_json::Value) {
7446        use http_body_util::BodyExt;
7447        use tower::ServiceExt;
7448
7449        let response = app
7450            .clone()
7451            .oneshot(
7452                axum::http::Request::builder()
7453                    .method("POST")
7454                    .uri(uri)
7455                    .header("content-type", "application/json")
7456                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7457                    .unwrap(),
7458            )
7459            .await
7460            .unwrap();
7461        let status = response.status();
7462        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7463        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
7464        (status, json)
7465    }
7466
7467    /// The GET twin of [`post_json_uri`], for the routes that report
7468    /// state rather than change it.
7469    pub(crate) async fn get_json_uri(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
7470        use http_body_util::BodyExt;
7471        use tower::ServiceExt;
7472
7473        let response = app
7474            .clone()
7475            .oneshot(
7476                axum::http::Request::builder()
7477                    .method("GET")
7478                    .uri(uri)
7479                    .body(axum::body::Body::empty())
7480                    .unwrap(),
7481            )
7482            .await
7483            .unwrap();
7484        let status = response.status();
7485        let bytes = response.into_body().collect().await.unwrap().to_bytes();
7486        let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::json!({}));
7487        (status, json)
7488    }
7489
7490    async fn post_json(app: &Router, body: serde_json::Value) -> serde_json::Value {
7491        post_json_uri(app, "/v1/chat/completions", body).await.1
7492    }
7493
7494    /// The engine's live footprint, beside the budget it was sized
7495    /// against. Two things are asserted rather than the number itself,
7496    /// which is a property of the host: it is never a ZERO (an engine
7497    /// using no memory is not a thing that happens, so a zero would be
7498    /// a failed read presented as a fact), and it always says WHICH
7499    /// quantity it is -- a caller comparing a PSS figure with an RSS
7500    /// one is comparing two different things and will read the
7501    /// difference as a leak.
7502    #[tokio::test]
7503    async fn stats_says_what_the_engine_is_using_and_which_quantity_that_is() {
7504        let app = test_app();
7505        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
7506        assert_eq!(status, StatusCode::OK);
7507
7508        let memory = &body["memory"];
7509        if memory.is_null() {
7510            // No `/proc`: absent is the honest answer, and the point of
7511            // this branch is that it is absent rather than zero.
7512            return;
7513        }
7514        assert!(
7515            memory["bytes"].as_u64().is_some_and(|b| b > 0),
7516            "a read that produced a zero is a broken read, not an idle \
7517             engine: {memory}"
7518        );
7519        assert!(
7520            ["pss", "rss"].contains(&memory["kind"].as_str().unwrap_or("")),
7521            "the quantity must travel with the number: {memory}"
7522        );
7523    }
7524
7525    /// A pool this deployment does not have is reported `null`, never
7526    /// as a zero row. "No window pool" and "a window pool with nothing
7527    /// in it" are different facts, and an operator shown the second for
7528    /// the first sizes against a pool that does not exist. The test
7529    /// state runs with no shared KV pool, so all three are absent here.
7530    #[tokio::test]
7531    async fn stats_reports_a_pool_it_does_not_have_as_absent_and_not_as_zero() {
7532        let app = test_app();
7533        let (status, body) = get_json(&app, frink_api::routes::V1_STATS).await;
7534        assert_eq!(status, StatusCode::OK);
7535        for pool in ["kv_pages", "window_slots", "state_slots"] {
7536            assert!(
7537                body["pools"][pool].is_null(),
7538                "{pool} must be null rather than a zero row: {}",
7539                body["pools"]
7540            );
7541        }
7542    }
7543
7544    /// A streamed `/v1/messages` can be cancelled only if the client
7545    /// can learn the id, and the Anthropic protocol has no field for
7546    /// it -- the `message_start` `msg_...` is a different identifier
7547    /// the cancel registry has never seen. So the header carries it,
7548    /// on the success path and on the error path alike, because a
7549    /// client that logs one id per call should not lose it exactly
7550    /// when something went wrong.
7551    #[tokio::test]
7552    async fn a_messages_response_states_the_id_that_v1_cancel_takes() {
7553        use http_body_util::BodyExt;
7554        use tower::ServiceExt;
7555
7556        let app = test_app();
7557        let send = |body: serde_json::Value| {
7558            let app = app.clone();
7559            async move {
7560                app.oneshot(
7561                    axum::http::Request::builder()
7562                        .method("POST")
7563                        .uri(frink_api::routes::V1_MESSAGES)
7564                        .header("content-type", "application/json")
7565                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
7566                        .unwrap(),
7567                )
7568                .await
7569                .unwrap()
7570            }
7571        };
7572
7573        let ok = send(serde_json::json!({
7574            "model": "test",
7575            "max_tokens": 1,
7576            "messages": [{"role": "user", "content": "hi"}],
7577        }))
7578        .await;
7579        assert_eq!(ok.status(), StatusCode::OK);
7580        let id = ok
7581            .headers()
7582            .get("request-id")
7583            .expect("a served message names its id")
7584            .to_str()
7585            .unwrap()
7586            .to_string();
7587        assert!(!id.is_empty());
7588
7589        // A rejected body still gets one, and a different one: two calls
7590        // must never collide in the ring.
7591        let bad = send(serde_json::json!({"model": "test"})).await;
7592        assert!(bad.status().is_client_error());
7593        let other = bad.headers().get("request-id").expect("errors too");
7594        assert_ne!(other.to_str().unwrap(), id);
7595        let _ = bad.into_body().collect().await.unwrap();
7596    }
7597
7598    /// The gate is the point of the rebuild endpoint: a request that
7599    /// arrives while the KV pool is being re-split must be refused,
7600    /// because admitting it would let a decode allocate out of a pool
7601    /// whose block count is about to change under it. `503` and not
7602    /// `500` -- the caller should retry in a moment, and the body says
7603    /// which of the four closed states it hit so a client can tell
7604    /// "not yet" from "not ever".
7605    #[tokio::test]
7606    async fn a_request_that_arrives_mid_rebuild_is_refused_and_admitted_again_after() {
7607        let state = Arc::new(test_state(
7608            test_model_full_byte_vocab(),
7609            ResponseCache::new(1000, Duration::from_secs(3600)),
7610        ));
7611        let app = test_app_with_state(Arc::clone(&state));
7612        let body = serde_json::json!({
7613            "model": "test",
7614            "messages": [{"role": "user", "content": "hi"}],
7615            "max_tokens": 1,
7616        });
7617
7618        state
7619            .maintenance
7620            .lock()
7621            .unwrap()
7622            .begin_rebuild()
7623            .expect("a fresh server is serving, so the rebuild starts");
7624        let (status, refused) = post_json_uri(&app, "/v1/chat/completions", body.clone()).await;
7625        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
7626        assert_eq!(refused["error"]["type"], "cache_rebuilding");
7627
7628        state.maintenance.lock().unwrap().finish_rebuild(true);
7629        let (status, _) = post_json_uri(&app, "/v1/chat/completions", body).await;
7630        assert_eq!(
7631            status,
7632            StatusCode::OK,
7633            "the gate reopens; a rebuild is not a latch"
7634        );
7635    }
7636
7637    /// Cancelling an id that is not generating must not answer `200`.
7638    /// A UI told "ok" for an already-finished request would report that
7639    /// it stopped work it did not stop, and the two outcomes are the
7640    /// only thing this endpoint exists to distinguish.
7641    #[tokio::test]
7642    async fn cancelling_an_id_that_is_not_generating_is_a_404_that_says_so() {
7643        let app = test_app();
7644        let (status, body) = post_json_uri(
7645            &app,
7646            frink_api::routes::V1_CANCEL,
7647            serde_json::json!({ "request_id": "chatcmpl-never-issued" }),
7648        )
7649        .await;
7650        assert_eq!(status, StatusCode::NOT_FOUND);
7651        assert_eq!(body["cancelled"], serde_json::json!(false));
7652        assert_eq!(body["request_id"], "chatcmpl-never-issued");
7653        assert!(
7654            body["detail"].as_str().is_some_and(|d| !d.is_empty()),
7655            "the verdict must carry a human reason: {body}"
7656        );
7657    }
7658
7659    /// The endpoint reaches the registry the streaming path registers
7660    /// into -- not a second, parallel one. Registered by hand here
7661    /// because a `oneshot` router cannot hold a stream open.
7662    #[tokio::test]
7663    async fn cancelling_a_live_generation_signals_its_token_and_answers_200() {
7664        let state = Arc::new(test_state(
7665            test_model_full_byte_vocab(),
7666            ResponseCache::new(1000, Duration::from_secs(3600)),
7667        ));
7668        let app = test_app_with_state(Arc::clone(&state));
7669        let (token, _guard) = state.cancels.register("chatcmpl-live");
7670
7671        let (status, before) = get_json(&app, frink_api::routes::ADMIN_STATS).await;
7672        assert_eq!(status, StatusCode::OK);
7673        assert_eq!(before["generating_now"], serde_json::json!(1));
7674
7675        let (status, body) = post_json_uri(
7676            &app,
7677            frink_api::routes::V1_CANCEL,
7678            serde_json::json!({ "request_id": "chatcmpl-live" }),
7679        )
7680        .await;
7681        assert_eq!(status, StatusCode::OK);
7682        assert_eq!(body["cancelled"], serde_json::json!(true));
7683        assert!(
7684            token.is_cancelled(),
7685            "the endpoint answered ok without setting the flag the decode loop reads"
7686        );
7687    }
7688
7689    #[tokio::test]
7690    async fn tokenize_detokenize_roundtrip_and_embeddings_mean() {
7691        let app = test_app();
7692        let (status, tok) =
7693            post_json_uri(&app, "/v1/tokenize", serde_json::json!({ "prompt": "Hi" })).await;
7694        assert_eq!(status, StatusCode::OK);
7695        let tokens = tok["tokens"].as_array().unwrap();
7696        assert_eq!(tok["count"], tokens.len());
7697        assert!(!tokens.is_empty());
7698
7699        let (status, detok) = post_json_uri(
7700            &app,
7701            "/v1/detokenize",
7702            serde_json::json!({ "tokens": tokens }),
7703        )
7704        .await;
7705        assert_eq!(status, StatusCode::OK);
7706        assert_eq!(detok["text"], "Hi");
7707
7708        let (status, emb) = post_json_uri(
7709            &app,
7710            "/v1/embeddings",
7711            serde_json::json!({
7712                "input": "Hi",
7713                "embedding_type": "mean"
7714            }),
7715        )
7716        .await;
7717        assert_eq!(status, StatusCode::OK);
7718        let vec = emb["data"][0]["embedding"].as_array().unwrap();
7719        assert!(!vec.is_empty());
7720        assert!(vec.iter().all(|v| v.as_f64().is_some()));
7721    }
7722
7723    /// The decoder path's accepted `embedding_type` set must not have
7724    /// widened when the encoder path arrived: `cls` is row 0 of a
7725    /// decoder's hidden states, which is its BOS position and means
7726    /// nothing, so it stays refused here and the refusal names what is
7727    /// accepted.
7728    #[tokio::test]
7729    async fn the_decoder_path_still_refuses_a_pooling_it_cannot_mean() {
7730        let app = test_app();
7731        let (status, body) = post_json_uri(
7732            &app,
7733            "/v1/embeddings",
7734            serde_json::json!({ "input": "Hi", "embedding_type": "cls" }),
7735        )
7736        .await;
7737        assert_eq!(status, StatusCode::BAD_REQUEST);
7738        let msg = body["error"]["message"].as_str().unwrap();
7739        assert!(msg.contains("mean") && msg.contains("last"), "{msg}");
7740    }
7741
7742    /// A real BGE checkpoint served through the route: CLS by default
7743    /// because the file says `pooling_type = 2`, 384 dims, unit norm,
7744    /// and `usage.prompt_tokens` counting the `[CLS]`/`[SEP]` the model
7745    /// actually saw.
7746    #[tokio::test]
7747    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
7748    async fn a_real_embedding_model_serves_v1_embeddings() {
7749        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7750            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
7751        if !path.exists() {
7752            eprintln!("SKIP: {} not present", path.display());
7753            return;
7754        }
7755        let encoder = frink_models::EmbeddingModel::from_gguf_path(&path).expect("load bge");
7756        let mut state = test_state(
7757            test_model_full_byte_vocab(),
7758            ResponseCache::new(1000, Duration::from_secs(3600)),
7759        );
7760        state.embedding = Some(Arc::new(encoder));
7761        let app = test_app_with_state(Arc::new(state));
7762
7763        let (status, body) = post_json_uri(
7764            &app,
7765            "/v1/embeddings",
7766            serde_json::json!({ "input": ["Hello world", "a second input"] }),
7767        )
7768        .await;
7769        assert_eq!(status, StatusCode::OK, "{body}");
7770        assert_eq!(body["model"], "bge-small-en-v1.5");
7771        let data = body["data"].as_array().unwrap();
7772        assert_eq!(data.len(), 2);
7773        for (i, row) in data.iter().enumerate() {
7774            assert_eq!(row["index"], i);
7775            let v: Vec<f64> = row["embedding"]
7776                .as_array()
7777                .unwrap()
7778                .iter()
7779                .map(|x| x.as_f64().unwrap())
7780                .collect();
7781            assert_eq!(v.len(), 384, "the encoder\'s width, not the decoder\'s");
7782            let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
7783            assert!((norm - 1.0).abs() < 1e-4, "not L2-normalized: {norm}");
7784        }
7785        // "Hello world" is [CLS] hello world [SEP] = 4, and the second
7786        // input adds its own two specials.
7787        assert!(body["usage"]["prompt_tokens"].as_u64().unwrap() >= 4 + 2);
7788
7789        // The default came from the file. Asking for MEAN must give a
7790        // different vector, which is what proves CLS was not a
7791        // coincidence of this input.
7792        let (status, mean) = post_json_uri(
7793            &app,
7794            "/v1/embeddings",
7795            serde_json::json!({ "input": "Hello world", "embedding_type": "mean" }),
7796        )
7797        .await;
7798        assert_eq!(status, StatusCode::OK);
7799        assert_ne!(mean["data"][0]["embedding"], data[0]["embedding"]);
7800    }
7801
7802    /// The same BGE checkpoint as `FRINK_MODEL_PATH` -- the *loaded*
7803    /// model, not a side-car.
7804    ///
7805    /// Four claims, and the third is the one this whole seam exists
7806    /// for: the loader routes an encoder-only GGUF away from every
7807    /// decoder path, `/v1/embeddings` serves it, `/v1/chat/completions`
7808    /// refuses it NAMING IT AS AN EMBEDDING MODEL (before this, the
7809    /// same file died in `tokenizer_from_gguf` with a message about
7810    /// WordPiece being unreadable -- true, and the wrong thing to send
7811    /// a user after), and `/v1/models` says which endpoint it is for so
7812    /// a client need not send a request to find out.
7813    #[tokio::test]
7814    #[ignore = "needs models/bge-small-en-v1.5-q8_0.gguf"]
7815    async fn an_encoder_can_be_the_loaded_model() {
7816        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7817            .join("../../models/bge-small-en-v1.5-q8_0.gguf");
7818        if !path.exists() {
7819            eprintln!("SKIP: {} not present", path.display());
7820            return;
7821        }
7822
7823        // Through the real `FRINK_MODEL_PATH` loader, not by
7824        // constructing an `EmbeddingModel` directly: the routing
7825        // decision is half of what is under test.
7826        let loaded = model::load_from_path(path.to_str().unwrap()).expect("load bge as the model");
7827        assert!(
7828            matches!(loaded, model::LoadedModel::Encoder(_)),
7829            "an encoder-only GGUF reached a decoder loader"
7830        );
7831        let (loaded, batcher, ceiling) = activate_loaded_model(loaded, true, None, None);
7832        assert!(
7833            matches!(loaded, Loaded::Encoder(_)),
7834            "the encoder did not stay an encoder through activation"
7835        );
7836        assert!(
7837            batcher.is_none() && ceiling.is_none(),
7838            "an encoder was given a decode batcher or a KV ceiling it has no use for"
7839        );
7840
7841        let state = test_state(
7842            test_model_full_byte_vocab(),
7843            ResponseCache::new(1000, Duration::from_secs(3600)),
7844        );
7845        state.swap_active(Some(Arc::new(ActiveModel {
7846            id: None,
7847            loaded,
7848            batcher,
7849            ceiling,
7850            checkpoint_path: None,
7851        })));
7852        let app = test_app_with_state(Arc::new(state));
7853
7854        // 1. It embeds.
7855        let (status, body) = post_json_uri(
7856            &app,
7857            "/v1/embeddings",
7858            serde_json::json!({ "input": "Hello world" }),
7859        )
7860        .await;
7861        assert_eq!(status, StatusCode::OK, "{body}");
7862        assert_eq!(body["model"], "bge-small-en-v1.5");
7863        let v = body["data"][0]["embedding"].as_array().unwrap();
7864        assert_eq!(v.len(), 384, "the encoder's width, not the decoder's");
7865
7866        // 2. It refuses to chat, by name.
7867        let (status, body) = post_json_uri(
7868            &app,
7869            "/v1/chat/completions",
7870            serde_json::json!({
7871                "model": "bge-small-en-v1.5",
7872                "messages": [{"role": "user", "content": "hi"}],
7873            }),
7874        )
7875        .await;
7876        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}");
7877        let msg = body["error"]["message"].as_str().unwrap();
7878        for fact in [
7879            "bge-small-en-v1.5",
7880            "bert",
7881            "embedding model",
7882            "/v1/embeddings",
7883        ] {
7884            assert!(msg.contains(fact), "the refusal does not say {fact}: {msg}");
7885        }
7886
7887        // 3. `/v1/models` lists it as what it is.
7888        let (status, models) = get_json(&app, frink_api::routes::V1_MODELS).await;
7889        assert_eq!(status, StatusCode::OK);
7890        let entry = &models["data"][0];
7891        assert_eq!(entry["id"], "bge-small-en-v1.5");
7892        assert_eq!(entry["frink_model_kind"], "embedding");
7893        assert_eq!(entry["frink_tokenizer"], "gguf-wordpiece");
7894        assert_eq!(entry["frink_n_embd"], 384);
7895        assert_eq!(entry["frink_pooling"], "CLS");
7896        assert_eq!(
7897            entry["frink_endpoints"],
7898            serde_json::json!(["/v1/embeddings"])
7899        );
7900        // A reasoning-gear field here would be an invented answer about
7901        // a template the checkpoint does not have.
7902        assert!(entry.get("supported_reasoning_efforts").is_none());
7903
7904        // 4. `/health` is ready, and says which endpoint is ready.
7905        let (status, health) = get_json(&app, frink_api::routes::HEALTH).await;
7906        assert_eq!(status, StatusCode::OK, "an encoder is a loaded model");
7907        assert_eq!(health["model"]["id"], "bge-small-en-v1.5");
7908        assert_eq!(health["model"]["synthetic_weights"], false);
7909        let weights = health["capabilities"]
7910            .as_array()
7911            .unwrap()
7912            .iter()
7913            .find(|c| c["id"] == frink_api::health::capability::REAL_WEIGHTS)
7914            .expect("a real-weights capability row");
7915        let detail = weights["detail"].as_str().unwrap_or_default();
7916        assert!(detail.contains("ENCODER"), "{detail}");
7917        // 5. It tokenizes, and round-trips. An embedding model's whole
7918        // contract is the vector it returns for a string, so when that
7919        // vector surprises you the first question is what tokens it
7920        // actually saw. These routes used to go through
7921        // `generative()?` and answer 501 "not a generative model",
7922        // which left no way to ask without loading the checkpoint in a
7923        // second tool (issue #28).
7924        let (status, body) = post_json_uri(
7925            &app,
7926            frink_api::routes::V1_TOKENIZE,
7927            serde_json::json!({ "content": "hello world" }),
7928        )
7929        .await;
7930        assert_eq!(
7931            status,
7932            StatusCode::OK,
7933            "an encoder has a real tokenizer: {body}"
7934        );
7935        let tokens = body["tokens"].as_array().expect("tokens array").clone();
7936        assert!(!tokens.is_empty(), "WordPiece produced nothing: {body}");
7937
7938        let (status, body) = post_json_uri(
7939            &app,
7940            frink_api::routes::V1_DETOKENIZE,
7941            serde_json::json!({ "tokens": tokens }),
7942        )
7943        .await;
7944        assert_eq!(status, StatusCode::OK, "{body}");
7945        let round_tripped = body["content"].as_str().expect("content").to_string();
7946        assert!(
7947            round_tripped.contains("hello") && round_tripped.contains("world"),
7948            "the ids did not decode back through the encoder's own vocabulary: {round_tripped}"
7949        );
7950
7951        // And the refusal that must NOT have been weakened: a decode is
7952        // still a decode, and this checkpoint still cannot do one.
7953        let (status, _) = post_json_uri(
7954            &app,
7955            "/v1/completions",
7956            serde_json::json!({ "model": "m", "prompt": "hi", "max_tokens": 1 }),
7957        )
7958        .await;
7959        assert_eq!(
7960            status,
7961            StatusCode::NOT_IMPLEMENTED,
7962            "tokenizing an encoder must not have opened a path to generating with one"
7963        );
7964    }
7965
7966    /// The /metrics endpoint must expose the bounded expert cache's
7967    /// counters when the model streams routed experts, and the
7968    /// counters must reflect real decode activity (a forward pass
7969    /// through store-backed MoE layers produces misses/hits).
7970    #[tokio::test]
7971    async fn metrics_exposes_expert_store_counters_when_streaming_is_active() {
7972        use http_body_util::BodyExt;
7973        use tower::ServiceExt;
7974
7975        let fixture = concat!(
7976            "../frink-models/tests/fixtures/",
7977            "frink_real_moe_test.gguf"
7978        );
7979        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
7980        let decoder = Decoder::from_gguf_with_expert_cache(
7981            &fixture,
7982            frink_models::config::test_moe_fixture(),
7983            Some(1024 * 1024),
7984        )
7985        .expect("MoE fixture must load store-backed");
7986
7987        // Drive one real forward pass so the store sees decode
7988        // activity (the fixture's tiny vocab can't survive the HTTP
7989        // path's template text, so decode directly).
7990        let mut caches: Vec<frink_core::cache::KvCache> = decoder.config.new_kv_caches();
7991        decoder.forward_token(1, 0, &mut caches);
7992
7993        let model = Model::Gguf(GgufModel {
7994            decoder: Arc::new(decoder),
7995            tokenizer: Arc::new(ServerTokenizer::Byte),
7996            stop_tokens: StopTokens::default(),
7997            bos_id: None,
7998            is_synthetic: false,
7999            chat_template: chat_template::PromptTemplate::plain(),
8000        });
8001        let state = Arc::new(test_state(
8002            model,
8003            ResponseCache::new(16, Duration::from_secs(60)),
8004        ));
8005        let app = Router::new()
8006            .route("/metrics", axum::routing::get(metrics))
8007            .route("/v1/chat/completions", post(chat_completions))
8008            .with_state(state);
8009
8010        let fetch_metrics = |app: Router| async move {
8011            let resp = app
8012                .oneshot(
8013                    axum::http::Request::builder()
8014                        .method("GET")
8015                        .uri("/metrics")
8016                        .body(axum::body::Body::empty())
8017                        .unwrap(),
8018                )
8019                .await
8020                .unwrap();
8021            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
8022            String::from_utf8(bytes.to_vec()).unwrap()
8023        };
8024
8025        let after = fetch_metrics(app.clone()).await;
8026        assert!(
8027            after.contains("frink_expert_cache_misses_total"),
8028            "streaming model must expose expert-cache metrics: {after}"
8029        );
8030        let misses: u64 = after
8031            .lines()
8032            .find(|l| l.starts_with("frink_expert_cache_misses_total"))
8033            .and_then(|l| l.split_whitespace().nth(1))
8034            .and_then(|v| v.parse().ok())
8035            .expect("misses metric line must parse");
8036        assert!(
8037            misses > 0,
8038            "decode must have read experts through the store: {after}"
8039        );
8040    }
8041
8042    fn weather_tool() -> serde_json::Value {
8043        serde_json::json!({
8044            "type": "function",
8045            "function": {
8046                "name": "get_weather",
8047                "description": "Get the current weather for a location.",
8048                "parameters": {
8049                    "type": "object",
8050                    "properties": {"location": {"type": "string"}},
8051                    "required": ["location"]
8052                }
8053            }
8054        })
8055    }
8056
8057    fn weather_tool_def() -> ToolDef {
8058        ToolDef {
8059            kind: "function".to_string(),
8060            function: ToolFunctionDef {
8061                name: "get_weather".to_string(),
8062                description: Some("Get the current weather for a location.".to_string()),
8063                parameters: Some(serde_json::json!({
8064                    "type": "object",
8065                    "properties": {"location": {"type": "string"}},
8066                    "required": ["location"]
8067                })),
8068            },
8069        }
8070    }
8071
8072    #[test]
8073    fn tool_preamble_mentions_every_tool_name_and_description() {
8074        let preamble = tool_preamble(&[weather_tool_def()]);
8075        assert!(preamble.contains("get_weather"));
8076        assert!(preamble.contains("Get the current weather for a location."));
8077        assert!(preamble.contains("<tool_call>"));
8078        assert!(preamble.contains("</tool_call>"));
8079    }
8080
8081    #[test]
8082    fn a_real_marker_becomes_a_structured_tool_call() {
8083        let text = "sure, let me check.<tool_call>{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}</tool_call>";
8084        let (message, finish) = build_response_message(
8085            text.to_string(),
8086            &[weather_tool_def()],
8087            output::OutputPosture::for_model("test-model"),
8088            "stop",
8089        );
8090        assert_eq!(finish, "tool_calls");
8091        let calls = message.tool_calls.expect("must carry a tool call");
8092        assert_eq!(calls[0].function.name, "get_weather");
8093        let parsed: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
8094        assert_eq!(parsed["location"], "Paris");
8095    }
8096
8097    #[test]
8098    fn a_plain_answer_is_not_promoted_to_a_tool_call() {
8099        let (message, finish) = build_response_message(
8100            "just an answer".to_string(),
8101            &[weather_tool_def()],
8102            output::OutputPosture::for_model("test-model"),
8103            "stop",
8104        );
8105        assert_eq!(finish, "stop");
8106        assert!(message.tool_calls.is_none());
8107        assert_eq!(message.content.as_deref(), Some("just an answer"));
8108    }
8109
8110    /// Malformed JSON inside the marker is not a call. Returning it as
8111    /// one would hand a client arguments it cannot parse.
8112    #[test]
8113    fn a_malformed_payload_is_not_a_tool_call() {
8114        let (message, finish) = build_response_message(
8115            "<tool_call>not valid json at all</tool_call>".to_string(),
8116            &[weather_tool_def()],
8117            output::OutputPosture::for_model("test-model"),
8118            "stop",
8119        );
8120        assert_eq!(finish, "stop");
8121        assert!(message.tool_calls.is_none());
8122    }
8123
8124    /// A call to something the request never offered is refused: the
8125    /// client would be asked to execute a tool it does not have.
8126    #[test]
8127    fn a_tool_that_was_never_offered_is_not_returned() {
8128        let (message, finish) = build_response_message(
8129            "<tool_call>{\"name\": \"ping\", \"arguments\": {}}</tool_call>".to_string(),
8130            &[weather_tool_def()],
8131            output::OutputPosture::for_model("test-model"),
8132            "stop",
8133        );
8134        assert_eq!(finish, "stop");
8135        assert!(message.tool_calls.is_none());
8136    }
8137
8138    /// With no tools offered at all, marker text is just text.
8139    #[test]
8140    fn marker_text_with_no_tools_offered_stays_content() {
8141        let (message, finish) = build_response_message(
8142            "<tool_call>{\"name\": \"get_weather\", \"arguments\": {}}</tool_call>".to_string(),
8143            &[],
8144            output::OutputPosture::for_model("test-model"),
8145            "stop",
8146        );
8147        assert_eq!(finish, "stop");
8148        assert!(message.tool_calls.is_none());
8149        assert!(message.content.is_some());
8150    }
8151
8152    /// The streaming contract a coding agent depends on: the call's
8153    /// identity arrives first, then its arguments in pieces, and the
8154    /// pieces concatenate to exactly the final arguments.
8155    #[test]
8156    fn a_streamed_call_opens_then_delivers_its_arguments_in_pieces() {
8157        let opened = std::cell::Cell::new(0usize);
8158        let mut parser = crate::policy::parser::ToolCallParser::new(
8159            crate::policy::parser::ToolCallFormat::Qwen3Coder,
8160            vec![
8161                crate::policy::parser::tool_call::ToolSchema::with_parameters(
8162                    "write_file",
8163                    serde_json::json!({"type": "object", "properties": {
8164                        "path": {"type": "string"},
8165                        "contents": {"type": "string"}
8166                    }}),
8167                ),
8168            ],
8169        );
8170        let wire = "<tool_call><function=write_file>\
8171                    <parameter=path>\n/tmp/x\n</parameter>\
8172                    <parameter=contents>\nhello world\n</parameter>\
8173                    </function></tool_call>";
8174
8175        let mut deltas = Vec::new();
8176        let mut text = String::new();
8177        for piece in wire.as_bytes().chunks(7) {
8178            let chunk = String::from_utf8_lossy(piece).into_owned();
8179            let (more_text, more) = tool_call_deltas(parser.push(&chunk), &opened);
8180            text.push_str(&more_text);
8181            deltas.extend(more);
8182        }
8183        let (more_text, more) = tool_call_deltas(parser.finish(), &opened);
8184        text.push_str(&more_text);
8185        deltas.extend(more);
8186
8187        assert_eq!(opened.get(), 1, "one call opened");
8188        assert!(text.is_empty(), "the markers are not content: {text:?}");
8189
8190        let first = &deltas[0];
8191        assert_eq!(first.index, 0);
8192        assert_eq!(first.id.as_deref(), Some("call_0"));
8193        assert_eq!(first.kind, Some("function"));
8194        assert_eq!(first.function.name.as_deref(), Some("write_file"));
8195
8196        // Everything after the opening delta is argument text only,
8197        // and it parses once concatenated.
8198        let joined: String = deltas
8199            .iter()
8200            .filter_map(|d| d.function.arguments.clone())
8201            .collect();
8202        let parsed: serde_json::Value =
8203            serde_json::from_str(&joined).expect("the fragments concatenate to valid JSON");
8204        assert_eq!(parsed["path"], serde_json::json!("/tmp/x"));
8205        assert_eq!(parsed["contents"], serde_json::json!("hello world"));
8206        assert!(
8207            deltas.len() >= 3,
8208            "the arguments arrived in pieces, not whole: {}",
8209            deltas.len()
8210        );
8211        assert!(
8212            deltas[1..].iter().all(|d| d.function.name.is_none()),
8213            "only the opening delta carries identity"
8214        );
8215    }
8216
8217    /// Text either side of a call still streams as content, in order.
8218    #[test]
8219    fn text_around_a_streamed_call_is_still_content() {
8220        let opened = std::cell::Cell::new(0usize);
8221        let mut parser = crate::policy::parser::ToolCallParser::new(
8222            crate::policy::parser::ToolCallFormat::Qwen25,
8223            vec![crate::policy::parser::tool_call::ToolSchema::new(
8224                "get_weather",
8225            )],
8226        );
8227        let wire = "let me check. <tool_call>{\"name\": \"get_weather\", \
8228                    \"arguments\": {}}</tool_call> done";
8229        let mut text = String::new();
8230        for piece in wire.as_bytes().chunks(5) {
8231            let chunk = String::from_utf8_lossy(piece).into_owned();
8232            let (more, _) = tool_call_deltas(parser.push(&chunk), &opened);
8233            text.push_str(&more);
8234        }
8235        let (more, _) = tool_call_deltas(parser.finish(), &opened);
8236        text.push_str(&more);
8237
8238        assert_eq!(opened.get(), 1);
8239        assert!(text.starts_with("let me check. "), "{text:?}");
8240        assert!(text.ends_with(" done"), "{text:?}");
8241        assert!(!text.contains("<tool_call>"), "markers leaked: {text:?}");
8242    }
8243
8244    /// A reasoning model's thinking must not be returned as its
8245    /// answer.
8246    #[test]
8247    fn a_reasoning_block_is_split_out_of_the_answer() {
8248        let (message, finish) = build_response_message(
8249            "<think>weighing it up</think>The answer is 4.".to_string(),
8250            &[],
8251            output::OutputPosture::for_model("Qwen3-8B"),
8252            "stop",
8253        );
8254        assert_eq!(finish, "stop");
8255        assert_eq!(message.content.as_deref(), Some("The answer is 4."));
8256        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
8257    }
8258
8259    /// ... and a model with no reasoning format keeps its text intact,
8260    /// markers and all.
8261    #[test]
8262    fn a_non_reasoning_model_keeps_a_literal_marker_in_its_answer() {
8263        let (message, _) = build_response_message(
8264            "Use the <think> tag like this.".to_string(),
8265            &[],
8266            output::OutputPosture::for_model("llama-3.1-8b"),
8267            "stop",
8268        );
8269        assert_eq!(
8270            message.content.as_deref(),
8271            Some("Use the <think> tag like this.")
8272        );
8273        assert!(message.reasoning_content.is_none());
8274    }
8275
8276    /// Zero-regression proof: an ordinary request with no `tools`/
8277    /// `session_id` produces the plain response shape -- `content` a
8278    /// string, no `tool_calls` field -- with an honest finish reason:
8279    /// this 4-token greedy request truncates at `max_tokens`, so
8280    /// `finish_reason` must be "length" (an earlier version hardcoded
8281    /// "stop" for every non-streaming response), and `usage` counts
8282    /// exactly the generated tokens.
8283    #[tokio::test]
8284    async fn a_request_with_no_tools_or_session_behaves_exactly_as_before() {
8285        let app = test_app();
8286        let body = serde_json::json!({
8287            "model": "m",
8288            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8289            "max_tokens": 4,
8290            "temperature": 0,
8291        });
8292        let resp = post_json(&app, body).await;
8293        let message = &resp["choices"][0]["message"];
8294        assert!(message["content"].is_string());
8295        assert!(message.get("tool_calls").is_none());
8296        assert_eq!(resp["choices"][0]["finish_reason"], "length");
8297        assert_eq!(resp["usage"]["completion_tokens"], 4);
8298        assert_eq!(
8299            resp["usage"]["total_tokens"],
8300            resp["usage"]["prompt_tokens"].as_u64().unwrap() + 4
8301        );
8302    }
8303
8304    pub(crate) async fn get_json(app: &Router, uri: &str) -> (StatusCode, serde_json::Value) {
8305        use http_body_util::BodyExt;
8306        use tower::ServiceExt;
8307
8308        let response = app
8309            .clone()
8310            .oneshot(
8311                axum::http::Request::builder()
8312                    .method("GET")
8313                    .uri(uri)
8314                    .body(axum::body::Body::empty())
8315                    .unwrap(),
8316            )
8317            .await
8318            .unwrap();
8319        let status = response.status();
8320        let bytes = response.into_body().collect().await.unwrap().to_bytes();
8321        (status, serde_json::from_slice(&bytes).unwrap())
8322    }
8323
8324    #[tokio::test]
8325    async fn health_answers_a_capability_handshake_not_a_boolean() {
8326        let app = test_app();
8327        let (status, body) = get_json(&app, frink_api::routes::HEALTH).await;
8328        assert_eq!(status, StatusCode::OK);
8329
8330        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
8331        assert_eq!(health.state, frink_api::HealthState::Ready);
8332        assert!(health.pid > 0);
8333        assert!(health.server_time_unix_ms > 0);
8334        // Nothing has been served yet: the field is absent rather than
8335        // claiming a request happened at time zero.
8336        assert_eq!(health.last_request_age_seconds, None);
8337
8338        // Every control the UI might grey out has a code it can switch
8339        // on and a sentence it can show.
8340        for id in [
8341            frink_api::health::capability::CPU,
8342            frink_api::health::capability::METAL,
8343            frink_api::health::capability::CUDA,
8344            frink_api::health::capability::REAL_WEIGHTS,
8345            frink_api::health::capability::CONTINUOUS_BATCHING,
8346        ] {
8347            let cap = health
8348                .capability(id)
8349                .unwrap_or_else(|| panic!("{id} missing"));
8350            assert!(!cap.reason.is_empty(), "{cap:?}");
8351            assert!(!cap.detail.is_empty(), "{cap:?}");
8352        }
8353        // The test app serves synthetic random weights, and health must
8354        // say so: a UI that presents noise as a model invites a bug
8355        // report about "quality".
8356        let weights = health
8357            .capability(frink_api::health::capability::REAL_WEIGHTS)
8358            .unwrap();
8359        assert!(!weights.available);
8360        assert_eq!(weights.reason, frink_api::health::reason::MODEL_NOT_LOADED);
8361        assert!(health.model.as_ref().unwrap().synthetic_weights);
8362    }
8363
8364    #[tokio::test]
8365    async fn health_vouches_for_liveness_after_a_request_has_been_served() {
8366        let app = test_app();
8367        let _ = post_json(
8368            &app,
8369            serde_json::json!({
8370                "model": "m",
8371                "messages": [{"role": "user", "content": "\u{1}"}],
8372                "max_tokens": 1,
8373                "temperature": 0,
8374            }),
8375        )
8376        .await;
8377        let (_status, body) = get_json(&app, frink_api::routes::HEALTH).await;
8378        let health: frink_api::HealthResponse = serde_json::from_value(body).unwrap();
8379        let age = health
8380            .last_request_age_seconds
8381            .expect("a served request is evidence of liveness");
8382        assert!((0.0..5.0).contains(&age), "implausible age {age}");
8383    }
8384
8385    /// Every `data:` payload of an SSE response body, `[DONE]` excluded.
8386    async fn post_sse_chunks(app: &Router, body: serde_json::Value) -> Vec<serde_json::Value> {
8387        use http_body_util::BodyExt;
8388        use tower::ServiceExt;
8389
8390        let response = app
8391            .clone()
8392            .oneshot(
8393                axum::http::Request::builder()
8394                    .method("POST")
8395                    .uri("/v1/chat/completions")
8396                    .header("content-type", "application/json")
8397                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
8398                    .unwrap(),
8399            )
8400            .await
8401            .unwrap();
8402        let bytes = response.into_body().collect().await.unwrap().to_bytes();
8403        String::from_utf8(bytes.to_vec())
8404            .unwrap()
8405            .lines()
8406            .filter_map(|line| line.strip_prefix("data: "))
8407            .filter(|payload| *payload != "[DONE]")
8408            .map(|payload| serde_json::from_str(payload).unwrap())
8409            .collect()
8410    }
8411
8412    #[tokio::test]
8413    async fn a_stream_states_its_request_id_once_in_the_first_chunk() {
8414        let app = test_app();
8415        let chunks = post_sse_chunks(
8416            &app,
8417            serde_json::json!({
8418                "model": "m",
8419                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8420                "max_tokens": 4,
8421                "temperature": 0,
8422                "stream": true,
8423            }),
8424        )
8425        .await;
8426
8427        assert!(!chunks.is_empty());
8428        let request_id = chunks[0]["request_id"]
8429            .as_str()
8430            .expect("the first chunk names the request")
8431            .to_string();
8432        assert!(request_id.starts_with("chatcmpl-"), "{request_id}");
8433        // Once, and before any content: a client that reads the id from
8434        // chunk zero never has to correlate by heuristic.
8435        for (i, chunk) in chunks.iter().enumerate().skip(1) {
8436            assert!(
8437                chunk.get("request_id").is_none(),
8438                "chunk {i} repeats request_id"
8439            );
8440        }
8441        // Every chunk of one stream carries the same `id`, and it is
8442        // that request id -- not a shared constant.
8443        for chunk in &chunks {
8444            assert_eq!(chunk["id"], serde_json::json!(request_id));
8445        }
8446
8447        let other = post_sse_chunks(
8448            &app,
8449            serde_json::json!({
8450                "model": "m",
8451                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8452                "max_tokens": 4,
8453                "temperature": 0,
8454                "stream": true,
8455            }),
8456        )
8457        .await;
8458        assert_ne!(
8459            other[0]["request_id"].as_str().unwrap(),
8460            request_id,
8461            "two concurrent chats must not share an id"
8462        );
8463    }
8464
8465    #[tokio::test]
8466    async fn a_non_streamed_response_names_the_same_request_id_as_its_completion_id() {
8467        let app = test_app();
8468        let resp = post_json(
8469            &app,
8470            serde_json::json!({
8471                "model": "m",
8472                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8473                "max_tokens": 2,
8474                "temperature": 0,
8475            }),
8476        )
8477        .await;
8478        assert_eq!(resp["id"], resp["request_id"]);
8479        assert!(resp["request_id"]
8480            .as_str()
8481            .unwrap()
8482            .starts_with("chatcmpl-"));
8483    }
8484
8485    /// The whole point of server-reported timings: a client can tell
8486    /// prefill from decode without a stopwatch (see `frink_api::usage`).
8487    #[tokio::test]
8488    async fn usage_carries_separate_prefill_and_decode_timings() {
8489        let app = test_app();
8490        let resp = post_json(
8491            &app,
8492            serde_json::json!({
8493                "model": "m",
8494                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8495                "max_tokens": 4,
8496                "temperature": 0,
8497            }),
8498        )
8499        .await;
8500        let usage = &resp["usage"];
8501        assert!(usage["prompt_eval_duration_ms"].is_number(), "{usage}");
8502        assert!(usage["generation_duration_ms"].is_number(), "{usage}");
8503        assert!(usage["time_to_first_token_ms"].is_number(), "{usage}");
8504        assert!(usage["predicted_per_second"].is_number(), "{usage}");
8505        // No prefix cache in this app: the field must be absent, not 0.
8506        assert!(usage.get("cached_tokens").is_none(), "{usage}");
8507    }
8508
8509    /// A real, deterministic small model with random weights will not
8510    /// spontaneously produce a `<tool_call>{...}</tool_call>` marker
8511    /// (whether a real deployed model does is a property of that
8512    /// model, not of frink's plumbing) -- so the real, testable
8513    /// end-to-end property here is that a `tools`-bearing request
8514    /// whose output does NOT contain the marker falls through cleanly
8515    /// to an ordinary text response instead of erroring or panicking.
8516    #[tokio::test]
8517    async fn a_tools_request_with_no_marker_in_the_output_falls_back_to_plain_content() {
8518        let app = test_app();
8519        let body = serde_json::json!({
8520            "model": "m",
8521            "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8522            "max_tokens": 4,
8523            "temperature": 0,
8524            "tools": [weather_tool()],
8525        });
8526        let resp = post_json(&app, body).await;
8527        let message = &resp["choices"][0]["message"];
8528        assert!(
8529            message["content"].is_string(),
8530            "must fall back to plain content when no real tool-call marker is present: {resp:?}"
8531        );
8532        assert!(message.get("tool_calls").is_none());
8533        // Truncated at max_tokens, so the honest finish reason is
8534        // "length" -- the point here is only that it is NOT
8535        // "tool_calls".
8536        assert_eq!(resp["choices"][0]["finish_reason"], "length");
8537    }
8538
8539    /// A whole-response cache hit must be indistinguishable from
8540    /// recomputing: same content, same (honest) finish_reason, same
8541    /// usage counts -- only the `frink_cache` marker may differ.
8542    #[tokio::test]
8543    async fn a_cache_hit_reports_the_original_finish_reason_and_usage() {
8544        let app = test_app();
8545        let body = serde_json::json!({
8546            "model": "m",
8547            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8548            "max_tokens": 3,
8549            "temperature": 0,
8550        });
8551        let first = post_json(&app, body.clone()).await;
8552        assert_eq!(first["frink_cache"], "miss");
8553        let second = post_json(&app, body).await;
8554        assert_eq!(second["frink_cache"], "hit");
8555        assert_eq!(
8556            first["choices"][0]["message"]["content"],
8557            second["choices"][0]["message"]["content"]
8558        );
8559        assert_eq!(
8560            first["choices"][0]["finish_reason"],
8561            second["choices"][0]["finish_reason"]
8562        );
8563        assert_eq!(first["usage"], second["usage"]);
8564        assert_eq!(second["usage"]["completion_tokens"], 3);
8565    }
8566
8567    /// The whole of #35 through the real router: a request that adds a
8568    /// GRAMMAR to a body already answered without one must be generated
8569    /// afresh, under that grammar.
8570    ///
8571    /// The cache used to be consulted before
8572    /// `generation_params_for_template` had even compiled the grammar,
8573    /// and the key held no trace of it, so the constrained request was
8574    /// handed the previous caller's unconstrained prose with a 200. The
8575    /// answer is asserted, not the key: a key that differs proves
8576    /// nothing if the lookup uses something else.
8577    #[tokio::test]
8578    async fn a_grammar_request_is_not_answered_from_an_unconstrained_cache_entry() {
8579        let app = test_app();
8580        let plain = serde_json::json!({
8581            "model": "m",
8582            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8583            "max_tokens": 3,
8584            "temperature": 0,
8585        });
8586
8587        let first = post_json(&app, plain.clone()).await;
8588        assert_eq!(first["frink_cache"], "miss");
8589        let unconstrained = first["choices"][0]["message"]["content"]
8590            .as_str()
8591            .expect("content")
8592            .to_string();
8593
8594        let mut constrained = plain.clone();
8595        constrained["grammar"] = serde_json::json!("root ::= \"yes\"");
8596        let second = post_json(&app, constrained).await;
8597        assert_eq!(
8598            second["frink_cache"], "miss",
8599            "a grammar is part of the key, so this body has never been answered"
8600        );
8601        // The synthetic demo model wraps its decode in a banner, so the
8602        // assertion is on the decoded text inside it: `yes` is the only
8603        // string this grammar admits, and it is there.
8604        let constrained_answer = second["choices"][0]["message"]["content"]
8605            .as_str()
8606            .expect("content")
8607            .to_string();
8608        assert!(
8609            constrained_answer.contains("-> \"yes\"]"),
8610            "the grammar must have been compiled AND applied, not skipped \
8611             by a cache hit: {constrained_answer}"
8612        );
8613        assert_ne!(
8614            constrained_answer, unconstrained,
8615            "the constrained request was served the unconstrained answer"
8616        );
8617
8618        // And the entry the first request made is still the first
8619        // request's: the miss above is the grammar, not a key that
8620        // fails to repeat.
8621        let third = post_json(&app, plain).await;
8622        assert_eq!(third["frink_cache"], "hit");
8623        assert_eq!(third["choices"][0]["message"]["content"], unconstrained);
8624    }
8625
8626    /// The third of #35's fields, and the one whose old failure was
8627    /// LOUD: `validate_json_object_output` runs against whatever came
8628    /// back, so a `json_object` request answered from a cached prose
8629    /// entry got a hard 400 for a body that had never been generated
8630    /// under the JSON mask at all.
8631    ///
8632    /// The system message is what makes this reproducible, and it is the
8633    /// repo's own bug shape underneath. `inject_json_object_system_hint`
8634    /// usually leaves a fingerprint in the PROMPT, which happened to
8635    /// split the two keys apart -- a correctness property nothing stated
8636    /// or enforced, resting on a string edit made for a different
8637    /// reason. Its `!s.contains("JSON")` arm is the hole: a caller who
8638    /// already says "JSON" in their own system message gets NO hint
8639    /// appended, so the two requests render byte-identical prompts and
8640    /// the old key could not tell them apart.
8641    ///
8642    /// The synthetic model emits its demo banner under either mask, so
8643    /// the 400 is the same on both sides of this fix and cannot be the
8644    /// assertion; the cache-level twin in `response_cache` asserts the
8645    /// answer. What is asserted here is that the answer did not come
8646    /// from the other request's entry.
8647    #[tokio::test]
8648    async fn a_json_object_request_does_not_reuse_the_unconstrained_cache_entry() {
8649        let state = Arc::new(test_state(
8650            test_model_full_byte_vocab(),
8651            ResponseCache::new(1000, Duration::from_secs(3600)),
8652        ));
8653        let app = test_app_with_state(state.clone());
8654        let plain = serde_json::json!({
8655            "model": "m",
8656            "messages": [
8657                {"role": "system", "content": "Answer in JSON when it helps."},
8658                {"role": "user", "content": "\u{1}\u{2}"},
8659            ],
8660            "max_tokens": 3,
8661            "temperature": 0,
8662        });
8663
8664        let first = post_json(&app, plain.clone()).await;
8665        assert_eq!(first["frink_cache"], "miss");
8666        assert_eq!(state.cache_stats().entries, 1);
8667
8668        let mut as_json = plain.clone();
8669        as_json["response_format"] = serde_json::json!({"type": "json_object"});
8670        let (status, _) = post_json_uri(&app, "/v1/chat/completions", as_json).await;
8671        assert_eq!(
8672            status,
8673            StatusCode::BAD_REQUEST,
8674            "the demo banner is not a JSON object, whoever generated it"
8675        );
8676        assert_eq!(
8677            state.cache_stats().hits,
8678            0,
8679            "a json_object request must not be answered from an entry the \
8680             JSON mask never produced"
8681        );
8682        assert_eq!(
8683            state.cache_stats().entries,
8684            2,
8685            "json_object must key its own entry, not reuse the unconstrained \
8686             one it happens to render the same prompt as"
8687        );
8688    }
8689
8690    /// The same failure for `ignore_eos`, whose whole purpose is that a
8691    /// benchmarking run produces EXACTLY `max_tokens`. Answered from a
8692    /// cache entry the model's own EOS had cut short, it produced the
8693    /// short answer instead -- the one outcome the field exists to rule
8694    /// out (#35).
8695    ///
8696    /// `0x77` is the id this model greedily emits SECOND for the prompt
8697    /// below, so with it as the EOS the plain request stops after one
8698    /// token and the `ignore_eos` one runs the whole budget. Asserted on
8699    /// the token count and the finish reason, which is where a replayed
8700    /// answer shows.
8701    #[tokio::test]
8702    async fn an_ignore_eos_request_is_not_answered_from_a_cache_entry_that_stopped_at_eos() {
8703        let app = test_app_with_state(Arc::new(test_state(
8704            test_model_full_byte_vocab_with_eos(Some(0x77)),
8705            ResponseCache::new(1000, Duration::from_secs(3600)),
8706        )));
8707        let body = serde_json::json!({
8708            "model": "m",
8709            "messages": [{"role": "user", "content": "\u{1}\u{2}"}],
8710            "max_tokens": 6,
8711            "temperature": 0,
8712        });
8713
8714        let stopped = post_json(&app, body.clone()).await;
8715        assert_eq!(stopped["frink_cache"], "miss");
8716        assert_eq!(
8717            stopped["choices"][0]["finish_reason"], "stop",
8718            "the fixture is only meaningful if the model's EOS really fires here"
8719        );
8720        assert_eq!(stopped["usage"]["completion_tokens"], 1);
8721
8722        let mut ignoring = body.clone();
8723        ignoring["ignore_eos"] = serde_json::json!(true);
8724        let ran_on = post_json(&app, ignoring).await;
8725        assert_eq!(
8726            ran_on["frink_cache"], "miss",
8727            "ignore_eos is part of the key, so this body has never been answered"
8728        );
8729        assert_eq!(
8730            ran_on["usage"]["completion_tokens"], 6,
8731            "ignore_eos must run the full budget, not replay the EOS-terminated answer"
8732        );
8733        assert_eq!(ran_on["choices"][0]["finish_reason"], "length");
8734        assert_ne!(
8735            ran_on["choices"][0]["message"]["content"],
8736            stopped["choices"][0]["message"]["content"]
8737        );
8738    }
8739
8740    /// The real proof for session reuse:
8741    /// a two-request session where the second request sends only its
8742    /// new message must produce exactly the same output as manually
8743    /// resending the full history (built from the *real* first reply,
8744    /// not an assumed one) with no `session_id` at all.
8745    #[tokio::test]
8746    async fn session_reuse_produces_the_same_output_as_manually_resending_full_history() {
8747        let session_app = test_app();
8748        let manual_app = test_app();
8749
8750        // Turn 1, via session.
8751        let turn1 = post_json(
8752            &session_app,
8753            serde_json::json!({
8754                "model": "m",
8755                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8756                "session_id": "s1",
8757                "max_tokens": 5,
8758                "temperature": 0,
8759            }),
8760        )
8761        .await;
8762        let reply1 = turn1["choices"][0]["message"]["content"]
8763            .as_str()
8764            .unwrap()
8765            .to_string();
8766
8767        // Turn 1, manually, for comparison -- must match exactly
8768        // (trivially, since it's the literal same single-turn
8769        // request), confirming the session path's first turn isn't
8770        // doing anything different from a plain request.
8771        let manual_turn1 = post_json(
8772            &manual_app,
8773            serde_json::json!({
8774                "model": "m",
8775                "messages": [{"role": "user", "content": "\u{1}\u{2}\u{3}"}],
8776                "max_tokens": 5,
8777                "temperature": 0,
8778            }),
8779        )
8780        .await;
8781        assert_eq!(
8782            manual_turn1["choices"][0]["message"]["content"]
8783                .as_str()
8784                .unwrap(),
8785            reply1
8786        );
8787
8788        // Turn 2, via session: sends ONLY the new message.
8789        let turn2 = post_json(
8790            &session_app,
8791            serde_json::json!({
8792                "model": "m",
8793                "messages": [{"role": "user", "content": "\u{4}\u{5}"}],
8794                "session_id": "s1",
8795                "max_tokens": 5,
8796                "temperature": 0,
8797            }),
8798        )
8799        .await;
8800        let reply2 = turn2["choices"][0]["message"]["content"]
8801            .as_str()
8802            .unwrap()
8803            .to_string();
8804
8805        // Turn 2, manually: the full three-message history
8806        // reconstructed using the REAL reply1 text, with no
8807        // session_id -- must produce byte-identical output.
8808        let manual_turn2 = post_json(
8809            &manual_app,
8810            serde_json::json!({
8811                "model": "m",
8812                "messages": [
8813                    {"role": "user", "content": "\u{1}\u{2}\u{3}"},
8814                    {"role": "assistant", "content": reply1},
8815                    {"role": "user", "content": "\u{4}\u{5}"},
8816                ],
8817                "max_tokens": 5,
8818                "temperature": 0,
8819            }),
8820        )
8821        .await;
8822        assert_eq!(
8823            manual_turn2["choices"][0]["message"]["content"]
8824                .as_str()
8825                .unwrap(),
8826            reply2,
8827            "resuming a session must produce identical output to manually resending the full history"
8828        );
8829    }
8830
8831    /// `lock_cache` must return a usable guard even after the mutex was
8832    /// poisoned by a panic elsewhere.
8833    #[test]
8834    fn lock_cache_recovers_from_a_poisoned_mutex() {
8835        let cache = Arc::new(Mutex::new(ResponseCache::new(10, Duration::from_secs(60))));
8836
8837        let poison_cache = Arc::clone(&cache);
8838        let _ = std::thread::spawn(move || {
8839            let _guard = poison_cache.lock().unwrap();
8840            panic!("simulated panic while holding the lock");
8841        })
8842        .join();
8843
8844        // A plain `.lock().unwrap()` would panic here; lock_cache must not.
8845        let recovered = lock_cache(&cache);
8846        assert_eq!(recovered.stats().entries, 0);
8847    }
8848
8849    #[test]
8850    fn is_cacheable_true_for_greedy_or_seeded_requests() {
8851        let mut req_body = serde_json::json!({
8852            "model": "m",
8853            "messages": [{"role": "user", "content": "hi"}],
8854        });
8855        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8856        assert!(
8857            req.is_cacheable(),
8858            "default (temperature 0) must be cacheable"
8859        );
8860
8861        req_body["temperature"] = serde_json::json!(0.8);
8862        let req: ChatCompletionRequest = serde_json::from_value(req_body.clone()).unwrap();
8863        assert!(
8864            !req.is_cacheable(),
8865            "unseeded sampling must never be cacheable"
8866        );
8867
8868        req_body["seed"] = serde_json::json!(42);
8869        let req: ChatCompletionRequest = serde_json::from_value(req_body).unwrap();
8870        assert!(
8871            req.is_cacheable(),
8872            "sampling with an explicit seed is deterministic and must be cacheable"
8873        );
8874    }
8875
8876    /// A template that grades only the OpenAI triple. `raise_exception`
8877    /// is how a real one rejects a value it does not know, which is what
8878    /// makes the load-time probe able to learn the vocabulary at all.
8879    const GRADED: &str = "{% if reasoning_effort %}\
8880         {% if reasoning_effort not in ['low','medium','high'] %}\
8881           {{ raise_exception('unsupported effort') }}\
8882         {% endif %}E:{{ reasoning_effort }}|{% endif %}\
8883         {% if enable_thinking %}THINK|{% endif %}{{ messages[0].content }}";
8884
8885    fn graded_template() -> chat_template::PromptTemplate {
8886        chat_template::PromptTemplate::from_gguf_metadata(
8887            Some(GRADED),
8888            Some("qwen3"),
8889            false,
8890            true,
8891            None,
8892            None,
8893        )
8894    }
8895
8896    fn chat_request(value: serde_json::Value) -> ChatCompletionRequest {
8897        serde_json::from_value(value).expect("request")
8898    }
8899
8900    /// The wire field reaches the sampler, compiled.
8901    ///
8902    /// Serde is the failure mode here, not the grammar engine: an
8903    /// undeclared field is dropped silently and the caller is served
8904    /// unconstrained text with a 200, which is exactly why `logit_bias`
8905    /// is declared on this struct only to be refused by name.
8906    #[test]
8907    fn a_grammar_on_the_chat_wire_reaches_the_generation_params() {
8908        let req = chat_request(serde_json::json!({
8909            "model": "m",
8910            "messages": [{"role": "user", "content": "hi"}],
8911            "grammar": "root ::= \"a\"+",
8912        }));
8913        req.validate_supported_fields()
8914            .expect("a valid grammar is a valid request");
8915        let params = req
8916            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8917            .expect("a valid grammar compiles at params time too");
8918        assert!(
8919            params.grammar.is_some(),
8920            "the grammar was dropped between the wire and the sampler"
8921        );
8922        assert!(
8923            params.needs_vocab_logits(),
8924            "a grammar request that may fold lm_head into a GPU argmax is \
8925             a grammar request served unconstrained"
8926        );
8927
8928        let plain = chat_request(serde_json::json!({
8929            "model": "m",
8930            "messages": [{"role": "user", "content": "hi"}],
8931        }));
8932        assert!(plain
8933            .generation_params(crate::sampling_knobs::SamplerModel::absent())
8934            .unwrap()
8935            .grammar
8936            .is_none());
8937    }
8938
8939    fn tool_request(tool_choice: serde_json::Value) -> ChatCompletionRequest {
8940        chat_request(serde_json::json!({
8941            "model": "m",
8942            "messages": [{"role": "user", "content": "weather in Rome?"}],
8943            "tools": [weather_tool()],
8944            "tool_choice": tool_choice,
8945        }))
8946    }
8947
8948    /// `tool_choice: "required"` used to be a 501. It now compiles the
8949    /// offered tools into a grammar that rides on the params, which is
8950    /// the only thing every decode path shares.
8951    #[test]
8952    fn a_forced_tool_choice_puts_a_grammar_on_the_generation_params() {
8953        for choice in [
8954            serde_json::json!("required"),
8955            serde_json::json!({"type": "function", "function": {"name": "get_weather"}}),
8956        ] {
8957            let req = tool_request(choice.clone());
8958            req.validate_supported_fields()
8959                .unwrap_or_else(|e| panic!("{choice} is a valid request: {e:?}"));
8960            let params = req
8961                .generation_params_for_template(
8962                    &graded_template(),
8963                    "Qwen3-8B",
8964                    crate::sampling_knobs::SamplerModel::absent(),
8965                )
8966                .unwrap_or_else(|e| panic!("{choice} compiles: {e:?}"));
8967            let grammar = params
8968                .grammar
8969                .as_ref()
8970                .unwrap_or_else(|| panic!("{choice} was accepted and then not enforced"));
8971            assert!(
8972                grammar.is_awaiting_trigger(),
8973                "the model must be free to think before it calls"
8974            );
8975            assert!(
8976                !grammar.allows_eog(),
8977                "{choice} must not be able to end the turn without a call"
8978            );
8979            // The bug that has been fixed three times: a constrained
8980            // request that lets a backend fold lm_head+argmax on device
8981            // is a constrained request served unconstrained. A LAZY
8982            // grammar needs the vocabulary from the FIRST token, because
8983            // its trigger can fire on any of them.
8984            assert!(
8985                params.needs_vocab_logits(),
8986                "{choice} would let a backend return a token id instead of logits"
8987            );
8988            assert!(
8989                !generate::greedy_gpu_fold_allowed(&params),
8990                "{choice} at temperature 0 must still refuse the greedy GPU fold"
8991            );
8992        }
8993    }
8994
8995    /// `auto` and `none` force nothing, and must not acquire a grammar.
8996    #[test]
8997    fn an_unforced_tool_choice_leaves_the_generation_unconstrained() {
8998        for choice in [serde_json::json!("auto"), serde_json::json!("none")] {
8999            let req = tool_request(choice.clone());
9000            req.validate_supported_fields().expect("still supported");
9001            let params = match req.generation_params_for_template(
9002                &graded_template(),
9003                "Qwen3-8B",
9004                crate::sampling_knobs::SamplerModel::absent(),
9005            ) {
9006                Ok(p) => p,
9007                Err((status, _)) => panic!("{choice} has no constraint to compile: {status}"),
9008            };
9009            assert!(
9010                params.grammar.is_none(),
9011                "{choice} does not force a call and must not be constrained"
9012            );
9013        }
9014    }
9015
9016    /// Every refusal a forced choice can produce names the field, and
9017    /// none of them is a silent downgrade to `auto`.
9018    #[test]
9019    fn a_forced_tool_choice_refuses_rather_than_quietly_not_forcing() {
9020        // No tools to choose between.
9021        let req = chat_request(serde_json::json!({
9022            "model": "m",
9023            "messages": [{"role": "user", "content": "hi"}],
9024            "tool_choice": "required",
9025        }));
9026        let (status, _) = req
9027            .validate_supported_fields()
9028            .expect_err("nothing to call");
9029        assert_eq!(status, StatusCode::BAD_REQUEST);
9030
9031        // A name that is not on offer.
9032        let req =
9033            tool_request(serde_json::json!({"type": "function", "function": {"name": "nope"}}));
9034        let (status, Json(body)) = req.validate_supported_fields().expect_err("no such tool");
9035        assert_eq!(status, StatusCode::BAD_REQUEST);
9036        assert_eq!(body["error"]["param"], "tool_choice");
9037
9038        // An object that names nothing at all.
9039        let req = tool_request(serde_json::json!({"type": "function"}));
9040        let (status, _) = req.validate_supported_fields().expect_err("names nothing");
9041        assert_eq!(status, StatusCode::BAD_REQUEST);
9042
9043        // Two constraints on one generation.
9044        let req = chat_request(serde_json::json!({
9045            "model": "m",
9046            "messages": [{"role": "user", "content": "hi"}],
9047            "tools": [weather_tool()],
9048            "tool_choice": "required",
9049            "grammar": "root ::= \"a\"+",
9050        }));
9051        let (status, _) = req
9052            .validate_supported_fields()
9053            .expect_err("a grammar and a forced call are two constraints");
9054        assert_eq!(status, StatusCode::BAD_REQUEST);
9055
9056        // A checkpoint whose wire format has no grammar is refused by
9057        // name at params time, when the served model is known. GLM and
9058        // gemma4 both used to stand here and are forced now;
9059        // muse_glimmer is the one `tool_grammar::wire::shape` still
9060        // refuses, and the refusal says which format and why.
9061        let req = tool_request(serde_json::json!("required"));
9062        let (status, Json(body)) = match req.generation_params_for_template(
9063            &graded_template(),
9064            "muse-glimmer-8b",
9065            crate::sampling_knobs::SamplerModel::absent(),
9066        ) {
9067            Err(e) => e,
9068            Ok(_) => panic!("a muse_glimmer call's boundary is a channel, not a marker"),
9069        };
9070        assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
9071        assert!(
9072            body["error"]["message"]
9073                .as_str()
9074                .unwrap()
9075                .contains("muse_glimmer"),
9076            "{body}"
9077        );
9078
9079        // And the format this once refused is served: a served model
9080        // whose name resolves to gemma4 reaches a grammar rather than a
9081        // 501. `generation_params_for_template` is the only place a
9082        // forced choice becomes one, so this is the request-level
9083        // evidence that the wire work is wired.
9084        let req = tool_request(serde_json::json!("required"));
9085        let params = req
9086            .generation_params_for_template(
9087                &graded_template(),
9088                "gemma-4-E2B-it",
9089                crate::sampling_knobs::SamplerModel::absent(),
9090            )
9091            .expect("a gemma4 forced tool_choice is served");
9092        assert!(
9093            params.grammar.is_some(),
9094            "a forced tool_choice must arrive as the generation's grammar"
9095        );
9096    }
9097
9098    /// A grammar that does not parse is refused before any work, and
9099    /// the refusal names the field and the parser's own diagnostic.
9100    #[test]
9101    fn an_unparseable_grammar_on_the_chat_wire_is_a_400() {
9102        let req = chat_request(serde_json::json!({
9103            "model": "m",
9104            "messages": [{"role": "user", "content": "hi"}],
9105            "grammar": "root ::= \"a",
9106        }));
9107        let (status, Json(body)) = req
9108            .validate_supported_fields()
9109            .expect_err("this does not parse");
9110        assert_eq!(status, StatusCode::BAD_REQUEST);
9111        assert_eq!(body["error"]["param"], "grammar");
9112        assert!(
9113            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
9114                .is_err(),
9115            "and again at params time"
9116        );
9117    }
9118
9119    /// `response_format: json_schema` used to be a 501 naming the
9120    /// missing converter. It is served now, and the request-level
9121    /// evidence is that the schema reaches `generation_params` as a
9122    /// grammar -- there is exactly one place a `response_format` is
9123    /// decided, so a route that validated it and then forgot to apply
9124    /// it is the failure this asserts against.
9125    #[test]
9126    fn response_format_json_schema_becomes_the_requests_grammar() {
9127        let req = chat_request(serde_json::json!({
9128            "model": "m",
9129            "messages": [{"role": "user", "content": "hi"}],
9130            "response_format": {
9131                "type": "json_schema",
9132                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
9133            },
9134        }));
9135        req.validate_supported_fields()
9136            .expect("a boolean schema converts");
9137        let params = req
9138            .generation_params(crate::sampling_knobs::SamplerModel::absent())
9139            .expect("and compiles");
9140        let grammar = params.grammar.expect("the schema is the grammar");
9141        let mut g = (*grammar).clone();
9142        g.accept_token(0, b"true").expect("a boolean is accepted");
9143        assert!(g.allows_eog(), "and completes the parse");
9144        assert!(
9145            !params.json_object,
9146            "a schema is not the json_object character-class mask"
9147        );
9148    }
9149
9150    /// A schema the converter will not compile is a 400 naming the
9151    /// keyword, at both the validation and the params seam -- never a
9152    /// 500, and never a grammar that is approximately the schema.
9153    #[test]
9154    fn an_unconvertible_response_format_schema_is_a_400_naming_the_keyword() {
9155        let req = chat_request(serde_json::json!({
9156            "model": "m",
9157            "messages": [{"role": "user", "content": "hi"}],
9158            "response_format": {
9159                "type": "json_schema",
9160                "json_schema": {"name": "x", "schema": {"type": "integer", "minimum": 3}},
9161            },
9162        }));
9163        let (status, Json(body)) = req
9164            .validate_supported_fields()
9165            .expect_err("minimum has no grammar in this port");
9166        assert_eq!(status, StatusCode::BAD_REQUEST);
9167        assert!(
9168            body["error"]["message"]
9169                .as_str()
9170                .expect("a message")
9171                .contains("minimum"),
9172            "the refusal must name the keyword: {body}"
9173        );
9174        assert!(
9175            req.generation_params(crate::sampling_knobs::SamplerModel::absent())
9176                .is_err(),
9177            "and again at params time"
9178        );
9179    }
9180
9181    /// A forced `tool_choice` and a `response_format` schema are two
9182    /// constraints on one generation. The refusal used to be spelled
9183    /// against `self.grammar` alone, so the schema spelling walked past
9184    /// it and `generation_params_for_template` overwrote the schema's
9185    /// grammar with the tool-call one.
9186    #[test]
9187    fn a_forced_tool_choice_and_a_schema_are_two_constraints() {
9188        let req = chat_request(serde_json::json!({
9189            "model": "m",
9190            "messages": [{"role": "user", "content": "hi"}],
9191            "tool_choice": "required",
9192            "tools": [{
9193                "type": "function",
9194                "function": {"name": "f", "parameters": {"type": "object"}},
9195            }],
9196            "response_format": {
9197                "type": "json_schema",
9198                "json_schema": {"name": "x", "schema": {"type": "boolean"}},
9199            },
9200        }));
9201        let (status, Json(body)) = req
9202            .validate_supported_fields()
9203            .expect_err("two constraints, one generation");
9204        assert_eq!(status, StatusCode::BAD_REQUEST);
9205        assert_eq!(body["error"]["param"], "tool_choice");
9206    }
9207
9208    /// A chat client that omits `max_tokens` wants an answer, not
9209    /// OpenAI's legacy 16-token completion fragment.
9210    #[test]
9211    fn an_omitted_output_budget_is_a_whole_answer_not_sixteen_tokens() {
9212        let req = chat_request(serde_json::json!({
9213            "model": "m",
9214            "messages": [{"role": "user", "content": "hi"}],
9215        }));
9216        assert_eq!(req.max_tokens, DEFAULT_CHAT_MAX_TOKENS);
9217    }
9218
9219    /// A knob the wire accepts must reach the sampler. Serde declaring
9220    /// `min_p` is only half of it: the field spent two commits resolved
9221    /// to a hardcoded `0.0` on both routes, which is exactly the
9222    /// silently-dropped-parameter bug, just one layer further in.
9223    #[test]
9224    fn min_p_reaches_the_sampler_from_the_chat_wire() {
9225        let asked = chat_request(serde_json::json!({
9226            "model": "m",
9227            "messages": [{"role": "user", "content": "hi"}],
9228            "min_p": 0.07,
9229        }));
9230        assert_eq!(
9231            asked
9232                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
9233                .expect("knobs")
9234                .min_p,
9235            0.07
9236        );
9237
9238        let silent = chat_request(serde_json::json!({
9239            "model": "m",
9240            "messages": [{"role": "user", "content": "hi"}],
9241        }));
9242        assert_eq!(
9243            silent
9244                .sampling_params(crate::sampling_knobs::SamplerModel::absent())
9245                .expect("knobs")
9246                .min_p,
9247            0.0,
9248            "an unset min_p must be off, not llama.cpp's CLI default"
9249        );
9250    }
9251
9252    /// The whole-response cache is keyed on the sampler settings, and a
9253    /// setting left OUT of that key means two requests differing only in
9254    /// it share one answer: the second caller silently gets output
9255    /// computed under the first caller's parameters.
9256    ///
9257    /// Every knob the wire accepts is checked, not just the new one --
9258    /// this is the assertion that would have caught `min_p` being added
9259    /// to the sampler and forgotten here.
9260    #[test]
9261    fn no_sampler_knob_is_missing_from_the_cache_key() {
9262        let base = serde_json::json!({
9263            "model": "m",
9264            "messages": [{"role": "user", "content": "hi"}],
9265            "seed": 1,
9266        });
9267        let key_for = |body: serde_json::Value| {
9268            let req = chat_request(body);
9269            let params = req
9270                .generation_params(crate::sampling_knobs::SamplerModel::absent())
9271                .expect("params");
9272            req.cache_key("prompt", &params)
9273        };
9274        let baseline = key_for(base.clone());
9275        for (knob, value) in [
9276            ("temperature", serde_json::json!(0.5)),
9277            ("top_p", serde_json::json!(0.9)),
9278            ("min_p", serde_json::json!(0.05)),
9279            ("top_k", serde_json::json!(40)),
9280            ("repetition_penalty", serde_json::json!(1.1)),
9281            ("presence_penalty", serde_json::json!(0.3)),
9282            ("frequency_penalty", serde_json::json!(0.3)),
9283            (
9284                "samplers",
9285                serde_json::json!(["penalties", "top_p", "top_k", "min_p", "temperature"]),
9286            ),
9287        ] {
9288            let mut body = base.clone();
9289            body[knob] = value;
9290            assert_ne!(
9291                key_for(body),
9292                baseline,
9293                "`{knob}` is not in the cache key: two requests differing \
9294                 only in it would share one cached answer"
9295            );
9296        }
9297    }
9298
9299    /// The sampler half's twin, for the constraints. Each of these
9300    /// changes the answer and changes NOTHING about the rendered
9301    /// prompt, so an omission is invisible until a caller compares two
9302    /// answers it never sees side by side (#35).
9303    ///
9304    /// `grammar` here is the wire field; `response_format:
9305    /// {"type":"json_schema"}` and a forced `tool_choice` compile to a
9306    /// grammar through the same `GenerationParams::grammar`, so they are
9307    /// keyed by the same field being keyed at all.
9308    #[test]
9309    fn no_constraint_is_missing_from_the_cache_key() {
9310        let base = serde_json::json!({
9311            "model": "m",
9312            "messages": [{"role": "user", "content": "pick one"}],
9313        });
9314        let key_for = |body: serde_json::Value| {
9315            let req = chat_request(body);
9316            let params = req
9317                .generation_params(crate::sampling_knobs::SamplerModel::absent())
9318                .expect("params");
9319            req.cache_key("prompt", &params)
9320        };
9321        let baseline = key_for(base.clone());
9322        for (field, value) in [
9323            ("grammar", serde_json::json!("root ::= \"yes\" | \"no\"")),
9324            (
9325                "response_format",
9326                serde_json::json!({"type": "json_object"}),
9327            ),
9328            (
9329                "response_format",
9330                serde_json::json!({"type": "json_schema", "json_schema": {
9331                    "name": "answer",
9332                    "schema": {"type": "object", "properties": {"a": {"type": "string"}}}
9333                }}),
9334            ),
9335            ("ignore_eos", serde_json::json!(true)),
9336            ("stop", serde_json::json!(["\n"])),
9337            ("max_tokens", serde_json::json!(7)),
9338        ] {
9339            let mut body = base.clone();
9340            body[field] = value.clone();
9341            assert_ne!(
9342                key_for(body),
9343                baseline,
9344                "`{field}: {value}` is not in the cache key: two requests \
9345                 differing only in it would share one cached answer"
9346            );
9347        }
9348    }
9349
9350    /// Serde already tells absent from zero -- an absent field became
9351    /// the default -- so a 0 here is one the caller wrote, and a
9352    /// zero-token budget is a request that can never become decodable.
9353    #[test]
9354    fn an_explicit_zero_output_budget_is_a_client_error() {
9355        let req = chat_request(serde_json::json!({
9356            "model": "m",
9357            "messages": [{"role": "user", "content": "hi"}],
9358            "max_tokens": 0,
9359        }));
9360        let (status, body) = req.validate_supported_fields().expect_err("rejected");
9361        assert_eq!(status, StatusCode::BAD_REQUEST);
9362        assert_eq!(body["error"]["param"], serde_json::json!("max_tokens"));
9363    }
9364
9365    /// The direction that had no wire path at all before: every request
9366    /// rendered in thinking mode because only the ON branch existed.
9367    #[test]
9368    fn a_request_can_turn_thinking_off() {
9369        let template = graded_template();
9370        for body in [
9371            serde_json::json!({
9372                "model": "m",
9373                "messages": [{"role": "user", "content": "hi"}],
9374                "reasoning_effort": "none",
9375            }),
9376            serde_json::json!({
9377                "model": "m",
9378                "messages": [{"role": "user", "content": "hi"}],
9379                "thinking": {"type": "disabled"},
9380            }),
9381        ] {
9382            let kwargs = chat_request(body).resolve_template_kwargs(&template);
9383            assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
9384            assert_eq!(kwargs["thinking_mode"], serde_json::json!("disabled"));
9385            // And `none` must not have been rounded onto a real gear on
9386            // the way: "do not think" is not "think a little".
9387            assert!(!kwargs.contains_key("reasoning_effort"));
9388        }
9389    }
9390
9391    /// The switch is what the caller reached for last; the gear is what
9392    /// they would have used had thinking been on.
9393    #[test]
9394    fn a_disabled_switch_beats_an_effort_in_the_same_request() {
9395        let template = graded_template();
9396        let kwargs = chat_request(serde_json::json!({
9397            "model": "m",
9398            "messages": [{"role": "user", "content": "hi"}],
9399            "reasoning_effort": "high",
9400            "thinking": {"type": "disabled"},
9401        }))
9402        .resolve_template_kwargs(&template);
9403        assert_eq!(kwargs["enable_thinking"], serde_json::json!(false));
9404        assert!(!kwargs.contains_key("reasoning_effort"));
9405    }
9406
9407    /// Read as "on", a misspelled switch silently serves the opposite
9408    /// of what was asked for.
9409    #[test]
9410    fn an_unrecognized_thinking_switch_is_refused_rather_than_read_as_on() {
9411        let req = chat_request(serde_json::json!({
9412            "model": "m",
9413            "messages": [{"role": "user", "content": "hi"}],
9414            "thinking": {"type": "disable"},
9415        }));
9416        let (status, _) = req.validate_supported_fields().expect_err("rejected");
9417        assert_eq!(status, StatusCode::BAD_REQUEST);
9418    }
9419
9420    /// A caller who steered the template themselves has said what they
9421    /// want; merging a protocol default in would let it contradict them.
9422    #[test]
9423    fn an_explicit_template_kwarg_stands_the_protocol_knobs_down() {
9424        let template = graded_template();
9425        let kwargs = chat_request(serde_json::json!({
9426            "model": "m",
9427            "messages": [{"role": "user", "content": "hi"}],
9428            "reasoning_effort": "none",
9429            "chat_template_kwargs": {"enable_thinking": true},
9430        }))
9431        .resolve_template_kwargs(&template);
9432        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
9433    }
9434
9435    /// The acceptance criterion for effort plumbing: an off-vocabulary
9436    /// value is quantized onto the nearest gear the checkpoint really
9437    /// grades, and the request renders instead of failing.
9438    #[test]
9439    fn an_off_vocabulary_reasoning_effort_is_quantized_rather_than_interpolated() {
9440        let template = graded_template();
9441        let req = chat_request(serde_json::json!({
9442            "model": "m",
9443            "messages": [{"role": "user", "content": "hi"}],
9444            "reasoning_effort": "minimal",
9445        }));
9446        let kwargs = req.resolve_template_kwargs(&template);
9447        assert_eq!(kwargs["reasoning_effort"], serde_json::json!("low"));
9448        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
9449        assert!(prompt.starts_with("E:low|"), "{prompt}");
9450    }
9451
9452    /// The other half of the same rule: a value no gear is close enough
9453    /// to is dropped, so the checkpoint's own default applies rather
9454    /// than an unknown string reaching the prompt.
9455    #[test]
9456    fn an_effort_with_no_near_gear_is_dropped_so_the_template_default_applies() {
9457        let template = graded_template();
9458        let req = chat_request(serde_json::json!({
9459            "model": "m",
9460            "messages": [{"role": "user", "content": "hi"}],
9461            "chat_template_kwargs": {"reasoning_effort": "none"},
9462        }));
9463        let kwargs = req.resolve_template_kwargs(&template);
9464        assert!(!kwargs.contains_key("reasoning_effort"));
9465        let prompt = prompt_from_messages(&req.messages, &template, &[], kwargs).expect("renders");
9466        assert_eq!(prompt, "hi");
9467    }
9468
9469    /// `chat_template_kwargs` is the specific spelling and wins over the
9470    /// top-level one, which is what a caller who wrote both meant.
9471    #[test]
9472    fn chat_template_kwargs_wins_over_the_top_level_reasoning_effort() {
9473        let template = graded_template();
9474        let req = chat_request(serde_json::json!({
9475            "model": "m",
9476            "messages": [{"role": "user", "content": "hi"}],
9477            "reasoning_effort": "low",
9478            "chat_template_kwargs": {"reasoning_effort": "high"},
9479        }));
9480        assert_eq!(
9481            req.resolve_template_kwargs(&template)["reasoning_effort"],
9482            serde_json::json!("high")
9483        );
9484    }
9485
9486    /// Offering tools turns thinking on even when the caller asked for
9487    /// nothing: some encoders emit well-formed calls only in thinking
9488    /// mode.
9489    #[test]
9490    fn offering_tools_turns_thinking_on_by_itself() {
9491        let template = graded_template();
9492        let quiet = chat_request(serde_json::json!({
9493            "model": "m",
9494            "messages": [{"role": "user", "content": "hi"}],
9495        }));
9496        assert!(!quiet
9497            .resolve_template_kwargs(&template)
9498            .contains_key("enable_thinking"));
9499
9500        let with_tools = chat_request(serde_json::json!({
9501            "model": "m",
9502            "messages": [{"role": "user", "content": "hi"}],
9503            "tools": [{"type": "function", "function": {"name": "get_weather"}}],
9504        }));
9505        let kwargs = with_tools.resolve_template_kwargs(&template);
9506        assert_eq!(kwargs["enable_thinking"], serde_json::json!(true));
9507        let prompt =
9508            prompt_from_messages(&with_tools.messages, &template, &[], kwargs).expect("renders");
9509        assert!(prompt.starts_with("THINK|"), "{prompt}");
9510    }
9511
9512    /// The reason `force_reasoning` could only ever be `false` before:
9513    /// no template could open a block in the prompt, because no kwargs
9514    /// reached one. Now that they do, the parser has to start inside it
9515    /// -- and the evidence is the rendered prompt, not the model name.
9516    #[test]
9517    fn a_prompt_that_opens_the_reasoning_block_makes_the_first_token_reasoning() {
9518        let opener = chat_template::PromptTemplate::from_gguf_metadata(
9519            Some("{{ messages[0].content }}{% if enable_thinking %}<think>{% endif %}"),
9520            Some("qwen3"),
9521            false,
9522            true,
9523            None,
9524            None,
9525        );
9526        let req = chat_request(serde_json::json!({
9527            "model": "m",
9528            "messages": [{"role": "user", "content": "hi"}],
9529            "chat_template_kwargs": {"enable_thinking": true},
9530        }));
9531        let kwargs = req.resolve_template_kwargs(&opener);
9532        let prompt = prompt_from_messages(&req.messages, &opener, &[], kwargs).expect("renders");
9533        assert!(prompt.ends_with("<think>"), "{prompt}");
9534
9535        // No opening marker will ever arrive, so unparsed this whole
9536        // deliberation would have been served as the answer.
9537        let posture = output::OutputPosture::resolve("Qwen3-8B", &prompt);
9538        let (message, _) = build_response_message(
9539            "weighing it up</think>Paris.".to_string(),
9540            &[],
9541            posture,
9542            "stop",
9543        );
9544        assert_eq!(message.reasoning_content.as_deref(), Some("weighing it up"));
9545        assert_eq!(message.content.as_deref(), Some("Paris."));
9546
9547        // Same text, a prompt that did not open the block: the model
9548        // wrote a stray closer and it stays content.
9549        let closed = output::OutputPosture::resolve("Qwen3-8B", "<|im_start|>assistant\n");
9550        let (message, _) = build_response_message(
9551            "weighing it up</think>Paris.".to_string(),
9552            &[],
9553            closed,
9554            "stop",
9555        );
9556        assert_eq!(message.reasoning_content, None);
9557    }
9558
9559    #[test]
9560    fn stop_param_accepts_both_single_string_and_array() {
9561        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
9562            "model": "m",
9563            "messages": [{"role": "user", "content": "hi"}],
9564            "stop": "END",
9565        }))
9566        .unwrap();
9567        assert_eq!(req.stop_sequences(), vec!["END".to_string()]);
9568
9569        let req: ChatCompletionRequest = serde_json::from_value(serde_json::json!({
9570            "model": "m",
9571            "messages": [{"role": "user", "content": "hi"}],
9572            "stop": ["A", "B"],
9573        }))
9574        .unwrap();
9575        assert_eq!(req.stop_sequences(), vec!["A".to_string(), "B".to_string()]);
9576    }
9577
9578    #[test]
9579    fn run_generation_rejects_out_of_vocab_tokens_instead_of_panicking() {
9580        let model = test_model();
9581        let result = run_generation(
9582            &model,
9583            "hello",
9584            &greedy_params(4),
9585            None,
9586            None,
9587            None,
9588            None,
9589            None,
9590            None,
9591        );
9592        assert!(matches!(
9593            result,
9594            Err(generate::DecodeError::TokenOutOfVocab { .. })
9595        ));
9596    }
9597
9598    /// A pool that *could* serve this request but is momentarily fully
9599    /// held is the server being behind: 503, and retrying is honest
9600    /// advice because the blocks really do come back.
9601    #[test]
9602    fn run_generation_honors_an_exhausted_kv_pool_and_maps_it_to_a_503() {
9603        let model = test_model(); // 2 layers -> 2 blocks
9604        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9605        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
9606
9607        let holder_pool = Arc::clone(&pool);
9608        let holder = std::thread::spawn(move || {
9609            let mut held = frink_core::cache::KvCache::with_pool(1, 1, holder_pool, 0).unwrap();
9610            held.push(&[0.0], &[0.0]).unwrap(); // crosses into the second block
9611            std::thread::sleep(Duration::from_millis(200));
9612            drop(held);
9613        });
9614        std::thread::sleep(Duration::from_millis(15));
9615
9616        let config = generate::KvPoolConfig {
9617            pool,
9618            queue_wait: Duration::ZERO,
9619        };
9620        let result = run_generation(
9621            &model,
9622            &prompt,
9623            &greedy_params(4),
9624            Some(&config),
9625            None,
9626            None,
9627            None,
9628            None,
9629            None,
9630        );
9631        assert!(matches!(
9632            result,
9633            Err(generate::DecodeError::KvPoolExhausted)
9634        ));
9635
9636        let (status, _body) = decode_error_response(result.unwrap_err());
9637        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
9638        holder.join().unwrap();
9639    }
9640
9641    /// The same endpoint, the same pool size, a request too big for the
9642    /// *whole* pool: a 400 rather than a 503, because an idle server
9643    /// refuses it identically and `Retry-After` would be a promise
9644    /// nothing can keep.
9645    ///
9646    /// Confirmed to FAIL when `generate`'s `pool_immovable_refusal`
9647    /// check is removed: the status comes back 503.
9648    #[test]
9649    fn a_request_too_big_for_the_whole_pool_is_a_400_not_a_retryable_503() {
9650        let model = test_model(); // 2 layers
9651        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9652        // One block, two layers: no schedule ever serves this.
9653        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 1)));
9654        let config = generate::KvPoolConfig {
9655            pool,
9656            queue_wait: Duration::ZERO,
9657        };
9658
9659        let result = run_generation(
9660            &model,
9661            &prompt,
9662            &greedy_params(4),
9663            Some(&config),
9664            None,
9665            None,
9666            None,
9667            None,
9668            None,
9669        );
9670        let err = result.expect_err("one block cannot hold two layers' caches");
9671        assert!(
9672            matches!(
9673                &err,
9674                generate::DecodeError::KvBudgetExceeded { binding, .. }
9675                    if *binding == frink_models::Ceiling::DeviceMemory.code()
9676            ),
9677            "expected an immovable device-memory refusal, got {err:?}"
9678        );
9679        let (status, _body) = decode_error_response(err);
9680        assert_eq!(status, StatusCode::BAD_REQUEST);
9681    }
9682
9683    /// A full admission queue is the server being behind, not the
9684    /// client being wrong: 503, with the wait hint in the body (and the
9685    /// `Retry-After` header stamped by `limits::retry_after`) and the
9686    /// depth and cap named so an operator can tell a retry storm from a
9687    /// single oversized request.
9688    #[test]
9689    fn decode_error_response_maps_a_full_queue_to_a_retryable_503() {
9690        let (status, Json(body)) = decode_error_response(generate::DecodeError::QueueFull {
9691            queued: 512,
9692            cap: 512,
9693        });
9694        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
9695        assert_eq!(body["error"]["retry_after_seconds"], 1);
9696        let message = body["error"]["message"].as_str().expect("message");
9697        assert!(message.contains("512"), "{message}");
9698    }
9699
9700    #[test]
9701    fn decode_error_response_omits_a_retry_hint_for_an_unretryable_error() {
9702        let (_status, Json(body)) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
9703            token: 99,
9704            vocab_size: 32,
9705        });
9706        assert!(
9707            body["error"]["retry_after_seconds"].is_null(),
9708            "retrying a prompt this model cannot tokenize never helps"
9709        );
9710    }
9711
9712    #[test]
9713    fn decode_error_response_maps_token_out_of_vocab_to_bad_request() {
9714        let (status, _body) = decode_error_response(generate::DecodeError::TokenOutOfVocab {
9715            token: 99,
9716            vocab_size: 32,
9717        });
9718        assert_eq!(status, StatusCode::BAD_REQUEST);
9719    }
9720
9721    #[test]
9722    fn run_generation_succeeds_and_releases_blocks_when_the_pool_has_room() {
9723        let model = test_model(); // 2 layers
9724        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9725        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 2)));
9726        let config = generate::KvPoolConfig {
9727            pool: pool.clone(),
9728            queue_wait: Duration::ZERO,
9729        };
9730
9731        let produced = run_generation(
9732            &model,
9733            &prompt,
9734            &greedy_params(4),
9735            Some(&config),
9736            None,
9737            None,
9738            None,
9739            None,
9740            None,
9741        )
9742        .unwrap();
9743        assert_eq!(produced.choices[0].finish, FinishReason::Length);
9744        assert_eq!(
9745            pool.lock().unwrap().free_blocks(),
9746            2,
9747            "a completed request must return its blocks to the pool"
9748        );
9749    }
9750
9751    /// The core concurrency claim: two requests using the *same* `Arc<Model>`
9752    /// must be able to run their (independent, per-call) KV caches
9753    /// concurrently without interfering with each other or needing any
9754    /// shared lock around the model itself.
9755    #[tokio::test]
9756    async fn concurrent_requests_against_the_same_model_do_not_interfere() {
9757        let model = Arc::new(test_model());
9758        let prompt = String::from_utf8(vec![1u8, 2]).unwrap();
9759
9760        let mut handles = Vec::new();
9761        for _ in 0..8 {
9762            let model = Arc::clone(&model);
9763            let prompt = prompt.clone();
9764            handles.push(tokio::task::spawn_blocking(move || {
9765                run_generation(
9766                    &model,
9767                    &prompt,
9768                    &greedy_params(6),
9769                    None,
9770                    None,
9771                    None,
9772                    None,
9773                    None,
9774                    None,
9775                )
9776                .unwrap()
9777            }));
9778        }
9779
9780        let mut results = Vec::new();
9781        for h in handles {
9782            results.push(h.await.unwrap());
9783        }
9784        // Same prompt, same seed, same (greedy) sampling, same
9785        // immutable model -> every concurrent run must produce
9786        // identical output, proving no request's KV cache leaked into
9787        // another's.
9788        for r in &results[1..] {
9789            // `.0` is the per-choice `(finish_reason, text)` list and
9790            // `.1` the usage, so this one comparison covers both the
9791            // text and the reason it stopped.
9792            assert_eq!(r.choices, results[0].choices, "choices must match");
9793            assert_eq!(
9794                r.usage.prompt_tokens, results[0].usage.prompt_tokens,
9795                "prompt token count must match"
9796            );
9797            assert_eq!(
9798                r.usage.completion_tokens, results[0].usage.completion_tokens,
9799                "completion token count must match"
9800            );
9801        }
9802    }
9803
9804    /// A real, minimal safetensors shard: JSON header (name -> real
9805    /// dtype/shape/`data_offsets`) followed by the concatenated raw
9806    /// F32 bytes -- exactly the format `ShardedSafetensors::open_index`
9807    /// parses, hand-built here rather than depending on
9808    /// `frink-models::kimi_loader`'s own private test helpers (not
9809    /// visible across the crate boundary).
9810    fn write_safetensors_shard(tensors: &[(String, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
9811        let mut header_entries = Vec::new();
9812        let mut data = Vec::new();
9813        for (name, shape, values) in tensors {
9814            let start = data.len();
9815            for v in values {
9816                data.extend_from_slice(&v.to_le_bytes());
9817            }
9818            let end = data.len();
9819            let shape_str = shape
9820                .iter()
9821                .map(|d| d.to_string())
9822                .collect::<Vec<_>>()
9823                .join(",");
9824            header_entries.push(format!(
9825                "\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{shape_str}],\"data_offsets\":[{start},{end}]}}"
9826            ));
9827        }
9828        let header = format!("{{{}}}", header_entries.join(","));
9829        let header_bytes = header.as_bytes();
9830        let mut out = Vec::with_capacity(8 + header_bytes.len() + data.len());
9831        out.extend_from_slice(&(header_bytes.len() as u64).to_le_bytes());
9832        out.extend_from_slice(header_bytes);
9833        out.extend_from_slice(&data);
9834        out
9835    }
9836
9837    /// Builds a small but completely real Kimi K3 checkpoint directory
9838    /// on disk (real `model.safetensors.index.json` + shard bytes +
9839    /// `tiktoken.model`, the exact file layout `frink-cli`'s
9840    /// `run-kimi` command expects) and loads it through
9841    /// `model::load_kimi_checkpoint_with_config` (the same real loading
9842    /// logic `model::load()` uses for `FRINK_MODEL_PATH` pointing at a
9843    /// directory, parametrized here only so the checkpoint can be small
9844    /// -- see that function's doc comment). Shared by every test that
9845    /// needs a real, loaded `KimiLoaded` rather than duplicating this
9846    /// setup per test.
9847    fn build_synthetic_kimi_loaded() -> model::KimiLoaded {
9848        use frink_models::config::{AttentionKind, KdaConfig, KimiHybridAttention, MlaConfig};
9849        use frink_models::kimi_loader::KimiRealHparams;
9850        use frink_moe::{GatingFunction, MoeLayerConfig};
9851
9852        let hidden_dim = 8;
9853        let kda_num_heads = 2;
9854        let kda_head_dim = 3;
9855        let kda_proj = kda_num_heads * kda_head_dim;
9856        let conv_kernel = 4;
9857        let dense_intermediate = 5;
9858        // One token per byte value -- enough to round-trip a simple
9859        // ASCII prompt through the real tiktoken-format vocab below,
9860        // matching `kimi_generate`'s own test convention.
9861        let vocab_size = 256;
9862        let mla_num_heads = 1;
9863        let mla_q_lora_rank = 2;
9864        let mla_kv_lora_rank = 2;
9865        let mla_qk_nope_head_dim = 2;
9866        let mla_qk_rope_head_dim = 2;
9867        let mla_v_head_dim = 2;
9868
9869        let model_cfg = frink_models::ModelConfig {
9870            rope_layers: frink_models::rope_layers::RopeLayers::All,
9871            layer_shapes: frink_models::layer_shapes::LayerShapes::Uniform,
9872            name: "synthetic-kimi-server-test",
9873            n_layers: 1,
9874            n_mtp_blocks: 0,
9875            hidden_dim,
9876            n_heads: 1,
9877            n_kv_heads: 1,
9878            head_dim: 4,
9879            v_head_dim: None,
9880            vocab_size,
9881            rope_theta: 10000.0,
9882            rms_norm_eps: 1e-5,
9883            post_norm_eps: 1e-5,
9884            sliding_window: None,
9885            moe: MoeLayerConfig {
9886                expert_weights_scale: 1.0,
9887                routed_weight_before_ffn: false,
9888                n_experts: 1,
9889                n_experts_active: 1,
9890                n_shared_experts: 0,
9891                hidden_dim,
9892                expert_ffn_dim: 4,
9893                gating: GatingFunction::Sigmoid,
9894                norm_topk_prob: true,
9895                expert_group_count: None,
9896                expert_group_used_count: None,
9897            },
9898            // Layer 0 is the sole dense leading layer, using KDA
9899            // attention (real Kimi K3's own layer-0 shape) -- the
9900            // 1-indexed `kda_layers`/`full_attn_layers` convention is
9901            // `ModelConfig::layer_attention_kind`'s, not this test's.
9902            n_dense_leading_layers: 1,
9903            moe_interleave_step: None,
9904            norm_function: frink_models::norm::NormFunction::Rms,
9905            attention: AttentionKind::KimiHybrid(KimiHybridAttention {
9906                kda_layers: vec![1],
9907                full_attn_layers: vec![],
9908                mla: MlaConfig {
9909                    num_heads: mla_num_heads,
9910                    q_lora_rank: mla_q_lora_rank,
9911                    kv_lora_rank: mla_kv_lora_rank,
9912                    qk_nope_head_dim: mla_qk_nope_head_dim,
9913                    qk_rope_head_dim: mla_qk_rope_head_dim,
9914                    v_head_dim: mla_v_head_dim,
9915                    use_output_gate: true,
9916                    rope: None,
9917                },
9918                kda: KdaConfig {
9919                    num_heads: kda_num_heads,
9920                    head_dim: kda_head_dim,
9921                    short_conv_kernel_size: conv_kernel,
9922                    gate_lower_bound: -5.0,
9923                    use_full_rank_gate: true,
9924                },
9925            }),
9926            rope_freqs: None,
9927            rope_attn_factor: 1.0,
9928            rope_dim: None,
9929            rope_dim_swa: None,
9930            rope_freqs_long: None,
9931            rope_freqs_short: None,
9932            rope_orig_ctx: None,
9933            rope_layout: frink_models::config::RopeLayout::Neox,
9934            qk_norm_style: frink_models::capability::QkNormStyle::WholeVector,
9935            swa_layers: frink_models::swa_layers::SwaLayers::All,
9936            attn_logit_softcap: None,
9937            final_logit_softcap: None,
9938            embedding_scale: None,
9939            residual_scale: None,
9940            normed_residual_scale: None,
9941            clamp_kqv: None,
9942            attn_temperature: None,
9943            router_input: frink_models::router_input::RouterInput::NormedFfnInput,
9944            block_sub_norms: false,
9945            parallel_residual: false,
9946            learned_positions: false,
9947            attn_value_scale: None,
9948            alibi_max_bias: None,
9949            layer_loops: None,
9950            skip_stream: false,
9951            parallel_ssm: false,
9952            swa_chunked: false,
9953            weightless_qk_norm: false,
9954            logit_multiplier: None,
9955            attention_scale: None,
9956            rope_theta_swa: None,
9957            ffn_activation: frink_models::config::FfnActivation::Swiglu,
9958            best_effort_fields: &["synthetic test config, not a real preset"],
9959        };
9960        let hp = KimiRealHparams {
9961            hidden_dim,
9962            kda_num_heads,
9963            kda_head_dim,
9964            mla_num_heads,
9965            mla_q_lora_rank,
9966            mla_kv_lora_rank,
9967            mla_qk_nope_head_dim,
9968            mla_qk_rope_head_dim,
9969            mla_v_head_dim,
9970            dense_intermediate_dim: dense_intermediate,
9971            moe_hidden_dim: hidden_dim,
9972            moe_intermediate_dim: 4,
9973            n_experts: 1,
9974            num_shared_experts: 0,
9975        };
9976
9977        // Every real tensor name `kimi_loader::load_kimi_layer` (dense
9978        // FFN + KDA attention + block residual) and
9979        // `load_kimi_checkpoint` (top-level) actually read.
9980        let prefix = "language_model.model.layers.0";
9981        let mut tensors: Vec<(String, Vec<usize>, Vec<f32>)> = Vec::new();
9982        let push = |tensors: &mut Vec<(String, Vec<usize>, Vec<f32>)>,
9983                    name: String,
9984                    shape: Vec<usize>,
9985                    n: usize| {
9986            tensors.push((name, shape, vec![0.01f32; n]));
9987        };
9988        push(
9989            &mut tensors,
9990            format!("{prefix}.input_layernorm.weight"),
9991            vec![hidden_dim],
9992            hidden_dim,
9993        );
9994        push(
9995            &mut tensors,
9996            format!("{prefix}.post_attention_layernorm.weight"),
9997            vec![hidden_dim],
9998            hidden_dim,
9999        );
10000        push(
10001            &mut tensors,
10002            format!("{prefix}.self_attention_res_norm.weight"),
10003            vec![hidden_dim],
10004            hidden_dim,
10005        );
10006        push(
10007            &mut tensors,
10008            format!("{prefix}.self_attention_res_proj.weight"),
10009            vec![1, hidden_dim],
10010            hidden_dim,
10011        );
10012        push(
10013            &mut tensors,
10014            format!("{prefix}.mlp_res_norm.weight"),
10015            vec![hidden_dim],
10016            hidden_dim,
10017        );
10018        push(
10019            &mut tensors,
10020            format!("{prefix}.mlp_res_proj.weight"),
10021            vec![1, hidden_dim],
10022            hidden_dim,
10023        );
10024        push(
10025            &mut tensors,
10026            format!("{prefix}.self_attn.q_proj.weight"),
10027            vec![kda_proj, hidden_dim],
10028            kda_proj * hidden_dim,
10029        );
10030        push(
10031            &mut tensors,
10032            format!("{prefix}.self_attn.k_proj.weight"),
10033            vec![kda_proj, hidden_dim],
10034            kda_proj * hidden_dim,
10035        );
10036        push(
10037            &mut tensors,
10038            format!("{prefix}.self_attn.v_proj.weight"),
10039            vec![kda_proj, hidden_dim],
10040            kda_proj * hidden_dim,
10041        );
10042        push(
10043            &mut tensors,
10044            format!("{prefix}.self_attn.q_conv1d.weight"),
10045            vec![kda_proj, 1, conv_kernel],
10046            kda_proj * conv_kernel,
10047        );
10048        push(
10049            &mut tensors,
10050            format!("{prefix}.self_attn.k_conv1d.weight"),
10051            vec![kda_proj, 1, conv_kernel],
10052            kda_proj * conv_kernel,
10053        );
10054        push(
10055            &mut tensors,
10056            format!("{prefix}.self_attn.v_conv1d.weight"),
10057            vec![kda_proj, 1, conv_kernel],
10058            kda_proj * conv_kernel,
10059        );
10060        push(
10061            &mut tensors,
10062            format!("{prefix}.self_attn.A_log"),
10063            vec![kda_num_heads],
10064            kda_num_heads,
10065        );
10066        push(
10067            &mut tensors,
10068            format!("{prefix}.self_attn.f_a_proj.weight"),
10069            vec![kda_head_dim, hidden_dim],
10070            kda_head_dim * hidden_dim,
10071        );
10072        push(
10073            &mut tensors,
10074            format!("{prefix}.self_attn.f_b_proj.weight"),
10075            vec![kda_proj, kda_head_dim],
10076            kda_proj * kda_head_dim,
10077        );
10078        push(
10079            &mut tensors,
10080            format!("{prefix}.self_attn.dt_bias"),
10081            vec![kda_proj],
10082            kda_proj,
10083        );
10084        push(
10085            &mut tensors,
10086            format!("{prefix}.self_attn.b_proj.weight"),
10087            vec![kda_num_heads, hidden_dim],
10088            kda_num_heads * hidden_dim,
10089        );
10090        push(
10091            &mut tensors,
10092            format!("{prefix}.self_attn.g_proj.weight"),
10093            vec![kda_proj, hidden_dim],
10094            kda_proj * hidden_dim,
10095        );
10096        push(
10097            &mut tensors,
10098            format!("{prefix}.self_attn.o_norm.weight"),
10099            vec![kda_head_dim],
10100            kda_head_dim,
10101        );
10102        push(
10103            &mut tensors,
10104            format!("{prefix}.self_attn.o_proj.weight"),
10105            vec![hidden_dim, kda_proj],
10106            hidden_dim * kda_proj,
10107        );
10108        push(
10109            &mut tensors,
10110            format!("{prefix}.mlp.gate_proj.weight"),
10111            vec![dense_intermediate, hidden_dim],
10112            dense_intermediate * hidden_dim,
10113        );
10114        push(
10115            &mut tensors,
10116            format!("{prefix}.mlp.up_proj.weight"),
10117            vec![dense_intermediate, hidden_dim],
10118            dense_intermediate * hidden_dim,
10119        );
10120        push(
10121            &mut tensors,
10122            format!("{prefix}.mlp.down_proj.weight"),
10123            vec![hidden_dim, dense_intermediate],
10124            hidden_dim * dense_intermediate,
10125        );
10126        push(
10127            &mut tensors,
10128            "language_model.model.embed_tokens.weight".to_string(),
10129            vec![vocab_size, hidden_dim],
10130            vocab_size * hidden_dim,
10131        );
10132        push(
10133            &mut tensors,
10134            "language_model.lm_head.weight".to_string(),
10135            vec![vocab_size, hidden_dim],
10136            vocab_size * hidden_dim,
10137        );
10138        push(
10139            &mut tensors,
10140            "language_model.model.norm.weight".to_string(),
10141            vec![hidden_dim],
10142            hidden_dim,
10143        );
10144        push(
10145            &mut tensors,
10146            "language_model.model.output_attn_res_norm.weight".to_string(),
10147            vec![hidden_dim],
10148            hidden_dim,
10149        );
10150        push(
10151            &mut tensors,
10152            "language_model.model.output_attn_res_proj.weight".to_string(),
10153            vec![1, hidden_dim],
10154            hidden_dim,
10155        );
10156
10157        // Unique per CALL, not per (pid, vocab_size). Both callers of
10158        // this helper use the same `vocab_size`, so keying on it gave
10159        // the two tests one directory -- and `fs::write` opens with
10160        // `O_TRUNC`, so one test rewriting the shard truncated it to
10161        // zero while the other's `frink-safetensors` MMAP of that
10162        // exact file was live. Touching a mapping past the end of its
10163        // file is SIGBUS, which kills the whole test binary rather than
10164        // failing one test, and only when the two happen to overlap --
10165        // so it showed up as an occasional unexplained CI crash.
10166        //
10167        // A counter and not a thread id: the harness reuses threads
10168        // across tests, so two sequential tests can share one.
10169        static FIXTURE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
10170        let dir = std::env::temp_dir().join(format!(
10171            "frink_server_kimi_e2e_test_{}_{}",
10172            std::process::id(),
10173            FIXTURE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
10174        ));
10175        std::fs::create_dir_all(&dir).unwrap();
10176        let shard_bytes = write_safetensors_shard(&tensors);
10177        std::fs::write(dir.join("shard0.safetensors"), &shard_bytes).unwrap();
10178        let map_entries: Vec<String> = tensors
10179            .iter()
10180            .map(|(name, ..)| format!("\"{name}\":\"shard0.safetensors\""))
10181            .collect();
10182        let index = format!("{{\"weight_map\":{{{}}}}}", map_entries.join(","));
10183        std::fs::write(dir.join("model.safetensors.index.json"), &index).unwrap();
10184
10185        // A real tiktoken-format vocab file: one base64-encoded byte
10186        // plus its rank per line -- enough to round-trip an ASCII
10187        // prompt without needing the real 163584-entry Kimi K3 vocab.
10188        use base64::Engine;
10189        let vocab_lines: Vec<String> = (0..vocab_size as u32)
10190            .map(|b| {
10191                let b64 = base64::engine::general_purpose::STANDARD.encode([b as u8]);
10192                format!("{b64} {b}")
10193            })
10194            .collect();
10195        std::fs::write(dir.join("tiktoken.model"), vocab_lines.join("\n")).unwrap();
10196
10197        let loaded = model::load_kimi_checkpoint_with_config(dir.to_str().unwrap(), model_cfg, hp)
10198            .expect("must load the synthetic Kimi checkpoint end to end");
10199        std::fs::remove_dir_all(&dir).ok();
10200        loaded
10201    }
10202
10203    /// The real end-to-end proof for Kimi-through-the-server: a real
10204    /// synthetic Kimi K3 checkpoint served through the exact same
10205    /// `run_generation` entry point the HTTP handlers call for the
10206    /// GGUF path. Proves the whole new plumbing end to end: directory-
10207    /// shaped checkpoint loading, `KimiEngine`/`KimiTokenizer` wired
10208    /// through the `Model` enum, and `generate::generate_engine`
10209    /// producing real, bounded generated text.
10210    #[test]
10211    fn kimi_model_serves_real_text_end_to_end_via_run_generation() {
10212        let loaded = build_synthetic_kimi_loaded();
10213        let state = build_app_state(
10214            StartupModels {
10215                loaded: model::LoadedModel::Kimi(loaded),
10216                embedding: None,
10217            },
10218            None,
10219            None,
10220            None,
10221            false,
10222            None,
10223            Arc::new(health::Detection::ready(health::probe_backends())),
10224        );
10225        let active = state.active().expect("a freshly built state has a model");
10226        assert_eq!(active.tokenizer_kind(), "kimi-tiktoken-bpe");
10227        assert!(!active.is_synthetic());
10228
10229        let produced = run_generation(
10230            active.generative().unwrap(),
10231            "hi",
10232            &greedy_params(5),
10233            None,
10234            None,
10235            None,
10236            None,
10237            None,
10238            None,
10239        )
10240        .expect("a real Kimi checkpoint must generate without error");
10241        assert!(matches!(
10242            produced.choices[0].finish,
10243            FinishReason::Length | FinishReason::Stop
10244        ));
10245    }
10246
10247    /// The THIRD decode path: `generate_engine`, which serves every
10248    /// model that is not a `Decoder`.
10249    ///
10250    /// This is where a constraint gets dropped without anyone noticing.
10251    /// JSON mode was honoured on the `Decoder` path and silently not on
10252    /// this one, because this path had no tokenizer to hand the mask.
10253    /// A grammar must reach it too, and this checkpoint's vocabulary is
10254    /// one token per byte value, so `root ::= "a"+` has exactly one
10255    /// legal token (97) and the answer is decidable: all `a`, however
10256    /// the random weights would otherwise have decoded.
10257    ///
10258    /// The unconstrained run beside it is the vacuity check.
10259    #[test]
10260    fn a_grammar_constrains_the_engine_decode_path() {
10261        let loaded = build_synthetic_kimi_loaded();
10262        let state = build_app_state(
10263            StartupModels {
10264                loaded: model::LoadedModel::Kimi(loaded),
10265                embedding: None,
10266            },
10267            None,
10268            None,
10269            None,
10270            false,
10271            None,
10272            Arc::new(health::Detection::ready(health::probe_backends())),
10273        );
10274        let active = state.active().expect("a freshly built state has a model");
10275
10276        let run = |grammar: Option<&str>| {
10277            let mut params = greedy_params(6);
10278            params.grammar = grammar.map(|src| {
10279                Arc::new(
10280                    frink_models::grammar::Grammar::from_str_with_root(src, "root")
10281                        .expect("test grammar parses"),
10282                )
10283            });
10284            run_generation(
10285                active.generative().unwrap(),
10286                "hi",
10287                &params,
10288                None,
10289                None,
10290                None,
10291                None,
10292                None,
10293                None,
10294            )
10295        };
10296
10297        let produced = run(None).expect("the unconstrained run must serve");
10298        let unconstrained = produced.choices[0].text.clone();
10299        assert!(
10300            unconstrained.chars().any(|c| c != 'a'),
10301            "the unconstrained run produced only `a` ({unconstrained:?}), so the \
10302             constrained run below would prove nothing"
10303        );
10304
10305        let produced =
10306            run(Some(r#"root ::= "a"+"#)).expect("a grammar this vocabulary can spell must serve");
10307        let one = produced.choices.into_iter().next().unwrap();
10308        let (finish, constrained) = (one.finish, one.text);
10309        assert!(
10310            !constrained.is_empty() && constrained.chars().all(|c| c == 'a'),
10311            "the engine decode path served text its grammar forbids ({constrained:?}): \
10312             the constraint was dropped between `generate_engine` and the sampler"
10313        );
10314        assert!(matches!(finish, FinishReason::Length | FinishReason::Stop));
10315    }
10316
10317    /// Explicit proof of the "gate, don't paper over" design decision
10318    /// (see `frink_models::engine`'s module docs): even when an operator configures
10319    /// a KV block pool and/or prefix cache, a Kimi request must never
10320    /// consult either -- `generate_engine`'s signature has no
10321    /// parameter for them at all, so this isn't just an unexercised
10322    /// code path, it's structurally impossible for a Kimi request to
10323    /// touch them. Confirmed here by observing both are completely
10324    /// untouched (pool blocks unchanged, cache stats unchanged) after a
10325    /// real Kimi generation runs alongside both.
10326    #[test]
10327    fn kv_pool_and_prefix_cache_are_never_consulted_for_a_kimi_model() {
10328        let loaded = build_synthetic_kimi_loaded();
10329        let state = build_app_state(
10330            StartupModels {
10331                loaded: model::LoadedModel::Kimi(loaded),
10332                embedding: None,
10333            },
10334            None,
10335            None,
10336            None,
10337            false,
10338            None,
10339            Arc::new(health::Detection::ready(health::probe_backends())),
10340        );
10341
10342        let pool = Arc::new(Mutex::new(frink_core::cache::KvBlockPool::new(64, 4)));
10343        let kv_pool_config = generate::KvPoolConfig {
10344            pool: pool.clone(),
10345            queue_wait: Duration::ZERO,
10346        };
10347        let pc = Mutex::new(PrefixCache::new(4));
10348
10349        run_generation(
10350            state
10351                .active()
10352                .expect("a freshly built state has a model")
10353                .generative()
10354                .unwrap(),
10355            "hi",
10356            &greedy_params(5),
10357            Some(&kv_pool_config),
10358            None,
10359            Some(&pc),
10360            None,
10361            None,
10362            None,
10363        )
10364        .expect("a real Kimi checkpoint must generate without error");
10365
10366        assert_eq!(
10367            pool.lock().unwrap().free_blocks(),
10368            4,
10369            "the KV pool must be completely untouched by a Kimi request"
10370        );
10371        let stats = pc.lock().unwrap().stats();
10372        assert_eq!(
10373            stats.hits + stats.misses,
10374            0,
10375            "the prefix cache must never be consulted for a Kimi request"
10376        );
10377    }
10378}