use std::{
convert::Infallible,
net::SocketAddr,
sync::{
atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
Arc,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use axum::{
extract::{rejection::JsonRejection, Request, State},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{
sse::{Event, Sse},
IntoResponse, Response,
},
routing::{get, post},
Json, Router,
};
use infr_core::config::Config;
use infr_engine::{ChatMessage, Delta, ToolCall};
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use tokio::sync::Semaphore;
mod metrics;
mod status;
pub use status::{DeviceMemory, GeneratorStatus};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Finish {
Stop,
Length,
ToolCalls,
}
impl Finish {
pub fn as_str(self) -> &'static str {
match self {
Finish::Stop => "stop",
Finish::Length => "length",
Finish::ToolCalls => "tool_calls",
}
}
}
pub trait ChatGenerator: Send + Sync {
fn chat(
&self,
messages: &[ChatMessage],
tools: Option<&serde_json::Value>,
tool_choice: Option<&str>,
params: &GenParams,
cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome>;
fn status(&self) -> GeneratorStatus;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChatOutcome {
pub finish: Finish,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cached_tokens: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextLengthExceeded {
pub message: String,
}
impl std::fmt::Display for ContextLengthExceeded {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ContextLengthExceeded {}
#[derive(Debug, Deserialize)]
pub struct ChatRequest {
pub model: String,
pub messages: Vec<ChatMessageDto>,
#[serde(default)]
pub stream: bool,
#[serde(default)]
pub tools: Option<serde_json::Value>,
#[serde(default)]
pub tool_choice: Option<serde_json::Value>,
#[serde(default, deserialize_with = "minus_one_is_unset")]
pub max_tokens: Option<u32>,
#[serde(default, deserialize_with = "minus_one_is_unset")]
pub max_completion_tokens: Option<u32>,
#[serde(default)]
pub temperature: Option<f32>,
#[serde(default)]
pub top_p: Option<f32>,
#[serde(default)]
pub top_k: Option<i64>,
#[serde(default, deserialize_with = "minus_one_is_unset")]
pub seed: Option<u64>,
#[serde(default)]
pub stop: Option<serde_json::Value>,
#[serde(default)]
pub presence_penalty: Option<f32>,
#[serde(default)]
pub frequency_penalty: Option<f32>,
#[serde(default)]
pub repeat_penalty: Option<f32>,
#[serde(default)]
pub stream_options: Option<StreamOptions>,
}
#[derive(Debug, Default, Deserialize)]
pub struct StreamOptions {
#[serde(default)]
pub include_usage: bool,
}
fn minus_one_is_unset<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: TryFrom<u64>,
{
use serde::de::Error;
match Option::<i128>::deserialize(d)? {
None | Some(-1) => Ok(None),
Some(v) => u64::try_from(v)
.ok()
.and_then(|v| T::try_from(v).ok())
.map(Some)
.ok_or_else(|| D::Error::custom(format!("{v} is out of range (use -1 for unset)"))),
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GenParams {
pub max_tokens: Option<u32>,
pub temperature: Option<f32>,
pub top_p: Option<f32>,
pub top_k: Option<usize>,
pub seed: Option<u64>,
pub presence_penalty: Option<f32>,
pub frequency_penalty: Option<f32>,
pub repeat_penalty: Option<f32>,
pub stop: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParamError {
pub param: &'static str,
pub message: String,
}
impl GenParams {
pub fn from_request(req: &ChatRequest) -> Result<Self, ParamError> {
let rng = |param: &'static str,
v: Option<f32>,
lo: f32,
hi: f32|
-> Result<Option<f32>, ParamError> {
match v {
Some(x) if !x.is_finite() || x < lo || x > hi => Err(ParamError {
param,
message: format!("{param} must be between {lo} and {hi}, got {x}"),
}),
other => Ok(other),
}
};
let top_k = match req.top_k {
Some(k) if k < 0 => {
return Err(ParamError {
param: "top_k",
message: format!("top_k must be >= 0, got {k}"),
})
}
Some(k) => Some(k as usize),
None => None,
};
let stop = match &req.stop {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::String(s)) => vec![s.clone()],
Some(serde_json::Value::Array(a)) => {
let mut v = Vec::with_capacity(a.len());
for item in a {
match item.as_str() {
Some(s) => v.push(s.to_string()),
None => {
return Err(ParamError {
param: "stop",
message: "stop must be a string or an array of strings".into(),
})
}
}
}
v
}
Some(_) => {
return Err(ParamError {
param: "stop",
message: "stop must be a string or an array of strings".into(),
})
}
};
if stop.len() > 4 {
return Err(ParamError {
param: "stop",
message: format!("at most 4 stop sequences are supported, got {}", stop.len()),
});
}
let stop: Vec<String> = stop.into_iter().filter(|s| !s.is_empty()).collect();
if let Some(p) = req.repeat_penalty {
if !p.is_finite() || p <= 0.0 {
return Err(ParamError {
param: "repeat_penalty",
message: format!("repeat_penalty must be > 0, got {p}"),
});
}
}
Ok(Self {
max_tokens: req.max_completion_tokens.or(req.max_tokens),
temperature: rng("temperature", req.temperature, 0.0, 2.0)?,
top_p: rng("top_p", req.top_p, 0.0, 1.0)?,
top_k,
seed: req.seed,
presence_penalty: rng("presence_penalty", req.presence_penalty, -2.0, 2.0)?,
frequency_penalty: rng("frequency_penalty", req.frequency_penalty, -2.0, 2.0)?,
repeat_penalty: req.repeat_penalty,
stop,
})
}
}
#[derive(Debug, Default)]
pub struct StopMatcher {
stops: Vec<String>,
held: String,
hit: bool,
}
impl StopMatcher {
pub fn new(stops: Vec<String>) -> Self {
Self {
stops: stops.into_iter().filter(|s| !s.is_empty()).collect(),
held: String::new(),
hit: false,
}
}
pub fn is_active(&self) -> bool {
!self.stops.is_empty()
}
pub fn hit(&self) -> bool {
self.hit
}
pub fn push(&mut self, piece: &str) -> String {
if self.hit {
return String::new();
}
if self.stops.is_empty() {
return piece.to_string();
}
self.held.push_str(piece);
if let Some(cut) = self
.stops
.iter()
.filter_map(|s| self.held.find(s.as_str()))
.min()
{
self.hit = true;
let out = self.held[..cut].to_string();
self.held.clear();
return out;
}
let hold = self.longest_partial_suffix();
let split = self.held.len() - hold;
let out = self.held[..split].to_string();
self.held.drain(..split);
out
}
pub fn flush(&mut self) -> String {
if self.hit {
return String::new();
}
std::mem::take(&mut self.held)
}
fn longest_partial_suffix(&self) -> usize {
let max = self
.stops
.iter()
.map(|s| s.len())
.max()
.unwrap_or(0)
.saturating_sub(1)
.min(self.held.len());
for n in (1..=max).rev() {
let start = self.held.len() - n;
if !self.held.is_char_boundary(start) {
continue;
}
let tail = &self.held[start..];
if self
.stops
.iter()
.any(|s| s.as_bytes().starts_with(tail.as_bytes()))
{
return n;
}
}
0
}
}
fn tool_choice_str(v: &serde_json::Value) -> Result<Option<String>, ParamError> {
match v {
serde_json::Value::String(s) => Ok(Some(s.clone())),
serde_json::Value::Object(_) => v
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.map(|s| Some(s.to_owned()))
.ok_or_else(|| ParamError {
param: "tool_choice",
message: "tool_choice object must have a string `function.name`".into(),
}),
_ => Err(ParamError {
param: "tool_choice",
message: "tool_choice must be \"auto\"/\"required\"/\"none\" or a function object"
.into(),
}),
}
}
const TOOL_CHOICE_POLICIES: [&str; 3] = ["auto", "none", "required"];
fn validate_tool_choice(
tool_choice: Option<&str>,
tools: Option<&serde_json::Value>,
) -> Result<(), ParamError> {
let Some(choice) = tool_choice else {
return Ok(());
};
if TOOL_CHOICE_POLICIES.contains(&choice) && choice != "required" {
return Ok(());
}
let names: Vec<&str> = tools
.and_then(|t| t.as_array())
.map(|a| {
a.iter()
.filter_map(|t| t.get("function")?.get("name")?.as_str())
.collect()
})
.unwrap_or_default();
if names.is_empty() {
return Err(ParamError {
param: "tool_choice",
message: format!(
"tool_choice {choice:?} requires a non-empty `tools` array; none was supplied"
),
});
}
if choice == "required" || names.contains(&choice) {
return Ok(());
}
Err(ParamError {
param: "tool_choice",
message: format!(
"tool_choice {choice:?} names no tool in `tools` (have: {})",
names.join(", ")
),
})
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ChatMessageDto {
pub role: String,
#[serde(default)]
pub content: Option<serde_json::Value>,
#[serde(default)]
pub tool_calls: Option<serde_json::Value>,
#[serde(default)]
pub tool_call_id: Option<String>,
#[serde(default)]
pub name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ModelsResponse {
pub object: &'static str,
pub data: Vec<ModelCard>,
}
#[derive(Debug, Serialize)]
pub struct ModelCard {
pub id: String,
pub object: &'static str,
pub owned_by: &'static str,
}
#[derive(Debug, Serialize)]
pub struct ChatCompletionResponse {
pub id: String,
pub object: &'static str,
pub created: i64,
pub model: String,
pub choices: Vec<CompletionChoice>,
pub usage: UsageInfo,
}
#[derive(Debug, Serialize)]
pub struct CompletionChoice {
pub index: u32,
pub message: AssistantMessage,
pub finish_reason: String,
}
#[derive(Debug, Serialize)]
pub struct AssistantMessage {
pub role: &'static str,
pub content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_calls: Option<Vec<OAIToolCall>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct OAIToolCall {
pub index: usize,
pub id: String,
#[serde(rename = "type")]
pub kind: &'static str,
pub function: OAIFunction,
}
#[derive(Debug, Clone, Serialize)]
pub struct OAIFunction {
pub name: String,
pub arguments: String,
}
#[derive(Debug, Serialize)]
pub struct UsageInfo {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
pub prompt_tokens_details: PromptTokensDetails,
}
#[derive(Debug, Serialize)]
pub struct PromptTokensDetails {
pub cached_tokens: u32,
}
impl UsageInfo {
pub fn from_outcome(outcome: &ChatOutcome) -> Self {
Self {
prompt_tokens: outcome.prompt_tokens,
completion_tokens: outcome.completion_tokens,
total_tokens: outcome
.prompt_tokens
.saturating_add(outcome.completion_tokens),
prompt_tokens_details: PromptTokensDetails {
cached_tokens: outcome.cached_tokens,
},
}
}
}
#[derive(Debug, Serialize)]
pub struct ChatCompletionChunk {
pub id: String,
pub object: &'static str,
pub created: i64,
pub model: String,
pub choices: Vec<ChunkChoice>,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage: Option<UsageInfo>,
}
#[derive(Debug, Serialize)]
pub struct ChunkChoice {
pub index: u32,
pub delta: DeltaPayload,
pub finish_reason: Option<String>,
}
#[derive(Debug, Default, Serialize)]
pub struct DeltaPayload {
#[serde(skip_serializing_if = "Option::is_none")]
pub role: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_calls: Option<Vec<OAIToolCall>>,
}
static REQ_SEQ: AtomicU64 = AtomicU64::new(1);
fn next_req_id() -> u64 {
REQ_SEQ.fetch_add(1, Ordering::Relaxed)
}
#[derive(Debug, Default)]
struct ServeStats {
interval_prompt_tokens: AtomicU64,
interval_gen_tokens: AtomicI64,
interval_completed: AtomicU64,
interval_failed: AtomicU64,
active: AtomicU64,
queued: AtomicU64,
window: AtomicU64,
lifetime: metrics::Lifetime,
}
impl ServeStats {
fn bump_gen(&self, n: i64) {
self.interval_gen_tokens.fetch_add(n, Ordering::Relaxed);
}
fn window(&self) -> u64 {
self.window.load(Ordering::Relaxed)
}
fn fold_completion(&self, rec: &ReqRecord) {
self.interval_prompt_tokens
.fetch_add(u64::from(rec.prompt_tokens), Ordering::Relaxed);
let correction = i64::from(rec.gen_tokens) - rec.deltas as i64;
if correction > 0 {
self.bump_gen(correction);
} else if correction < 0 && rec.window == self.window() {
let retractable = rec.deltas_in_window.min(i64::MAX as u64) as i64;
self.bump_gen(-correction.abs().min(retractable));
}
self.interval_completed.fetch_add(1, Ordering::Relaxed);
self.lifetime.fold_completion(rec);
}
fn fold_failure(&self) {
self.interval_completed.fetch_add(1, Ordering::Relaxed);
self.interval_failed.fetch_add(1, Ordering::Relaxed);
self.lifetime.fold_failure();
}
fn drain(&self, elapsed: Duration) -> StatsWindow {
self.window.fetch_add(1, Ordering::Relaxed);
StatsWindow {
elapsed,
prompt_tokens: self.interval_prompt_tokens.swap(0, Ordering::Relaxed),
gen_tokens: self.interval_gen_tokens.swap(0, Ordering::Relaxed).max(0) as u64,
completed: self.interval_completed.swap(0, Ordering::Relaxed),
failed: self.interval_failed.swap(0, Ordering::Relaxed),
active: self.active.load(Ordering::Relaxed),
queued: self.queued.load(Ordering::Relaxed),
busy_slots: 0,
total_slots: 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct StatsWindow {
elapsed: Duration,
prompt_tokens: u64,
gen_tokens: u64,
completed: u64,
failed: u64,
active: u64,
queued: u64,
busy_slots: u64,
total_slots: u64,
}
impl StatsWindow {
fn has_activity(&self) -> bool {
self.prompt_tokens > 0
|| self.gen_tokens > 0
|| self.completed > 0
|| self.active > 0
|| self.queued > 0
}
fn prefill_tps(&self) -> f64 {
per_second(self.prompt_tokens, self.elapsed)
}
fn decode_tps(&self) -> f64 {
per_second(self.gen_tokens, self.elapsed)
}
}
fn per_second(n: u64, d: Duration) -> f64 {
let secs = d.as_secs_f64();
if secs > 0.0 {
n as f64 / secs
} else {
0.0
}
}
struct QueuedGuard(Arc<ServeStats>);
impl QueuedGuard {
fn new(stats: Arc<ServeStats>) -> Self {
stats.queued.fetch_add(1, Ordering::Relaxed);
Self(stats)
}
}
impl Drop for QueuedGuard {
fn drop(&mut self) {
self.0.queued.fetch_sub(1, Ordering::Relaxed);
}
}
struct ActiveGuard(Arc<ServeStats>);
impl ActiveGuard {
fn new(stats: Arc<ServeStats>) -> Self {
stats.active.fetch_add(1, Ordering::Relaxed);
Self(stats)
}
}
impl Drop for ActiveGuard {
fn drop(&mut self) {
self.0.active.fetch_sub(1, Ordering::Relaxed);
}
}
#[derive(Debug)]
struct ReqTally {
started: Instant,
first_delta: Option<Instant>,
deltas: u64,
window: u64,
deltas_in_window: u64,
}
impl ReqTally {
fn new() -> Self {
Self {
started: Instant::now(),
first_delta: None,
deltas: 0,
window: 0,
deltas_in_window: 0,
}
}
fn on_text_delta(&mut self, stats: &ServeStats) {
if self.first_delta.is_none() {
self.first_delta = Some(Instant::now());
}
let w = stats.window();
if w != self.window {
self.window = w;
self.deltas_in_window = 0;
}
self.deltas += 1;
self.deltas_in_window += 1;
stats.bump_gen(1);
}
fn finish(&self, outcome: ChatOutcome, finish: Finish) -> ReqRecord {
let total = self.started.elapsed();
let prefill = self
.first_delta
.map_or(total, |t| t.saturating_duration_since(self.started));
ReqRecord {
prompt_tokens: outcome.prompt_tokens.saturating_sub(outcome.cached_tokens),
gen_tokens: outcome.completion_tokens,
deltas: self.deltas,
window: self.window,
deltas_in_window: self.deltas_in_window,
prefill,
decode: total.saturating_sub(prefill),
total,
finish,
}
}
}
#[derive(Debug, Clone, Copy)]
struct ReqRecord {
prompt_tokens: u32,
gen_tokens: u32,
deltas: u64,
window: u64,
deltas_in_window: u64,
prefill: Duration,
decode: Duration,
total: Duration,
finish: Finish,
}
impl ReqRecord {
fn prefill_tps(&self) -> f64 {
per_second(u64::from(self.prompt_tokens), self.prefill)
}
fn decode_tps(&self) -> f64 {
per_second(u64::from(self.gen_tokens), self.decode)
}
}
fn log_request_done(req_id: u64, model: &str, stream: bool, rec: &ReqRecord) {
tracing::info!(
req = req_id,
model,
stream,
prompt_tokens = rec.prompt_tokens,
gen_tokens = rec.gen_tokens,
prefill_tps = format_args!("{:.1}", rec.prefill_tps()),
decode_tps = format_args!("{:.1}", rec.decode_tps()),
total_ms = format_args!("{:.0}", rec.total.as_secs_f64() * 1000.0),
finish = rec.finish.as_str(),
"request done"
);
}
fn log_request_start(
req_id: u64,
route: &'static str,
model: &str,
messages: usize,
prompt_chars: usize,
max_tokens: Option<u32>,
stream: bool,
) {
tracing::info!(
req = req_id,
route,
model,
messages,
prompt_chars,
max_tokens = ?max_tokens,
stream,
"request start"
);
}
fn stats_interval(cfg: &Config) -> Option<Duration> {
let secs = cfg.serve.stats_interval_secs;
(secs > 0).then(|| Duration::from_secs(secs))
}
async fn stats_reporter(state: AppState, period: Duration) {
const POLL: Duration = Duration::from_millis(50);
let mut last = Instant::now();
loop {
tokio::time::sleep(POLL).await;
let shutting_down = infr_core::shutdown::shutdown_requested();
if !shutting_down && last.elapsed() < period {
continue;
}
let mut window = state.stats.drain(last.elapsed());
(window.busy_slots, window.total_slots) = state.slot_occupancy();
last = Instant::now();
if window.has_activity() {
tracing::info!(
interval_s = format_args!("{:.1}", window.elapsed.as_secs_f64()),
prefill_tps = format_args!("{:.1}", window.prefill_tps()),
decode_tps = format_args!("{:.1}", window.decode_tps()),
gen_tokens = window.gen_tokens,
prompt_tokens = window.prompt_tokens,
completed = window.completed,
failed = window.failed,
active = window.active,
queued = window.queued,
kv_slots = format_args!("{}/{}", window.busy_slots, window.total_slots),
"serve stats"
);
}
if shutting_down {
return;
}
}
}
#[derive(Clone)]
struct ModelEntry {
id: Arc<str>,
engine: Option<Arc<dyn ChatGenerator>>,
slots: Arc<Semaphore>,
capacity: usize,
}
impl ModelEntry {
fn new(id: &str, engine: Option<Arc<dyn ChatGenerator>>, n_parallel: usize) -> Self {
let capacity = n_parallel.max(1);
Self {
id: Arc::from(id),
engine,
slots: Arc::new(Semaphore::new(capacity)),
capacity,
}
}
fn busy(&self) -> usize {
self.capacity - self.slots.available_permits().min(self.capacity)
}
}
#[derive(Clone)]
pub struct AppState {
models: Arc<Vec<ModelEntry>>,
cfg: Arc<Config>,
stats: Arc<ServeStats>,
started: Instant,
}
impl AppState {
pub fn new(
generator: Arc<dyn ChatGenerator>,
model_id: impl Into<String>,
n_parallel: usize,
cfg: Arc<Config>,
) -> Self {
Self {
models: Arc::new(vec![ModelEntry::new(
&model_id.into(),
Some(generator),
n_parallel,
)]),
cfg,
stats: Arc::default(),
started: Instant::now(),
}
}
pub fn multi(entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>, cfg: Arc<Config>) -> Self {
assert!(
!entries.is_empty(),
"AppState::multi needs at least one model"
);
let models = entries
.into_iter()
.map(|(id, gen, n)| ModelEntry::new(&id, Some(gen), n))
.collect();
Self {
models: Arc::new(models),
cfg,
stats: Arc::default(),
started: Instant::now(),
}
}
pub fn headless(model_id: impl Into<String>, cfg: Arc<Config>) -> Self {
Self {
models: Arc::new(vec![ModelEntry::new(&model_id.into(), None, 1)]),
cfg,
stats: Arc::default(),
started: Instant::now(),
}
}
fn slot_occupancy(&self) -> (u64, u64) {
self.models.iter().fold((0, 0), |(busy, total), m| {
(busy + m.busy() as u64, total + m.capacity as u64)
})
}
fn route(&self, requested: &str) -> ModelEntry {
self.models
.iter()
.find(|m| &*m.id == requested)
.unwrap_or(&self.models[0])
.clone()
}
}
pub fn build_router(state: AppState) -> Router {
Router::new()
.route("/health", get(health_handler))
.route("/v1/models", get(models_handler))
.route("/metrics", get(metrics::metrics_handler))
.route("/status", get(status::status_handler))
.route(
"/v1/chat/completions",
post(chat_completions_handler)
.route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
)
.with_state(state)
}
async fn require_auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
if let Some(denied) = auth_gate(&state.cfg, req.headers()) {
return denied;
}
next.run(req).await
}
pub async fn serve(
generator: Arc<dyn ChatGenerator>,
model_id: String,
addr: SocketAddr,
n_parallel: usize,
cfg: Arc<Config>,
) -> anyhow::Result<()> {
serve_state(AppState::new(generator, model_id, n_parallel, cfg), addr).await
}
pub async fn serve_multi(
entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>,
addr: SocketAddr,
cfg: Arc<Config>,
) -> anyhow::Result<()> {
serve_state(AppState::multi(entries, cfg), addr).await
}
async fn serve_state(state: AppState, addr: SocketAddr) -> anyhow::Result<()> {
let n_models = state.models.len();
let reporter = stats_interval(&state.cfg)
.map(|period| tokio::spawn(stats_reporter(state.clone(), period)));
let router = build_router(state);
let listener = tokio::net::TcpListener::bind(addr).await?;
tracing::info!(%addr, %n_models, "infr-server listening");
let served = axum::serve(listener, router)
.with_graceful_shutdown(shutdown_latched())
.await;
if let Some(h) = reporter {
h.abort();
}
served?;
Ok(())
}
async fn shutdown_latched() {
while !infr_core::shutdown::shutdown_requested() {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
tracing::info!("shutdown requested — draining in-flight requests");
}
async fn health_handler() -> StatusCode {
StatusCode::OK
}
async fn models_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(denied) = auth_gate(&state.cfg, &headers) {
return denied;
}
Json(ModelsResponse {
object: "list",
data: state
.models
.iter()
.map(|m| ModelCard {
id: m.id.to_string(),
object: "model",
owned_by: "local",
})
.collect(),
})
.into_response()
}
async fn chat_completions_handler(
State(state): State<AppState>,
body: Result<Json<ChatRequest>, JsonRejection>,
) -> Response {
let Json(req) = match body {
Ok(j) => j,
Err(e) => return body_rejection(e),
};
let mut params = match GenParams::from_request(&req) {
Ok(p) => p,
Err(e) => return param_error(Some(e.param), e.message),
};
params.max_tokens = clamp_max_tokens(params.max_tokens, max_tokens_cap(&state.cfg));
let messages: Vec<ChatMessage> = req.messages.iter().map(dto_to_engine).collect();
let tools: Option<serde_json::Value> = req.tools.clone();
let tool_choice: Option<String> = match req.tool_choice.as_ref() {
None | Some(serde_json::Value::Null) => None,
Some(v) => match tool_choice_str(v) {
Ok(tc) => tc,
Err(e) => return param_error(Some(e.param), e.message),
},
};
if let Err(e) = validate_tool_choice(tool_choice.as_deref(), tools.as_ref()) {
return param_error(Some(e.param), e.message);
}
let entry = state.route(&req.model);
let model_id = entry.id.to_string();
let ctx = ReqCtx {
id: next_req_id(),
cid: make_id(),
model_id,
created: unix_ts(),
deadline: request_timeout(&state.cfg),
stream: req.stream,
include_usage: req.stream_options.as_ref().is_some_and(|o| o.include_usage),
stats: state.stats.clone(),
};
log_request_start(
ctx.id,
"/v1/chat/completions",
&ctx.model_id,
messages.len(),
messages.iter().map(|m| m.content.len()).sum(),
params.max_tokens,
ctx.stream,
);
if ctx.stream {
streaming(entry, messages, tools, tool_choice, params, ctx).await
} else {
non_streaming(entry, messages, tools, tool_choice, params, ctx).await
}
}
struct ReqCtx {
id: u64,
cid: String,
model_id: String,
created: i64,
deadline: Option<Duration>,
stream: bool,
include_usage: bool,
stats: Arc<ServeStats>,
}
async fn non_streaming(
entry: ModelEntry,
messages: Vec<ChatMessage>,
tools: Option<serde_json::Value>,
tool_choice: Option<String>,
params: GenParams,
ctx: ReqCtx,
) -> Response {
let ReqCtx {
id: req_id,
cid,
model_id,
created,
deadline,
stream,
include_usage: _,
stats,
} = ctx;
let queued = QueuedGuard::new(stats.clone());
let Ok(permit) = entry.slots.clone().acquire_owned().await else {
stats.fold_failure();
tracing::warn!(req = req_id, "rejected — server shutting down");
return json_error(
StatusCode::SERVICE_UNAVAILABLE,
"server shutting down".into(),
);
};
drop(queued);
let active = ActiveGuard::new(stats.clone());
let engine_arc = entry.engine.clone();
let cid_blk = cid.clone();
let stats_blk = stats.clone();
let cancel = Arc::new(AtomicBool::new(false));
let cancel_blk = cancel.clone();
let _hangup = CancelOnDrop(cancel.clone());
let mut handle = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
let _permit = permit;
let _active = active;
let Some(engine) = engine_arc else {
anyhow::bail!("no engine loaded");
};
let mut reasoning = String::new();
let mut content = String::new();
let mut tool_calls: Vec<OAIToolCall> = Vec::new();
let mut tally = ReqTally::new();
let outcome = engine.chat(
&messages,
tools.as_ref(),
tool_choice.as_deref(),
¶ms,
&cancel_blk,
&mut |delta| match delta {
Delta::Reasoning(t) => {
tally.on_text_delta(&stats_blk);
reasoning.push_str(&t);
}
Delta::Content(t) => {
tally.on_text_delta(&stats_blk);
content.push_str(&t);
}
Delta::ToolCall { name, arguments } => {
let idx = tool_calls.len();
tool_calls.push(OAIToolCall {
index: idx,
id: tool_call_id(&cid_blk, idx),
kind: "function",
function: OAIFunction { name, arguments },
});
}
},
)?;
Ok((reasoning, content, tool_calls, outcome, tally))
});
let mut deadline_hit = false;
let joined = match deadline {
None => handle.await,
Some(d) => match tokio::time::timeout(d, &mut handle).await {
Ok(joined) => joined,
Err(_elapsed) => {
deadline_hit = true;
cancel.store(true, Ordering::Relaxed);
tracing::warn!(
req = req_id,
timeout_s = d.as_secs(),
"request deadline hit — returning the partial completion"
);
handle.await
}
},
};
let result = joined.map_err(anyhow::Error::from).and_then(|r| r);
match result {
Err(e) => {
stats.fold_failure();
tracing::warn!(req = req_id, error = %e, "request failed");
match e.downcast_ref::<ContextLengthExceeded>() {
Some(c) => (StatusCode::BAD_REQUEST, Json(context_length_body(c))).into_response(),
None => json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
}
}
Ok((reasoning, content, tool_calls, outcome, tally)) => {
let finish = if !tool_calls.is_empty() {
Finish::ToolCalls
} else if deadline_hit {
Finish::Length
} else {
outcome.finish
};
let rec = tally.finish(outcome, finish);
stats.fold_completion(&rec);
log_request_done(req_id, &model_id, stream, &rec);
Json(ChatCompletionResponse {
id: cid,
object: "chat.completion",
created,
model: model_id,
choices: vec![CompletionChoice {
index: 0,
message: AssistantMessage {
role: "assistant",
content: if content.is_empty() {
None
} else {
Some(content.clone())
},
reasoning_content: if reasoning.is_empty() {
None
} else {
Some(reasoning)
},
tool_calls: if tool_calls.is_empty() {
None
} else {
Some(tool_calls)
},
},
finish_reason: finish.as_str().into(),
}],
usage: UsageInfo::from_outcome(&outcome),
})
.into_response()
}
}
}
async fn streaming(
entry: ModelEntry,
messages: Vec<ChatMessage>,
tools: Option<serde_json::Value>,
tool_choice: Option<String>,
params: GenParams,
ctx: ReqCtx,
) -> Response {
let ReqCtx {
id: req_id,
cid,
model_id,
created,
deadline,
stream,
include_usage,
stats,
} = ctx;
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
let queued = QueuedGuard::new(stats.clone());
let Ok(permit) = entry.slots.clone().acquire_owned().await else {
stats.fold_failure();
tracing::warn!(req = req_id, "rejected — server shutting down");
return json_error(
StatusCode::SERVICE_UNAVAILABLE,
"server shutting down".into(),
);
};
drop(queued);
let active = ActiveGuard::new(stats.clone());
let engine_arc = entry.engine.clone();
let tx_cb = tx.clone();
let cid_cb = cid.clone();
let model_cb = model_id.clone();
let stats_cb = stats.clone();
let cancel = Arc::new(AtomicBool::new(false));
let cancel_cb = cancel.clone();
let hangup_done = cancel_on_hangup(&tx, cancel.clone());
let deadline_hit = Arc::new(AtomicBool::new(false));
let deadline_hit_cb = deadline_hit.clone();
let done_tx = deadline.map(|d| arm_deadline(d, cancel.clone(), deadline_hit.clone()));
tokio::task::spawn_blocking(move || {
let _permit = permit;
let _active = active;
let _done_tx = done_tx;
let _hangup_done = hangup_done;
let mut done = DoneGuard {
tx: tx.clone(),
req_id,
stats: stats.clone(),
settled: false,
};
let _ = tx.send(Ok(sse_chunk(
&cid,
&model_id,
created,
DeltaPayload {
role: Some("assistant".into()),
..Default::default()
},
None,
)));
let Some(engine) = engine_arc else {
done.fail("no engine loaded");
return;
};
let mut tc_index = 0usize;
let mut saw_tool_call = false;
let mut tally = ReqTally::new();
let res = engine.chat(
&messages,
tools.as_ref(),
tool_choice.as_deref(),
¶ms,
&cancel_cb,
&mut |delta| {
let payload = match delta {
Delta::Reasoning(t) => {
tally.on_text_delta(&stats_cb);
DeltaPayload {
reasoning_content: Some(t),
..Default::default()
}
}
Delta::Content(t) => {
tally.on_text_delta(&stats_cb);
DeltaPayload {
content: Some(t),
..Default::default()
}
}
Delta::ToolCall { name, arguments } => {
let tc = OAIToolCall {
index: tc_index,
id: tool_call_id(&cid_cb, tc_index),
kind: "function",
function: OAIFunction { name, arguments },
};
tc_index += 1;
saw_tool_call = true;
DeltaPayload {
tool_calls: Some(vec![tc]),
..Default::default()
}
}
};
if tx_cb
.send(Ok(sse_chunk(&cid_cb, &model_cb, created, payload, None)))
.is_err()
{
cancel_cb.store(true, Ordering::Relaxed);
}
},
);
match res {
Ok(outcome) => {
let finish = if saw_tool_call {
Finish::ToolCalls
} else if deadline_hit_cb.load(Ordering::Relaxed) {
Finish::Length
} else {
outcome.finish
};
let _ = tx.send(Ok(sse_chunk(
&cid,
&model_id,
created,
DeltaPayload::default(),
Some(finish.as_str().into()),
)));
if include_usage {
let _ = tx.send(Ok(sse_usage_chunk(&cid, &model_id, created, &outcome)));
}
let rec = tally.finish(outcome, finish);
stats.fold_completion(&rec);
log_request_done(req_id, &model_id, stream, &rec);
done.settled();
}
Err(e) => {
match e.downcast_ref::<ContextLengthExceeded>() {
Some(c) => done.fail_with(context_length_body(c), &c.message),
None => done.fail(&e.to_string()),
}
}
}
});
let stream = futures_util::stream::unfold(rx, |mut rx| async move {
rx.recv().await.map(|item| (item, rx))
});
Sse::new(stream).into_response()
}
struct DoneGuard {
tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
req_id: u64,
stats: Arc<ServeStats>,
settled: bool,
}
impl DoneGuard {
fn settled(&mut self) {
self.settled = true;
}
fn fail(&mut self, msg: &str) {
self.fail_with(error_body(msg, "server_error"), msg);
}
fn fail_with(&mut self, body: serde_json::Value, msg: &str) {
if self.settled {
return;
}
self.settled = true;
let _ = self.tx.send(Ok(sse_error_event(&body)));
self.stats.fold_failure();
tracing::warn!(req = self.req_id, error = msg, "request failed");
}
}
impl Drop for DoneGuard {
fn drop(&mut self) {
self.fail("internal error: generation ended without a terminal frame");
let _ = self.tx.send(Ok(Event::default().data("[DONE]")));
}
}
fn error_body(msg: &str, ty: &str) -> serde_json::Value {
serde_json::json!({"error": {"message": msg, "type": ty}})
}
fn sse_error_event(body: &serde_json::Value) -> Event {
Event::default().data(body.to_string())
}
fn sse_chunk(
cid: &str,
model: &str,
created: i64,
delta: DeltaPayload,
finish_reason: Option<String>,
) -> Event {
let chunk = ChatCompletionChunk {
id: cid.to_owned(),
object: "chat.completion.chunk",
created,
model: model.to_owned(),
choices: vec![ChunkChoice {
index: 0,
delta,
finish_reason,
}],
usage: None,
};
Event::default()
.json_data(chunk)
.expect("ChatCompletionChunk always serializes")
}
fn sse_usage_chunk(cid: &str, model: &str, created: i64, outcome: &ChatOutcome) -> Event {
let chunk = ChatCompletionChunk {
id: cid.to_owned(),
object: "chat.completion.chunk",
created,
model: model.to_owned(),
choices: Vec::new(),
usage: Some(UsageInfo::from_outcome(outcome)),
};
Event::default()
.json_data(chunk)
.expect("ChatCompletionChunk always serializes")
}
fn json_error(status: StatusCode, msg: String) -> Response {
(status, Json(error_body(&msg, "server_error"))).into_response()
}
fn invalid_request(
status: StatusCode,
param: Option<&str>,
code: Option<&str>,
msg: String,
) -> Response {
(status, Json(invalid_request_body(param, code, &msg))).into_response()
}
fn invalid_request_body(param: Option<&str>, code: Option<&str>, msg: &str) -> serde_json::Value {
let mut body = error_body(msg, "invalid_request_error");
body["error"]["param"] = serde_json::json!(param);
body["error"]["code"] = serde_json::json!(code);
body
}
fn context_length_body(c: &ContextLengthExceeded) -> serde_json::Value {
invalid_request_body(
Some("messages"),
Some("context_length_exceeded"),
&c.message,
)
}
fn body_rejection(e: JsonRejection) -> Response {
let status = match e.status() {
s @ (StatusCode::PAYLOAD_TOO_LARGE | StatusCode::UNSUPPORTED_MEDIA_TYPE) => s,
_ => StatusCode::BAD_REQUEST,
};
invalid_request(status, None, None, e.body_text())
}
fn param_error(param: Option<&str>, msg: String) -> Response {
invalid_request(StatusCode::BAD_REQUEST, param, None, msg)
}
static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
fn make_id() -> String {
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
let seq = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
format!("chatcmpl-{ms}-{seq}")
}
const TOOL_CALL_ID_LEN: usize = 9;
const TOOL_CALL_ID_ALPHABET: &[u8] =
b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
fn tool_call_id(cid: &str, idx: usize) -> String {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut h = DefaultHasher::new();
(cid, idx).hash(&mut h);
let mut n = h.finish();
let base = TOOL_CALL_ID_ALPHABET.len() as u64;
(0..TOOL_CALL_ID_LEN)
.map(|_| {
let c = TOOL_CALL_ID_ALPHABET[(n % base) as usize] as char;
n /= base;
c
})
.collect()
}
const DEFAULT_MAX_TOKENS_CAP: u32 = 131_072;
fn max_tokens_cap(cfg: &Config) -> u32 {
let cap = cfg.serve.max_tokens_cap;
if cap > 0 {
cap
} else {
DEFAULT_MAX_TOKENS_CAP
}
}
fn clamp_max_tokens(requested: Option<u32>, cap: u32) -> Option<u32> {
requested.map(|v| v.min(cap))
}
fn request_timeout(cfg: &Config) -> Option<Duration> {
let secs = cfg.serve.request_timeout_secs;
(secs > 0).then(|| Duration::from_secs(secs))
}
fn arm_deadline(
d: Duration,
cancel: Arc<AtomicBool>,
hit: Arc<AtomicBool>,
) -> tokio::sync::oneshot::Sender<()> {
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
tokio::select! {
_ = tokio::time::sleep(d) => {
hit.store(true, Ordering::Relaxed);
cancel.store(true, Ordering::Relaxed);
tracing::warn!(timeout_s = d.as_secs(), "request deadline hit — aborting generation");
}
_ = done_rx => {}
}
});
done_tx
}
fn cancel_on_hangup(
tx: &tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
cancel: Arc<AtomicBool>,
) -> tokio::sync::oneshot::Sender<()> {
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
let tx = tx.clone();
tokio::spawn(async move {
tokio::select! {
_ = tx.closed() => cancel.store(true, Ordering::Relaxed),
_ = done_rx => {}
}
});
done_tx
}
struct CancelOnDrop(Arc<AtomicBool>);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
fn authorize(expected: Option<&str>, auth_header: Option<&str>) -> bool {
match expected {
None => true,
Some(key) => auth_header
.and_then(|h| {
h.strip_prefix("Bearer ")
.or_else(|| h.strip_prefix("bearer "))
})
.map(str::trim)
.is_some_and(|tok| bool::from(tok.as_bytes().ct_eq(key.as_bytes()))),
}
}
fn auth_gate(cfg: &Config, headers: &HeaderMap) -> Option<Response> {
let key = configured_api_key(cfg)?;
let auth = headers.get("authorization").and_then(|v| v.to_str().ok());
(!authorize(Some(key), auth)).then(|| {
invalid_request(
StatusCode::UNAUTHORIZED,
None,
Some("invalid_api_key"),
"missing or invalid Authorization bearer token".into(),
)
})
}
fn configured_api_key(cfg: &Config) -> Option<&str> {
cfg.serve
.api_key
.as_deref()
.filter(|k: &&str| !k.is_empty())
}
fn unix_ts() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
pub fn flatten_content(v: &Option<serde_json::Value>) -> String {
match v {
None | Some(serde_json::Value::Null) => String::new(),
Some(serde_json::Value::String(s)) => s.clone(),
Some(serde_json::Value::Array(parts)) => parts
.iter()
.filter_map(|p| {
if p.get("type")?.as_str()? == "text" {
p.get("text")?.as_str().map(str::to_owned)
} else {
None
}
})
.collect::<Vec<_>>()
.join(""),
Some(other) => other.to_string(),
}
}
fn dto_to_engine(dto: &ChatMessageDto) -> ChatMessage {
ChatMessage {
role: dto.role.clone(),
content: flatten_content(&dto.content),
tool_calls: dto.tool_calls.as_ref().and_then(parse_oai_tool_calls),
tool_call_id: dto.tool_call_id.clone(),
name: dto.name.clone(),
}
}
fn parse_oai_tool_calls(v: &serde_json::Value) -> Option<Vec<ToolCall>> {
let arr = v.as_array()?;
let calls: Vec<ToolCall> = arr
.iter()
.filter_map(|c| {
let f = c.get("function")?;
let name = f.get("name")?.as_str()?.to_owned();
let arguments = match f.get("arguments") {
Some(serde_json::Value::String(s)) => {
serde_json::from_str(s).unwrap_or(serde_json::Value::String(s.clone()))
}
Some(other) => other.clone(),
None => serde_json::Value::Object(serde_json::Map::new()),
};
let id = c.get("id").and_then(|v| v.as_str()).map(str::to_owned);
Some(ToolCall {
name,
arguments,
id,
})
})
.collect();
(!calls.is_empty()).then_some(calls)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, http::Request};
use http_body_util::BodyExt;
use tower::ServiceExt;
fn test_router() -> Router {
build_router(AppState::headless(
"test-model",
Arc::new(Config::default()),
))
}
#[tokio::test]
async fn test_health_returns_200() {
let resp = test_router()
.oneshot(
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_models_returns_200_with_expected_shape() {
let resp = test_router()
.oneshot(
Request::builder()
.uri("/v1/models")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["object"], "list");
let card = &json["data"][0];
assert_eq!(card["id"], "test-model");
assert_eq!(card["object"], "model");
assert_eq!(card["owned_by"], "local");
}
fn cpu_status() -> GeneratorStatus {
GeneratorStatus {
backend: "cpu",
device: None,
ctx_per_slot: None,
memory: None,
}
}
pub(crate) struct EchoGen(pub(crate) &'static str);
impl ChatGenerator for EchoGen {
fn status(&self) -> GeneratorStatus {
GeneratorStatus {
backend: "vulkan",
device: Some(format!("dev-{}", self.0)),
ctx_per_slot: Some(4096),
memory: Some(DeviceMemory {
total_bytes: 8 << 30,
available_bytes: 6 << 30,
live: true,
unified: false,
}),
}
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
on_delta(Delta::Content(format!("from:{}", self.0)));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 3,
completion_tokens: 2,
cached_tokens: 0,
})
}
}
fn multi_router() -> Router {
let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
build_router(AppState::multi(
vec![("alpha".into(), a, 2), ("beta".into(), b, 2)],
Arc::new(Config::default()),
))
}
#[tokio::test]
async fn multi_models_are_all_listed() {
let resp = multi_router()
.oneshot(
Request::builder()
.uri("/v1/models")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let ids: Vec<&str> = json["data"]
.as_array()
.unwrap()
.iter()
.map(|c| c["id"].as_str().unwrap())
.collect();
assert_eq!(ids, vec!["alpha", "beta"]);
}
async fn chat_model_field(router: Router, requested: &str) -> (String, String) {
let body =
format!(r#"{{"model":"{requested}","messages":[{{"role":"user","content":"hi"}}]}}"#);
let resp = router
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
(
json["model"].as_str().unwrap().to_string(),
json["choices"][0]["message"]["content"]
.as_str()
.unwrap()
.to_string(),
)
}
#[tokio::test]
async fn request_routes_to_named_model() {
let (model, content) = chat_model_field(multi_router(), "beta").await;
assert_eq!(model, "beta");
assert_eq!(content, "from:beta");
}
#[tokio::test]
async fn unknown_model_falls_to_default() {
let (model, content) = chat_model_field(multi_router(), "does-not-exist").await;
assert_eq!(model, "alpha");
assert_eq!(content, "from:alpha");
}
#[test]
fn chat_request_string_content_deserializes() {
let raw = r#"{"model":"m","messages":[{"role":"user","content":"hello"}]}"#;
let req: ChatRequest = serde_json::from_str(raw).unwrap();
assert_eq!(req.messages[0].role, "user");
assert_eq!(flatten_content(&req.messages[0].content), "hello");
assert!(!req.stream);
assert!(req.tools.is_none());
assert!(req.max_tokens.is_none());
}
#[test]
fn chat_request_array_content_deserializes_and_flattens() {
let raw = r#"{
"model": "m",
"messages": [{
"role": "user",
"content": [
{"type":"text","text":"hello"},
{"type":"image_url","image_url":{"url":"data:..."}},
{"type":"text","text":" world"}
]
}]
}"#;
let req: ChatRequest = serde_json::from_str(raw).unwrap();
assert_eq!(flatten_content(&req.messages[0].content), "hello world");
}
#[test]
fn chat_request_stream_flag() {
let raw = r#"{"model":"m","messages":[],"stream":true}"#;
let req: ChatRequest = serde_json::from_str(raw).unwrap();
assert!(req.stream);
}
#[test]
fn chat_request_with_tools_and_max_tokens() {
let raw = r#"{
"model":"m","messages":[],
"tools":[{"type":"function","function":{"name":"bash","description":"run bash"}}],
"max_tokens":512
}"#;
let req: ChatRequest = serde_json::from_str(raw).unwrap();
assert_eq!(
req.tools,
Some(serde_json::json!([
{"type": "function", "function": {"name": "bash", "description": "run bash"}}
]))
);
assert_eq!(req.max_tokens, Some(512));
assert_eq!(req.max_completion_tokens, None);
assert_eq!(req.tool_choice, None);
assert!(req.messages.is_empty());
}
#[test]
fn chat_message_dto_with_tool_call_id_and_name() {
let raw = r#"{"role":"tool","content":"result","tool_call_id":"tc_1","name":"bash"}"#;
let msg: ChatMessageDto = serde_json::from_str(raw).unwrap();
assert_eq!(msg.tool_call_id.as_deref(), Some("tc_1"));
assert_eq!(msg.name.as_deref(), Some("bash"));
}
#[test]
fn replayed_tool_call_keeps_its_id() {
let raw = r#"{"role":"assistant","content":null,"tool_calls":[
{"id":"a1B2c3D4e","type":"function",
"function":{"name":"bash","arguments":"{\"cmd\":\"ls\"}"}},
{"type":"function","function":{"name":"noid","arguments":"{}"}}]}"#;
let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(raw).unwrap());
let calls = msg.tool_calls.expect("two calls parse");
assert_eq!(calls[0].id.as_deref(), Some("a1B2c3D4e"));
assert_eq!(calls[0].arguments, serde_json::json!({"cmd": "ls"}));
assert_eq!(calls[1].id, None);
}
#[test]
fn minted_tool_call_ids_are_template_safe_and_distinct() {
let mut seen = std::collections::HashSet::new();
for _ in 0..1000 {
let cid = make_id();
for idx in 0..4 {
let id = tool_call_id(&cid, idx);
assert_eq!(id.len(), TOOL_CALL_ID_LEN, "{id}");
assert!(id.bytes().all(|b| b.is_ascii_alphanumeric()), "{id}");
assert!(seen.insert(id.clone()), "duplicate tool-call id {id}");
assert_eq!(id, tool_call_id(&cid, idx));
}
}
}
#[test]
fn chat_completion_response_stop_serializes() {
let resp = ChatCompletionResponse {
id: "chatcmpl-test".into(),
object: "chat.completion",
created: 1000,
model: "test-model".into(),
choices: vec![CompletionChoice {
index: 0,
message: AssistantMessage {
role: "assistant",
content: Some("hello".into()),
reasoning_content: None,
tool_calls: None,
},
finish_reason: "stop".into(),
}],
usage: UsageInfo {
prompt_tokens: 10,
completion_tokens: 5,
total_tokens: 15,
prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
},
};
let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
assert_eq!(v["object"], "chat.completion");
assert_eq!(v["choices"][0]["finish_reason"], "stop");
assert_eq!(v["choices"][0]["message"]["role"], "assistant");
assert_eq!(v["choices"][0]["message"]["content"], "hello");
assert!(v["choices"][0]["message"]["reasoning_content"].is_null());
assert!(v["choices"][0]["message"]["tool_calls"].is_null());
}
#[test]
fn chat_completion_response_with_reasoning_content() {
let resp = ChatCompletionResponse {
id: "id".into(),
object: "chat.completion",
created: 0,
model: "m".into(),
choices: vec![CompletionChoice {
index: 0,
message: AssistantMessage {
role: "assistant",
content: Some("answer".into()),
reasoning_content: Some("I thought about it".into()),
tool_calls: None,
},
finish_reason: "stop".into(),
}],
usage: UsageInfo {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
},
};
let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
assert_eq!(
v["choices"][0]["message"]["reasoning_content"],
"I thought about it"
);
assert_eq!(v["choices"][0]["message"]["content"], "answer");
}
#[test]
fn chat_completion_response_tool_calls_finish_reason() {
let resp = ChatCompletionResponse {
id: "id".into(),
object: "chat.completion",
created: 0,
model: "m".into(),
choices: vec![CompletionChoice {
index: 0,
message: AssistantMessage {
role: "assistant",
content: None,
reasoning_content: None,
tool_calls: Some(vec![OAIToolCall {
index: 0,
id: "call_0".into(),
kind: "function",
function: OAIFunction {
name: "bash".into(),
arguments: r#"{"command":"ls"}"#.into(),
},
}]),
},
finish_reason: "tool_calls".into(),
}],
usage: UsageInfo {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
},
};
let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");
let tc = &v["choices"][0]["message"]["tool_calls"][0];
assert_eq!(tc["type"], "function");
assert_eq!(tc["function"]["name"], "bash");
assert_eq!(tc["function"]["arguments"], r#"{"command":"ls"}"#);
assert_eq!(tc["index"], 0);
assert!(v["choices"][0]["message"]["content"].is_null());
}
#[test]
fn streaming_chunk_role_delta() {
let chunk = ChatCompletionChunk {
id: "id".into(),
object: "chat.completion.chunk",
created: 0,
model: "m".into(),
choices: vec![ChunkChoice {
index: 0,
delta: DeltaPayload {
role: Some("assistant".into()),
..Default::default()
},
finish_reason: None,
}],
usage: None,
};
let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
assert_eq!(v["object"], "chat.completion.chunk");
assert_eq!(v["choices"][0]["delta"]["role"], "assistant");
assert!(v["choices"][0]["delta"]["content"].is_null());
assert!(v["choices"][0]["delta"]["reasoning_content"].is_null());
assert!(v["choices"][0]["delta"]["tool_calls"].is_null());
assert!(v["choices"][0]["finish_reason"].is_null());
}
#[test]
fn streaming_chunk_content_delta() {
let chunk = ChatCompletionChunk {
id: "id".into(),
object: "chat.completion.chunk",
created: 0,
model: "m".into(),
choices: vec![ChunkChoice {
index: 0,
delta: DeltaPayload {
content: Some("hello".into()),
..Default::default()
},
finish_reason: None,
}],
usage: None,
};
let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
assert_eq!(v["choices"][0]["delta"]["content"], "hello");
assert!(v["choices"][0]["delta"]["role"].is_null());
}
#[test]
fn streaming_chunk_reasoning_content_delta() {
let chunk = ChatCompletionChunk {
id: "id".into(),
object: "chat.completion.chunk",
created: 0,
model: "m".into(),
choices: vec![ChunkChoice {
index: 0,
delta: DeltaPayload {
reasoning_content: Some("thinking...".into()),
..Default::default()
},
finish_reason: None,
}],
usage: None,
};
let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
assert_eq!(v["choices"][0]["delta"]["reasoning_content"], "thinking...");
assert!(v["choices"][0]["delta"]["content"].is_null());
}
#[test]
fn streaming_chunk_tool_call_delta() {
let chunk = ChatCompletionChunk {
id: "id".into(),
object: "chat.completion.chunk",
created: 0,
model: "m".into(),
choices: vec![ChunkChoice {
index: 0,
delta: DeltaPayload {
tool_calls: Some(vec![OAIToolCall {
index: 0,
id: "call_0".into(),
kind: "function",
function: OAIFunction {
name: "bash".into(),
arguments: r#"{"cmd":"ls"}"#.into(),
},
}]),
..Default::default()
},
finish_reason: None,
}],
usage: None,
};
let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
let tc = &v["choices"][0]["delta"]["tool_calls"][0];
assert_eq!(tc["index"], 0);
assert_eq!(tc["type"], "function");
assert_eq!(tc["function"]["name"], "bash");
}
#[test]
fn streaming_chunk_finish_reason() {
let chunk = ChatCompletionChunk {
id: "id".into(),
object: "chat.completion.chunk",
created: 0,
model: "m".into(),
choices: vec![ChunkChoice {
index: 0,
delta: DeltaPayload::default(), finish_reason: Some("stop".into()),
}],
usage: None,
};
let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
assert_eq!(v["choices"][0]["finish_reason"], "stop");
assert!(v["choices"][0]["delta"]["content"].is_null());
assert!(v["choices"][0]["delta"]["role"].is_null());
}
#[test]
fn models_response_serializes() {
let resp = ModelsResponse {
object: "list",
data: vec![ModelCard {
id: "my-model".into(),
object: "model",
owned_by: "local",
}],
};
let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
assert_eq!(v["object"], "list");
assert_eq!(v["data"][0]["id"], "my-model");
assert_eq!(v["data"][0]["object"], "model");
assert_eq!(v["data"][0]["owned_by"], "local");
}
fn req(raw: &str) -> ChatRequest {
serde_json::from_str(raw).unwrap()
}
#[test]
fn absent_sampling_fields_stay_none() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
))
.unwrap();
assert_eq!(p, GenParams::default());
}
#[test]
fn sampling_fields_parse() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"temperature":0.0,"top_p":0.9,"top_k":40,"seed":42,
"presence_penalty":0.5,"frequency_penalty":-0.25,"repeat_penalty":1.1,
"stop":["\n\n","END"]}"#,
))
.unwrap();
assert_eq!(p.temperature, Some(0.0));
assert_eq!(p.top_p, Some(0.9));
assert_eq!(p.top_k, Some(40));
assert_eq!(p.seed, Some(42));
assert_eq!(p.presence_penalty, Some(0.5));
assert_eq!(p.frequency_penalty, Some(-0.25));
assert_eq!(p.repeat_penalty, Some(1.1));
assert_eq!(p.stop, vec!["\n\n".to_string(), "END".to_string()]);
}
#[test]
fn unknown_fields_are_ignored_not_rejected() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"n":1,"user":"bob","logit_bias":{},"logprobs":true}"#,
))
.unwrap();
assert_eq!(p, GenParams::default());
}
#[test]
fn max_completion_tokens_is_preferred_alias() {
let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"max_tokens":10}"#))
.unwrap();
assert_eq!(p.max_tokens, Some(10));
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"max_completion_tokens":20}"#,
))
.unwrap();
assert_eq!(p.max_tokens, Some(20));
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"max_tokens":10,"max_completion_tokens":20}"#,
))
.unwrap();
assert_eq!(p.max_tokens, Some(20));
}
#[test]
fn stop_accepts_a_bare_string() {
let p =
GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":"\n"}"#)).unwrap();
assert_eq!(p.stop, vec!["\n".to_string()]);
}
#[test]
fn empty_stop_strings_are_dropped() {
let p =
GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":["",""]}"#)).unwrap();
assert!(p.stop.is_empty());
}
#[test]
fn invalid_values_are_param_errors_not_clamps() {
for (raw, param) in [
(
r#"{"model":"m","messages":[],"temperature":-1}"#,
"temperature",
),
(
r#"{"model":"m","messages":[],"temperature":3}"#,
"temperature",
),
(r#"{"model":"m","messages":[],"top_p":5}"#, "top_p"),
(r#"{"model":"m","messages":[],"top_k":-2}"#, "top_k"),
(
r#"{"model":"m","messages":[],"presence_penalty":-3}"#,
"presence_penalty",
),
(
r#"{"model":"m","messages":[],"frequency_penalty":9}"#,
"frequency_penalty",
),
(
r#"{"model":"m","messages":[],"repeat_penalty":0}"#,
"repeat_penalty",
),
(r#"{"model":"m","messages":[],"stop":[1,2]}"#, "stop"),
(
r#"{"model":"m","messages":[],"stop":["a","b","c","d","e"]}"#,
"stop",
),
] {
let e = GenParams::from_request(&req(raw)).unwrap_err();
assert_eq!(e.param, param, "{raw}");
}
}
#[tokio::test]
async fn bad_temperature_returns_openai_shaped_400() {
let resp = test_router()
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":-1}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"]["type"], "invalid_request_error");
assert_eq!(v["error"]["param"], "temperature");
}
fn run_stops(stops: &[&str], pieces: &[&str]) -> (String, bool) {
let mut m = StopMatcher::new(stops.iter().map(|s| s.to_string()).collect());
let mut out = String::new();
for p in pieces {
out.push_str(&m.push(p));
if m.hit() {
break;
}
}
if !m.hit() {
out.push_str(&m.flush());
}
(out, m.hit())
}
#[test]
fn stop_within_one_token_fires_and_is_excluded() {
let (out, hit) = run_stops(&["END"], &["hello ", "END", " more"]);
assert!(hit);
assert_eq!(out, "hello ");
}
#[test]
fn stop_split_across_two_tokens_still_fires() {
let (out, hit) = run_stops(&["END"], &["hello ", "E", "ND", " more"]);
assert!(hit, "a stop split across tokens must fire");
assert_eq!(out, "hello ", "no partial stop prefix may leak");
}
#[test]
fn stop_split_across_three_tokens_still_fires() {
let (out, hit) = run_stops(&["<|done|>"], &["a", "<|", "do", "ne", "|>", "b"]);
assert!(hit);
assert_eq!(out, "a");
}
#[test]
fn double_newline_stop_split_across_tokens() {
let (out, hit) = run_stops(&["\n\n"], &["line", "\n", "\n", "next"]);
assert!(hit);
assert_eq!(out, "line");
}
#[test]
fn stop_prefix_that_does_not_complete_is_eventually_emitted() {
let (out, hit) = run_stops(&["END"], &["E", "very", " day"]);
assert!(!hit);
assert_eq!(out, "Every day");
}
#[test]
fn held_prefix_is_flushed_at_end_of_generation() {
let (out, hit) = run_stops(&["END"], &["done E"]);
assert!(!hit);
assert_eq!(out, "done E");
}
#[test]
fn multiple_stops_take_the_earliest_match() {
let (out, hit) = run_stops(&["World", "lo"], &["hel", "lo World"]);
assert!(hit);
assert_eq!(out, "hel");
}
#[test]
fn no_stops_is_a_passthrough() {
let (out, hit) = run_stops(&[], &["a", "b", "c"]);
assert!(!hit);
assert_eq!(out, "abc");
assert!(!StopMatcher::new(vec![]).is_active());
}
#[test]
fn multibyte_stop_split_mid_codepoint_is_safe() {
let (out, hit) = run_stops(&["→END"], &["x", "→", "END", "y"]);
assert!(hit);
assert_eq!(out, "x");
}
#[test]
fn nothing_is_emitted_after_a_hit() {
let mut m = StopMatcher::new(vec!["END".into()]);
assert_eq!(m.push("aEND"), "a");
assert!(m.hit());
assert_eq!(m.push("more"), "");
assert_eq!(m.flush(), "");
}
#[test]
fn finish_reason_strings() {
assert_eq!(Finish::Stop.as_str(), "stop");
assert_eq!(Finish::Length.as_str(), "length");
assert_eq!(Finish::ToolCalls.as_str(), "tool_calls");
}
#[test]
fn flatten_content_string_value() {
let v = Some(serde_json::Value::String("hello world".into()));
assert_eq!(flatten_content(&v), "hello world");
}
#[test]
fn flatten_content_array_skips_non_text_parts() {
let v = Some(serde_json::json!([
{"type": "text", "text": "hello"},
{"type": "image_url", "image_url": {"url": "http://x"}},
{"type": "text", "text": " world"}
]));
assert_eq!(flatten_content(&v), "hello world");
}
#[test]
fn flatten_content_none_gives_empty_string() {
assert_eq!(flatten_content(&None), "");
}
#[test]
fn flatten_content_null_json_gives_empty_string() {
assert_eq!(flatten_content(&Some(serde_json::Value::Null)), "");
}
#[test]
fn flatten_content_non_string_renders_json_leniently() {
use serde_json::json;
assert_eq!(flatten_content(&Some(json!(42))), "42");
assert_eq!(flatten_content(&Some(json!(-1.5))), "-1.5");
assert_eq!(flatten_content(&Some(json!(true))), "true");
assert_eq!(flatten_content(&Some(json!(false))), "false");
assert_eq!(flatten_content(&Some(json!({"a": 1}))), r#"{"a":1}"#);
assert_eq!(
flatten_content(&Some(json!({"a": "b", "c": [1, 2]}))),
r#"{"a":"b","c":[1,2]}"#
);
}
#[test]
fn make_id_is_unique_across_rapid_calls() {
let n = 10_000;
let ids: std::collections::HashSet<String> = (0..n).map(|_| make_id()).collect();
assert_eq!(ids.len(), n, "make_id produced a collision");
}
#[test]
fn usage_total_is_prompt_plus_completion() {
let outcome = ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 17,
completion_tokens: 5,
cached_tokens: 0,
};
let usage = UsageInfo::from_outcome(&outcome);
assert_eq!(usage.total_tokens, 22);
assert_eq!(
usage.total_tokens,
usage.prompt_tokens + usage.completion_tokens
);
}
#[tokio::test]
async fn non_streaming_usage_comes_from_generator() {
let resp = multi_router()
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(
r#"{"model":"alpha","messages":[{"role":"user","content":"hi"}]}"#,
))
.unwrap(),
)
.await
.unwrap();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["usage"]["prompt_tokens"], 3);
assert_eq!(v["usage"]["completion_tokens"], 2);
assert_eq!(v["usage"]["total_tokens"], 5);
}
#[test]
fn tool_choice_string_passes_through() {
assert_eq!(
tool_choice_str(&serde_json::json!("required")).unwrap(),
Some("required".to_string())
);
assert_eq!(
tool_choice_str(&serde_json::json!("auto")).unwrap(),
Some("auto".to_string())
);
}
#[test]
fn a_forced_tool_choice_needs_tools_that_can_satisfy_it() {
let tools = serde_json::json!([{"function": {"name": "bash"}}]);
for choice in ["required", "bash"] {
assert!(
validate_tool_choice(Some(choice), None).is_err(),
"{choice:?} with no tools must 400"
);
assert!(
validate_tool_choice(Some(choice), Some(&serde_json::json!([]))).is_err(),
"{choice:?} with an empty tools array must 400"
);
}
assert!(validate_tool_choice(Some("bogus"), Some(&tools)).is_err());
assert!(validate_tool_choice(Some("auto"), None).is_ok());
assert!(
validate_tool_choice(Some("none"), None).is_ok(),
"`none` asks for no tool call, which needs no tools"
);
assert!(validate_tool_choice(None, None).is_ok());
assert!(validate_tool_choice(Some("required"), Some(&tools)).is_ok());
assert!(validate_tool_choice(Some("bash"), Some(&tools)).is_ok());
}
#[tokio::test]
async fn forced_tool_choice_without_tools_is_a_400() {
let resp = multi_router()
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(
r#"{"model":"a","messages":[{"role":"user","content":"hi"}],"tool_choice":"required"}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let v = body_json(resp).await;
assert_eq!(v["error"]["param"], "tool_choice");
assert_eq!(v["error"]["type"], "invalid_request_error");
}
#[test]
fn tool_choice_named_function_forces_that_tool() {
let v = serde_json::json!({"type":"function","function":{"name":"bash"}});
assert_eq!(tool_choice_str(&v).unwrap(), Some("bash".to_string()));
}
#[test]
fn tool_choice_object_without_name_is_an_error_not_auto() {
let v = serde_json::json!({"type":"function","function":{}});
let e = tool_choice_str(&v).unwrap_err();
assert_eq!(e.param, "tool_choice");
let v = serde_json::json!({"type":"function"});
assert!(tool_choice_str(&v).is_err());
}
#[test]
fn tool_choice_wrong_shape_is_an_error() {
assert!(tool_choice_str(&serde_json::json!(42)).is_err());
assert!(tool_choice_str(&serde_json::json!(["auto"])).is_err());
}
#[test]
fn max_tokens_clamps_absurd_values_but_passes_unset_and_normal() {
assert_eq!(clamp_max_tokens(None, 1000), None);
assert_eq!(clamp_max_tokens(Some(512), 1000), Some(512));
assert_eq!(clamp_max_tokens(Some(10_000_000), 1000), Some(1000));
assert_eq!(clamp_max_tokens(Some(1000), 1000), Some(1000));
}
#[test]
fn auth_disabled_allows_everything() {
assert!(authorize(None, None));
assert!(authorize(None, Some("Bearer whatever")));
assert!(authorize(None, Some("garbage")));
}
#[test]
fn auth_enabled_requires_matching_bearer() {
let key = Some("s3cret");
assert!(authorize(key, Some("Bearer s3cret")));
assert!(authorize(key, Some("bearer s3cret")));
assert!(!authorize(key, Some("Bearer wrong")));
assert!(!authorize(key, None));
assert!(!authorize(key, Some("s3cret")));
assert!(!authorize(key, Some("Basic s3cret")));
}
#[test]
fn auth_compares_full_token_not_a_prefix() {
let key = Some("s3cret");
assert!(authorize(key, Some("Bearer s3cret")));
assert!(!authorize(key, Some("Bearer s3creT")));
assert!(!authorize(key, Some("Bearer S3cret")));
assert!(!authorize(key, Some("Bearer s3c")));
assert!(!authorize(key, Some("Bearer s")));
assert!(!authorize(key, Some("Bearer ")));
assert!(!authorize(key, Some("Bearer s3cretx")));
assert!(authorize(key, Some("Bearer s3cret ")));
assert!(!authorize(key, Some("Bearer s3cre ")));
}
#[test]
fn configured_api_key_reads_the_config_and_empty_still_means_no_auth() {
let mut cfg = Config::default();
assert_eq!(configured_api_key(&cfg), None, "unset => auth disabled");
cfg.serve.api_key = Some(String::new());
assert_eq!(configured_api_key(&cfg), None, "empty => auth DISABLED");
cfg.serve.api_key = Some("hunter2".into());
assert_eq!(configured_api_key(&cfg), Some("hunter2"));
assert!(authorize(configured_api_key(&cfg), Some("Bearer hunter2")));
assert!(!authorize(configured_api_key(&cfg), None));
}
#[test]
fn max_tokens_cap_reads_the_config_and_rejects_non_positive() {
let mut cfg = Config::default();
assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
cfg.serve.max_tokens_cap = 4096;
assert_eq!(max_tokens_cap(&cfg), 4096);
assert_eq!(
clamp_max_tokens(Some(10_000), max_tokens_cap(&cfg)),
Some(4096)
);
cfg.serve.max_tokens_cap = 0;
assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
}
#[tokio::test]
async fn configured_api_key_gates_the_chat_endpoint() {
let mut cfg = Config::default();
cfg.serve.api_key = Some("s3cret".into());
let state = AppState::headless("test-model", Arc::new(cfg));
let body = r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}]}"#;
let req = |auth: Option<&str>| {
let mut b = Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json");
if let Some(a) = auth {
b = b.header("authorization", a);
}
b.body(Body::from(body)).unwrap()
};
let resp = build_router(state.clone())
.oneshot(req(None))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let resp = build_router(state)
.oneshot(req(Some("Bearer s3cret")))
.await
.unwrap();
assert_ne!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn configured_api_key_gates_models_but_never_health() {
let mut cfg = Config::default();
cfg.serve.api_key = Some("s3cret".into());
let state = AppState::headless("test-model", Arc::new(cfg));
let get = |uri: &str, auth: Option<&str>| {
let mut b = Request::builder().uri(uri);
if let Some(a) = auth {
b = b.header("authorization", a);
}
b.body(Body::empty()).unwrap()
};
let resp = build_router(state.clone())
.oneshot(get("/v1/models", None))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"]["type"], "invalid_request_error");
assert_eq!(v["error"]["code"], "invalid_api_key");
assert_eq!(
v["error"]["message"],
"missing or invalid Authorization bearer token"
);
assert!(
!String::from_utf8_lossy(&bytes).contains("test-model"),
"a 401 must not disclose the model set: {bytes:?}"
);
let resp = build_router(state.clone())
.oneshot(get("/v1/models", Some("Bearer wrong")))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let resp = build_router(state.clone())
.oneshot(get("/v1/models", Some("Bearer s3cret")))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["object"], "list");
assert_eq!(v["data"][0]["id"], "test-model");
assert_eq!(v["data"][0]["object"], "model");
assert_eq!(v["data"][0]["owned_by"], "local");
for auth in [None, Some("Bearer s3cret")] {
let resp = build_router(state.clone())
.oneshot(get("/health", auth))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "auth={auth:?}");
}
}
#[test]
fn request_timeout_is_off_by_default_and_zero_means_unbounded() {
let mut cfg = Config::default();
assert_eq!(request_timeout(&cfg), None, "default => no deadline");
cfg.serve.request_timeout_secs = 0;
assert_eq!(request_timeout(&cfg), None, "0 => no deadline");
cfg.serve.request_timeout_secs = 300;
assert_eq!(request_timeout(&cfg), Some(Duration::from_secs(300)));
}
struct LoopGen;
impl ChatGenerator for LoopGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
on_delta(Delta::Content("partial".into()));
while !cancel.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(2));
}
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 3,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
fn deadline_entry(generator: Arc<dyn ChatGenerator>) -> ModelEntry {
AppState::new(generator, "m", 1, Arc::new(Config::default())).route("m")
}
fn test_ctx(deadline: Option<Duration>, stream: bool) -> ReqCtx {
ReqCtx {
id: next_req_id(),
cid: "cid".into(),
model_id: "m".into(),
created: 0,
deadline,
stream,
include_usage: false,
stats: Arc::default(),
}
}
fn user_msg() -> Vec<ChatMessage> {
vec![ChatMessage {
role: "user".into(),
content: "hi".into(),
tool_calls: None,
tool_call_id: None,
name: None,
}]
}
async fn body_json(resp: Response) -> serde_json::Value {
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
serde_json::from_slice(&bytes).unwrap()
}
#[tokio::test]
async fn non_streaming_deadline_returns_partial_content_as_length() {
let started = std::time::Instant::now();
let resp = non_streaming(
deadline_entry(Arc::new(LoopGen)),
user_msg(),
None,
None,
GenParams::default(),
test_ctx(Some(Duration::from_millis(150)), false),
)
.await;
assert_eq!(resp.status(), StatusCode::OK, "a deadline is not a failure");
let v = body_json(resp).await;
assert_eq!(v["choices"][0]["finish_reason"], "length");
assert_eq!(
v["choices"][0]["message"]["content"], "partial",
"the partial completion must survive the deadline"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"the deadline did not stop the generator"
);
}
#[tokio::test]
async fn deadline_frees_the_slot_for_the_next_request() {
let entry = deadline_entry(Arc::new(LoopGen));
for _ in 0..2 {
let resp = non_streaming(
entry.clone(),
user_msg(),
None,
None,
GenParams::default(),
test_ctx(Some(Duration::from_millis(100)), false),
)
.await;
assert_eq!(
body_json(resp).await["choices"][0]["finish_reason"],
"length"
);
}
assert_eq!(
entry.slots.available_permits(),
1,
"the slot must be back after a deadline hit"
);
}
#[tokio::test]
async fn generation_inside_the_deadline_is_untouched() {
let resp = non_streaming(
deadline_entry(Arc::new(EchoGen("alpha"))),
user_msg(),
None,
None,
GenParams::default(),
test_ctx(Some(Duration::from_secs(30)), false),
)
.await;
let v = body_json(resp).await;
assert_eq!(v["choices"][0]["finish_reason"], "stop");
assert_eq!(v["choices"][0]["message"]["content"], "from:alpha");
}
#[tokio::test]
async fn streaming_deadline_finishes_with_length() {
let resp = streaming(
deadline_entry(Arc::new(LoopGen)),
user_msg(),
None,
None,
GenParams::default(),
test_ctx(Some(Duration::from_millis(150)), true),
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(text.contains("partial"), "partial content lost: {text}");
assert!(
text.contains("\"finish_reason\":\"length\""),
"a deadline hit must finish as `length`: {text}"
);
assert!(
!text.contains("\"finish_reason\":\"stop\""),
"the generator's `stop` must not reach the wire: {text}"
);
assert!(text.contains("[DONE]"), "sentinel missing: {text}");
}
#[tokio::test]
async fn dropping_the_done_signal_disarms_the_watchdog() {
let cancel = Arc::new(AtomicBool::new(false));
let hit = Arc::new(AtomicBool::new(false));
let done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
drop(done_tx); tokio::time::sleep(Duration::from_millis(200)).await;
assert!(
!cancel.load(Ordering::Relaxed) && !hit.load(Ordering::Relaxed),
"a disarmed watchdog must never fire"
);
let cancel = Arc::new(AtomicBool::new(false));
let hit = Arc::new(AtomicBool::new(false));
let _done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(cancel.load(Ordering::Relaxed) && hit.load(Ordering::Relaxed));
}
struct FailGen;
impl ChatGenerator for FailGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
on_delta(Delta::Content("partial".into()));
anyhow::bail!("boom mid-stream")
}
}
#[tokio::test]
async fn streaming_error_emits_error_frame_not_stop() {
let g: Arc<dyn ChatGenerator> = Arc::new(FailGen);
let router = build_router(AppState::new(g, "m", 1, Arc::new(Config::default())));
let resp = router
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(text.contains("\"error\""), "missing error frame: {text}");
assert!(
text.contains("boom mid-stream"),
"error message lost: {text}"
);
assert!(text.contains("[DONE]"), "sentinel missing: {text}");
assert!(
!text.contains("\"finish_reason\":\"stop\""),
"an Err must not report a clean stop: {text}"
);
}
struct PanicGen;
impl ChatGenerator for PanicGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
on_delta(Delta::Content("partial".into()));
panic!("boom: generator panicked mid-stream")
}
}
#[tokio::test]
async fn streaming_panic_is_reported_as_a_failure() {
let g: Arc<dyn ChatGenerator> = Arc::new(PanicGen);
let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
let stats = state.stats.clone();
let router = build_router(state);
let resp = router
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
))
.unwrap(),
)
.await
.unwrap();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(
text.contains("\"error\""),
"a panicking generator must still put a terminal error frame on the wire: {text}"
);
assert!(text.contains("[DONE]"), "sentinel missing: {text}");
assert!(
!text.contains("\"finish_reason\":\"stop\""),
"a panic must never look like a clean stop: {text}"
);
let w = stats.drain(Duration::from_secs(1));
assert_eq!(w.failed, 1, "the panic must be counted as a failure");
assert_eq!(
w.completed, 1,
"a failure is still a completed request for the interval line"
);
assert_eq!(w.active, 0, "the slot gauge must be released by the unwind");
}
#[test]
fn send_failure_latches_the_cancel_flag() {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
let cancel = AtomicBool::new(false);
drop(rx); if tx.send(Ok(Event::default().data("x"))).is_err() {
cancel.store(true, Ordering::Relaxed);
}
assert!(
cancel.load(Ordering::Relaxed),
"a failed send must latch the abort flag so the decode loop stops"
);
}
fn rec(prompt: u32, gen: u32, deltas: u64) -> ReqRecord {
rec_in_window(prompt, gen, deltas, 0, deltas)
}
fn rec_in_window(
prompt: u32,
gen: u32,
deltas: u64,
window: u64,
deltas_in_window: u64,
) -> ReqRecord {
ReqRecord {
prompt_tokens: prompt,
gen_tokens: gen,
deltas,
window,
deltas_in_window,
prefill: Duration::from_millis(100),
decode: Duration::from_millis(400),
total: Duration::from_millis(500),
finish: Finish::Stop,
}
}
#[test]
fn stats_windows_cover_the_interval_and_never_accumulate() {
let stats = ServeStats::default();
let window = Duration::from_secs(2);
for _ in 0..20 {
stats.bump_gen(1);
}
stats.fold_completion(&rec(100, 20, 20));
let busy = stats.drain(window);
assert_eq!(
(busy.prompt_tokens, busy.gen_tokens, busy.completed),
(100, 20, 1)
);
assert!((busy.decode_tps() - 10.0).abs() < 1e-9, "{busy:?}");
assert!((busy.prefill_tps() - 50.0).abs() < 1e-9, "{busy:?}");
for _ in 0..10 {
stats.bump_gen(1);
}
stats.fold_completion(&rec(20, 10, 10));
let quieter = stats.drain(window);
assert_eq!((quieter.prompt_tokens, quieter.gen_tokens), (20, 10));
assert!(
(quieter.decode_tps() - 5.0).abs() < 1e-9,
"the second interval must report only ITS OWN 10 tokens: {quieter:?}"
);
assert!(
quieter.decode_tps() < busy.decode_tps() && quieter.prefill_tps() < busy.prefill_tps(),
"half the work in the same wall time must report a LOWER rate: {busy:?} then {quieter:?}"
);
let idle = stats.drain(window);
assert_eq!(
(idle.gen_tokens, idle.prompt_tokens, idle.completed),
(0, 0, 0)
);
assert_eq!(idle.decode_tps(), 0.0);
assert!(
!idle.has_activity(),
"an interval with nothing in it must emit no line: {idle:?}"
);
}
#[test]
fn the_live_delta_count_is_reconciled_against_the_real_token_count() {
let under = ServeStats::default();
for _ in 0..3 {
under.bump_gen(1);
}
under.fold_completion(&rec(1, 5, 3));
assert_eq!(under.drain(Duration::from_secs(1)).gen_tokens, 5);
let over = ServeStats::default();
for _ in 0..6 {
over.bump_gen(1);
}
over.fold_completion(&rec(1, 4, 6));
assert_eq!(over.drain(Duration::from_secs(1)).gen_tokens, 4);
}
#[test]
fn a_correction_never_retracts_another_requests_tokens() {
let s = ServeStats::default();
let mut a = ReqTally::new();
a.on_text_delta(&s);
a.on_text_delta(&s);
let w1 = s.drain(Duration::from_secs(1));
assert_eq!(w1.gen_tokens, 2, "the open window had A's two deltas");
let mut b = ReqTally::new();
for _ in 0..3 {
b.on_text_delta(&s);
}
s.fold_completion(&a.finish(
ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 1,
cached_tokens: 0,
},
Finish::Stop,
));
let w2 = s.drain(Duration::from_secs(1));
assert_eq!(
w2.gen_tokens, 3,
"B's three tokens must survive A's correction — the −1 belongs to a closed window"
);
}
#[test]
fn a_correction_applies_within_the_open_window_and_is_clamped_to_its_own_deltas() {
let s = ServeStats::default();
let mut a = ReqTally::new();
for _ in 0..4 {
a.on_text_delta(&s);
}
s.fold_completion(&a.finish(
ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 2,
cached_tokens: 0,
},
Finish::Stop,
));
assert_eq!(s.drain(Duration::from_secs(1)).gen_tokens, 2);
let s = ServeStats::default();
let mut c = ReqTally::new();
c.on_text_delta(&s);
for _ in 0..5 {
s.bump_gen(1); }
let mut r = c.finish(
ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 0,
completion_tokens: 0,
cached_tokens: 0,
},
Finish::Stop,
);
r.deltas = 4; s.fold_completion(&r);
assert_eq!(
s.drain(Duration::from_secs(1)).gen_tokens,
5,
"the retraction is capped at this request's own contribution to the window"
);
}
#[test]
fn in_flight_requests_are_activity_and_an_empty_interval_is_not() {
let stats = Arc::new(ServeStats::default());
let w = Duration::from_secs(1);
assert!(!stats.drain(w).has_activity(), "idle must be silent");
let generating = ActiveGuard::new(stats.clone());
assert!(
stats.drain(w).has_activity(),
"a generation in flight is activity even before it yields a token"
);
drop(generating);
assert!(!stats.drain(w).has_activity());
let waiting = QueuedGuard::new(stats.clone());
assert!(
stats.drain(w).has_activity(),
"a request queued for a slot is activity"
);
drop(waiting);
assert!(!stats.drain(w).has_activity());
}
#[test]
fn the_active_gauge_is_released_by_an_unwinding_panic() {
let stats = Arc::new(ServeStats::default());
let inner = stats.clone();
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
let _active = ActiveGuard::new(inner);
panic!("decode closure blew up");
}));
assert!(caught.is_err(), "the panic must have happened");
assert_eq!(stats.active.load(Ordering::Relaxed), 0);
}
#[test]
fn stats_interval_defaults_to_five_seconds_and_zero_disables_it() {
let mut cfg = Config::default();
assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(5)));
cfg.serve.stats_interval_secs = 0;
assert_eq!(stats_interval(&cfg), None, "0 => no periodic line at all");
cfg.serve.stats_interval_secs = 30;
assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(30)));
}
#[tokio::test]
async fn slot_occupancy_counts_held_permits_across_models() {
let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
let state = AppState::multi(
vec![("alpha".into(), a, 3), ("beta".into(), b, 1)],
Arc::new(Config::default()),
);
assert_eq!(state.slot_occupancy(), (0, 4));
let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
assert_eq!(state.slot_occupancy(), (1, 4));
let held2 = state.models[1].slots.clone().acquire_owned().await.unwrap();
assert_eq!(state.slot_occupancy(), (2, 4));
drop(held);
drop(held2);
assert_eq!(state.slot_occupancy(), (0, 4));
}
#[test]
fn request_ids_are_monotonic_and_distinct() {
let ids: Vec<u64> = (0..1000).map(|_| next_req_id()).collect();
assert!(
ids.windows(2).all(|w| w[1] > w[0]),
"ids must increase monotonically"
);
let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "ids must never repeat");
}
#[tokio::test]
async fn a_served_request_folds_its_counts_into_the_window() {
let stats: Arc<ServeStats> = Arc::default();
let ctx = ReqCtx {
stats: stats.clone(),
..test_ctx(None, false)
};
let resp = non_streaming(
deadline_entry(Arc::new(EchoGen("alpha"))),
user_msg(),
None,
None,
GenParams::default(),
ctx,
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
let w = stats.drain(Duration::from_secs(1));
assert_eq!(
(w.prompt_tokens, w.gen_tokens, w.completed, w.failed),
(3, 2, 1, 0),
"EchoGen reports prompt_tokens=3, completion_tokens=2 for one request: {w:?}"
);
assert_eq!(
(w.active, w.queued),
(0, 0),
"both gauges must be back at zero once the request is answered"
);
}
#[tokio::test]
async fn a_failed_request_is_counted_as_a_failure() {
let stats: Arc<ServeStats> = Arc::default();
let ctx = ReqCtx {
stats: stats.clone(),
..test_ctx(None, false)
};
let resp = non_streaming(
deadline_entry(Arc::new(FailGen)),
user_msg(),
None,
None,
GenParams::default(),
ctx,
)
.await;
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let w = stats.drain(Duration::from_secs(1));
assert_eq!((w.completed, w.failed), (1, 1), "{w:?}");
assert!(
w.has_activity(),
"an interval of failures is not an idle one"
);
}
async fn post_chat(router: Router, body: &str) -> Response {
router
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from(body.to_owned()))
.unwrap(),
)
.await
.unwrap()
}
fn router_for(generator: Arc<dyn ChatGenerator>) -> Router {
build_router(AppState::new(
generator,
"m",
1,
Arc::new(Config::default()),
))
}
struct CachedPrefixGen;
impl ChatGenerator for CachedPrefixGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
on_delta(Delta::Content("ok".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 20,
completion_tokens: 1,
cached_tokens: 19,
})
}
}
#[tokio::test]
async fn usage_counts_the_whole_prompt_and_reports_the_cached_part() {
let g: Arc<dyn ChatGenerator> = Arc::new(CachedPrefixGen);
let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
let stats = state.stats.clone();
let resp = post_chat(
build_router(state),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
)
.await;
let v = body_json(resp).await;
assert_eq!(v["usage"]["prompt_tokens"], 20);
assert_eq!(v["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
assert_eq!(v["usage"]["total_tokens"], 21);
let w = stats.drain(Duration::from_secs(1));
assert_eq!(w.prompt_tokens, 1, "only the prefilled token is throughput");
}
async fn sse_frames(resp: Response) -> Vec<String> {
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec())
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix("data: ").map(str::to_owned))
.collect()
}
#[tokio::test]
async fn include_usage_ends_the_stream_with_a_usage_chunk() {
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true,
"stream_options":{"include_usage":true}}"#;
let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
let n = frames.len();
assert!(n >= 3, "{frames:?}");
assert_eq!(frames[n - 1], "[DONE]");
let usage: serde_json::Value = serde_json::from_str(&frames[n - 2]).unwrap();
assert_eq!(usage["choices"], serde_json::json!([]), "{frames:?}");
assert_eq!(usage["usage"]["prompt_tokens"], 20);
assert_eq!(usage["usage"]["completion_tokens"], 1);
assert_eq!(usage["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
let finish: serde_json::Value = serde_json::from_str(&frames[n - 3]).unwrap();
assert_eq!(finish["choices"][0]["finish_reason"], "stop", "{frames:?}");
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#;
let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
assert!(
frames.iter().all(|f| !f.contains("\"usage\"")),
"usage was not asked for: {frames:?}"
);
}
struct OverflowGen;
impl ChatGenerator for OverflowGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
_on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
Err(ContextLengthExceeded {
message: "too long".into(),
}
.into())
}
}
#[tokio::test]
async fn an_over_long_prompt_is_a_400_context_length_exceeded() {
let resp = post_chat(
router_for(Arc::new(OverflowGen)),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let v = body_json(resp).await;
assert_eq!(v["error"]["type"], "invalid_request_error");
assert_eq!(v["error"]["code"], "context_length_exceeded");
assert_eq!(v["error"]["param"], "messages");
assert_eq!(v["error"]["message"], "too long");
}
#[tokio::test]
async fn an_over_long_prompt_on_a_stream_is_a_typed_error_frame() {
let frames = sse_frames(
post_chat(
router_for(Arc::new(OverflowGen)),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
)
.await,
)
.await;
assert_eq!(
frames.last().map(String::as_str),
Some("[DONE]"),
"{frames:?}"
);
let err: serde_json::Value = frames
.iter()
.filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
.find(|v| v.get("error").is_some())
.expect("an error frame");
assert_eq!(err["error"]["type"], "invalid_request_error");
assert_eq!(err["error"]["code"], "context_length_exceeded");
assert_eq!(err["error"]["param"], "messages");
assert_eq!(err["error"]["message"], "too long");
}
#[tokio::test]
async fn oversized_and_untyped_bodies_keep_their_status() {
let huge = format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
"x".repeat(3 << 20)
);
let resp = post_chat(router_for(Arc::new(EchoGen("a"))), &huge).await;
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
body_json(resp).await["error"]["type"],
"invalid_request_error"
);
let resp = router_for(Arc::new(EchoGen("a")))
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.body(Body::from(
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert_eq!(
body_json(resp).await["error"]["type"],
"invalid_request_error"
);
let resp = post_chat(router_for(Arc::new(EchoGen("a"))), "{not json").await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn the_bearer_check_does_not_wait_for_the_body() {
let mut cfg = Config::default();
cfg.serve.api_key = Some("s3cret".into());
let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
let router = build_router(AppState::new(g, "m", 1, Arc::new(cfg)));
let never = futures_util::stream::pending::<Result<axum::body::Bytes, std::io::Error>>();
let resp = tokio::time::timeout(
Duration::from_secs(2),
router.oneshot(
Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("content-type", "application/json")
.body(Body::from_stream(never))
.unwrap(),
),
)
.await
.expect("an unauthenticated request waited for its body")
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn minus_one_seed_and_max_tokens_mean_unset() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"seed":-1,"max_tokens":-1,"max_completion_tokens":-1}"#,
))
.unwrap();
assert_eq!((p.seed, p.max_tokens), (None, None));
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"seed":18446744073709551615,"max_tokens":7}"#,
))
.unwrap();
assert_eq!((p.seed, p.max_tokens), (Some(u64::MAX), Some(7)));
for bad in [
r#""seed":-2"#,
r#""max_tokens":-5"#,
r#""max_tokens":4294967296"#,
] {
let raw = format!(r#"{{"model":"m","messages":[],{bad}}}"#);
assert!(serde_json::from_str::<ChatRequest>(&raw).is_err(), "{bad}");
}
let resp = post_chat(
router_for(Arc::new(EchoGen("a"))),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"seed":-1,"max_tokens":-1}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
}
struct HangGen {
entered: Arc<AtomicBool>,
cancelled: Arc<AtomicBool>,
}
impl ChatGenerator for HangGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn chat(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
cancel: &Arc<AtomicBool>,
_on_delta: &mut dyn FnMut(Delta),
) -> anyhow::Result<ChatOutcome> {
self.entered.store(true, Ordering::Relaxed);
let started = Instant::now();
while started.elapsed() < Duration::from_secs(5) {
if cancel.load(Ordering::Relaxed) {
self.cancelled.store(true, Ordering::Relaxed);
break;
}
std::thread::sleep(Duration::from_millis(2));
}
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 0,
cached_tokens: 0,
})
}
}
async fn eventually(flag: &AtomicBool, within: Duration) -> bool {
let started = Instant::now();
while !flag.load(Ordering::Relaxed) {
if started.elapsed() > within {
return false;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
true
}
async fn hang_up_reaches_the_generator(stream: bool) -> bool {
use tokio::io::AsyncWriteExt;
let entered = Arc::new(AtomicBool::new(false));
let cancelled = Arc::new(AtomicBool::new(false));
let g: Arc<dyn ChatGenerator> = Arc::new(HangGen {
entered: entered.clone(),
cancelled: cancelled.clone(),
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let router = router_for(g);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
let body = format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
);
let head = format!(
"POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n\
Content-Type: application/json\r\nContent-Length: {}\r\n\r\n",
body.len()
);
sock.write_all(head.as_bytes()).await.unwrap();
sock.write_all(body.as_bytes()).await.unwrap();
assert!(
eventually(&entered, Duration::from_secs(2)).await,
"the generation never started"
);
drop(sock);
let reached = eventually(&cancelled, Duration::from_secs(2)).await;
server.abort();
reached
}
#[tokio::test]
async fn a_non_streaming_hang_up_cancels_the_generation() {
assert!(hang_up_reaches_the_generator(false).await);
}
#[tokio::test]
async fn a_streaming_hang_up_during_prefill_cancels_the_generation() {
assert!(hang_up_reaches_the_generator(true).await);
}
}