use std::{
convert::Infallible,
net::SocketAddr,
sync::{
atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
Arc,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use axum::{
extract::{rejection::JsonRejection, DefaultBodyLimit, Request, State},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{
sse::{Event, KeepAlive, 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 completions;
mod host;
mod logprobs;
mod metrics;
mod status;
pub use logprobs::{ChatLogprobs, ChatTokenLogprob, ChatTokenLogprobAlt, LogprobStops, TokenText};
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 complete(
&self,
_prompt: &str,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
_on_text: &mut dyn FnMut(&str),
) -> anyhow::Result<ChatOutcome> {
Err(ParamError {
param: "model",
message: "this model does not support text completions".into(),
}
.into())
}
fn prepare_completion(&self, _prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
Ok(None)
}
fn complete_with_logprobs(
&self,
prompt: &str,
params: &GenParams,
cancel: &Arc<AtomicBool>,
on_text: &mut dyn FnMut(&str),
_on_logprob: &mut dyn FnMut(infr_engine::TokenLogprob),
) -> anyhow::Result<ChatOutcome> {
if params.logprobs {
return Err(ParamError {
param: "logprobs",
message: "logprobs: returning log probabilities is not supported by this backend"
.into(),
}
.into());
}
self.complete(prompt, params, cancel, on_text)
}
fn status(&self) -> GeneratorStatus;
fn supports_logprobs(&self) -> bool {
false
}
fn vocab_size(&self) -> usize;
fn prepare(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
) -> anyhow::Result<Option<PreparedRequest>> {
Ok(None)
}
#[allow(clippy::too_many_arguments)]
fn chat_prepared(
&self,
prepared: PreparedRequest,
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> {
drop(prepared);
self.chat(messages, tools, tool_choice, params, cancel, on_delta)
}
}
pub struct PreparedRequest {
pub prompt_tokens: u32,
pub context_length: Option<u32>,
state: Box<dyn std::any::Any + Send>,
}
impl PreparedRequest {
pub fn new(
prompt_tokens: u32,
context_length: Option<u32>,
state: impl std::any::Any + Send,
) -> Self {
Self {
prompt_tokens,
context_length,
state: Box::new(state),
}
}
pub fn into_state<T: std::any::Any>(self) -> Option<T> {
self.state.downcast::<T>().ok().map(|b| *b)
}
}
impl std::fmt::Debug for PreparedRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PreparedRequest")
.field("prompt_tokens", &self.prompt_tokens)
.field("context_length", &self.context_length)
.finish_non_exhaustive()
}
}
#[allow(clippy::too_many_arguments)]
fn generate(
engine: &dyn ChatGenerator,
prepared: Option<PreparedRequest>,
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> {
match prepared {
Some(p) => engine.chat_prepared(p, messages, tools, tool_choice, params, cancel, on_delta),
None => engine.chat(messages, tools, tool_choice, params, cancel, on_delta),
}
}
#[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 ContextLengthExceeded {
pub fn prompt_too_long(input: &str, context_length: usize, prompt_tokens: usize) -> Self {
Self {
message: format!(
"This model's maximum context length is {context_length} tokens. However, your \
{input} resulted in {prompt_tokens} tokens. Please reduce the length of the \
{input}."
),
}
}
pub fn reply_too_long(
input: &str,
context_length: usize,
prompt_tokens: usize,
reply_tokens: usize,
can_lower_reply: bool,
) -> Self {
let advice = if can_lower_reply {
format!("Please reduce the length of the {input} or completion.")
} else {
format!("Please reduce the length of the {input}.")
};
Self {
message: format!(
"This model's maximum context length is {context_length} tokens. However, you \
requested {} tokens ({prompt_tokens} in the {input}, {reply_tokens} in the \
completion). {advice}",
prompt_tokens + reply_tokens
),
}
}
}
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 min_p: Option<f32>,
#[serde(default)]
pub logit_bias: Option<LogitBiasArg>,
#[serde(default)]
pub n: Option<serde_json::Value>,
#[serde(default)]
pub logprobs: Option<bool>,
#[serde(default)]
pub top_logprobs: Option<serde_json::Value>,
#[serde(default)]
pub stream_options: Option<StreamOptions>,
#[serde(default)]
pub response_format: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ResponseFormat {
JsonObject,
JsonSchema(serde_json::Value),
}
impl ResponseFormat {
pub fn schema(&self) -> serde_json::Value {
match self {
ResponseFormat::JsonObject => serde_json::json!({"type": "object"}),
ResponseFormat::JsonSchema(schema) => schema.clone(),
}
}
fn from_request(v: Option<&serde_json::Value>) -> Result<Option<Self>, ParamError> {
let bad = |message: String| ParamError {
param: "response_format",
message,
};
let Some(v) = v.filter(|v| !v.is_null()) else {
return Ok(None);
};
let kind = v
.get("type")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| bad("response_format must be an object with a string `type`".into()))?;
let schema_at = |v: Option<&serde_json::Value>, path: &str| match v {
None | Some(serde_json::Value::Null) => Ok(None),
Some(s) if s.is_object() => Ok(Some(s.clone())),
_ => Err(bad(format!("{path} must be a JSON schema object"))),
};
match kind {
"text" => Ok(None),
"json_object" => Ok(Some(
match schema_at(v.get("schema"), "response_format.schema")? {
Some(s) => Self::JsonSchema(s),
None => Self::JsonObject,
},
)),
"json_schema" => {
let wrapper = v.get("json_schema").filter(|j| !j.is_null());
if wrapper.is_some_and(|j| !j.is_object()) {
return Err(bad("response_format.json_schema must be an object".into()));
}
let schema = schema_at(
wrapper.and_then(|j| j.get("schema")),
"response_format.json_schema.schema",
)?;
Ok(Some(Self::JsonSchema(
schema.unwrap_or_else(|| serde_json::json!({})),
)))
}
other => Err(bad(format!(
"response_format type must be \"text\", \"json_object\" or \"json_schema\", \
got {other:?}"
))),
}
}
}
#[derive(Debug, Clone)]
pub enum LogitBiasArg {
Entries(Vec<(String, serde_json::Value)>),
NotAnObject(&'static str),
}
impl<'de> Deserialize<'de> for LogitBiasArg {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = LogitBiasArg;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a JSON value")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut m: A,
) -> Result<Self::Value, A::Error> {
let mut entries = Vec::new();
while let Some(entry) = m.next_entry::<String, serde_json::Value>()? {
entries.push(entry);
}
Ok(LogitBiasArg::Entries(entries))
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut s: A,
) -> Result<Self::Value, A::Error> {
while s.next_element::<serde::de::IgnoredAny>()?.is_some() {}
Ok(LogitBiasArg::NotAnObject("array"))
}
fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {
Ok(LogitBiasArg::NotAnObject("boolean"))
}
fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {
Ok(LogitBiasArg::NotAnObject("number"))
}
fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {
Ok(LogitBiasArg::NotAnObject("number"))
}
fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {
Ok(LogitBiasArg::NotAnObject("number"))
}
fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {
Ok(LogitBiasArg::NotAnObject("string"))
}
}
d.deserialize_any(V)
}
}
#[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 min_p: Option<f32>,
pub logit_bias: Vec<(u32, f32)>,
pub logprobs: bool,
pub top_logprobs: usize,
pub stop: Vec<String>,
pub response_format: Option<ResponseFormat>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParamError {
pub param: &'static str,
pub message: String,
}
impl std::fmt::Display for ParamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ParamError {}
impl ParamError {
pub fn empty_prompt() -> Self {
Self {
param: "prompt",
message: "prompt is empty; send at least one token of text".into(),
}
}
}
const MAX_TOP_LOGPROBS: usize = 20;
impl GenParams {
pub fn from_request(req: &ChatRequest) -> Result<Self, ParamError> {
let unsupported = |param: &'static str, what: &str| ParamError {
param,
message: format!("{param}: {what} is not supported by this server"),
};
match whole_number("n", req.n.as_ref())? {
None | Some(1) => {}
Some(n) if n < 1 => {
return Err(ParamError {
param: "n",
message: format!("n must be >= 1, got {n}"),
})
}
Some(n) => return Err(unsupported("n", &format!("returning {n} choices"))),
}
let logprobs = req.logprobs.unwrap_or(false);
let top_logprobs = match whole_number("top_logprobs", req.top_logprobs.as_ref())? {
None if logprobs => MAX_TOP_LOGPROBS,
None | Some(0) => 0,
Some(k) if k < 0 => {
return Err(ParamError {
param: "top_logprobs",
message: format!("top_logprobs must be >= 0, got {k}"),
})
}
Some(k) if k > MAX_TOP_LOGPROBS as i64 => {
return Err(ParamError {
param: "top_logprobs",
message: format!("top_logprobs must be at most {MAX_TOP_LOGPROBS}, got {k}"),
})
}
Some(k) => k as usize,
};
if top_logprobs > 0 && !logprobs {
return Err(ParamError {
param: "top_logprobs",
message: "top_logprobs requires logprobs to be set to true".into(),
});
}
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}"),
});
}
}
let logit_bias = parse_logit_bias(req.logit_bias.as_ref())?;
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,
min_p: rng("min_p", req.min_p, 0.0, 1.0)?,
logit_bias,
logprobs,
top_logprobs,
stop,
response_format: ResponseFormat::from_request(req.response_format.as_ref())?,
})
}
pub fn check_vocab(&self, vocab: usize) -> Result<(), ParamError> {
match self.logit_bias.iter().find(|&&(t, _)| t as usize >= vocab) {
Some(&(t, _)) => Err(ParamError {
param: "logit_bias",
message: format!(
"logit_bias names token {t}, but the model's vocabulary has {vocab} tokens"
),
}),
None => Ok(()),
}
}
}
fn whole_number(
param: &'static str,
v: Option<&serde_json::Value>,
) -> Result<Option<i64>, ParamError> {
let Some(v) = v.filter(|v| !v.is_null()) else {
return Ok(None);
};
if let Some(i) = v.as_i64() {
return Ok(Some(i));
}
if let Some(u) = v.as_u64() {
return Ok(Some(i64::try_from(u).unwrap_or(i64::MAX)));
}
match v.as_f64() {
Some(f) if f.fract() == 0.0 && (i64::MIN as f64..=i64::MAX as f64).contains(&f) => {
Ok(Some(f as i64))
}
_ => Err(ParamError {
param,
message: format!("{param} must be an integer, got {v}"),
}),
}
}
const LOGIT_BIAS_LIMIT: f64 = 100.0;
fn parse_logit_bias(v: Option<&LogitBiasArg>) -> Result<Vec<(u32, f32)>, ParamError> {
let err = |message: String| ParamError {
param: "logit_bias",
message,
};
let entries = match v {
None => return Ok(Vec::new()),
Some(LogitBiasArg::Entries(e)) => e,
Some(LogitBiasArg::NotAnObject(t)) => {
return Err(err(format!(
"logit_bias must be an object mapping token ids to biases, got a {t}"
)))
}
};
let mut out = Vec::with_capacity(entries.len());
for (key, val) in entries {
let canonical = key.bytes().all(|b| b.is_ascii_digit())
&& (key == "0" || (!key.is_empty() && !key.starts_with('0')));
let id: u32 = canonical
.then(|| key.parse().ok())
.flatten()
.ok_or_else(|| {
err(format!(
"logit_bias key {key:?} is not a token id (a non-negative integer written \
without sign or leading zeros)"
))
})?;
let bias = val
.as_f64()
.ok_or_else(|| err(format!("logit_bias for token {id} must be a number")))?;
if !(-LOGIT_BIAS_LIMIT..=LOGIT_BIAS_LIMIT).contains(&bias) {
return Err(err(format!(
"logit_bias for token {id} must be between -{LOGIT_BIAS_LIMIT} and \
{LOGIT_BIAS_LIMIT}, got {bias}"
)));
}
out.push((id, bias as f32));
}
out.sort_by_key(|&(id, _)| id);
if let Some(w) = out.windows(2).find(|w| w[0].0 == w[1].0) {
return Err(err(format!("logit_bias names token {} twice", w[0].0)));
}
Ok(out)
}
#[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_tools(tools: Option<&serde_json::Value>) -> Result<(), ParamError> {
let bad = |message: String| ParamError {
param: "tools",
message,
};
let tools = match tools {
None | Some(serde_json::Value::Null) => return Ok(()),
Some(serde_json::Value::Array(a)) => a,
Some(_) => return Err(bad("tools must be an array".into())),
};
for (i, t) in tools.iter().enumerate() {
if t.get("function")
.and_then(|f| f.get("name"))
.and_then(serde_json::Value::as_str)
.is_none()
{
return Err(bad(format!("tools[{i}] has no string `function.name`")));
}
}
Ok(())
}
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,
#[serde(skip_serializing_if = "Option::is_none")]
pub logprobs: Option<ChatLogprobs>,
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,
#[serde(skip_serializing_if = "Option::is_none")]
pub logprobs: Option<ChatLogprobs>,
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"
);
}
struct RequestStart<'a> {
route: &'a str,
model: &'a str,
messages: usize,
prompt_chars: usize,
prompt_tokens: Option<u32>,
max_tokens: Option<u32>,
stream: bool,
}
fn log_request_start(req_id: u64, start: RequestStart<'_>) {
let RequestStart {
route,
model,
messages,
prompt_chars,
prompt_tokens,
max_tokens,
stream,
} = start;
tracing::info!(
req = req_id,
route,
model,
messages,
prompt_chars,
prompt_tokens,
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,
prepares: Arc<Semaphore>,
}
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,
prepares: Arc::new(Semaphore::new(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,
bind: Option<SocketAddr>,
}
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(),
bind: None,
}
}
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(),
bind: None,
}
}
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(),
bind: None,
}
}
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 {
let body_limit = max_body_bytes(&state.cfg);
Router::new()
.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)),
)
.route(
"/v1/completions",
post(completions::completions_handler)
.route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
)
.layer(middleware::from_fn_with_state(
state.clone(),
host::host_gate,
))
.route("/health", get(health_handler))
.layer(DefaultBodyLimit::max(body_limit))
.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(mut state: AppState, addr: SocketAddr) -> anyhow::Result<()> {
host::check_allowed_hosts(&state.cfg)?;
let n_models = state.models.len();
let listener = tokio::net::TcpListener::bind(addr).await?;
state.bind = Some(listener.local_addr()?);
let reporter = stats_interval(&state.cfg)
.map(|period| tokio::spawn(stats_reporter(state.clone(), period)));
let router = build_router(state);
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_tools(tools.as_ref())
.and_then(|()| validate_tool_choice(tool_choice.as_deref(), tools.as_ref()))
{
return param_error(Some(e.param), e.message);
}
let entry = state.route(&req.model);
if params.logprobs {
if let Some(engine) = &entry.engine {
if !engine.supports_logprobs() {
return param_error(
Some("logprobs"),
"logprobs: returning log probabilities is not supported by this backend".into(),
);
}
}
}
if let (false, Some(engine)) = (params.logit_bias.is_empty(), &entry.engine) {
if let Err(e) = params.check_vocab(engine.vocab_size()) {
return param_error(Some(e.param), e.message);
}
}
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),
keep_alive: sse_keep_alive(&state.cfg),
stream: req.stream,
include_usage: req.stream_options.as_ref().is_some_and(|o| o.include_usage),
stats: state.stats.clone(),
};
let prompt_chars = messages.iter().map(|m| m.content.len()).sum();
let n_messages = messages.len();
let (messages, tools, tool_choice, params, prepared) = match entry.engine.clone() {
None => (messages, tools, tool_choice, params, Ok(None)),
Some(engine) => {
let joined = prepare_bounded(&entry, &ctx, move || {
let prepared =
engine.prepare(&messages, tools.as_ref(), tool_choice.as_deref(), ¶ms);
(messages, tools, tool_choice, params, prepared)
})
.await;
match joined {
Ok(parts) => parts,
Err(resp) => return *resp,
}
}
};
let prompt_tokens = prepared
.as_ref()
.ok()
.and_then(|p| p.as_ref().map(|p| p.prompt_tokens));
let (prepared, refused) = match prepared {
Err(e) => (None, Some(e)),
Ok(Some(PreparedRequest {
prompt_tokens,
context_length: Some(max),
..
})) if prompt_tokens > max => (
None,
Some(
ContextLengthExceeded::prompt_too_long(
CHAT_INPUT,
max as usize,
prompt_tokens as usize,
)
.into(),
),
),
Ok(p) => (p, None),
};
log_request_start(
ctx.id,
RequestStart {
route: "/v1/chat/completions",
model: &ctx.model_id,
messages: n_messages,
prompt_chars,
prompt_tokens,
max_tokens: params.max_tokens,
stream: ctx.stream,
},
);
if let Some(e) = refused {
ctx.stats.fold_failure();
tracing::warn!(req = ctx.id, error = %e, "request refused before generation");
return error_response(&e, CHAT_INPUT);
}
if ctx.stream {
streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
} else {
non_streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
}
}
#[derive(Clone)]
struct ReqCtx {
id: u64,
cid: String,
model_id: String,
created: i64,
deadline: Option<Duration>,
keep_alive: Option<Duration>,
stream: bool,
include_usage: bool,
stats: Arc<ServeStats>,
}
const CHAT_INPUT: &str = "messages";
async fn prepare_bounded<T: Send + 'static>(
entry: &ModelEntry,
ctx: &ReqCtx,
f: impl FnOnce() -> T + Send + 'static,
) -> Result<T, Box<Response>> {
let Ok(permit) = entry.prepares.clone().acquire_owned().await else {
ctx.stats.fold_failure();
return Err(Box::new(json_error(
StatusCode::SERVICE_UNAVAILABLE,
"server shutting down".into(),
)));
};
tokio::task::spawn_blocking(move || {
let _permit = permit;
f()
})
.await
.map_err(|e| {
ctx.stats.fold_failure();
tracing::warn!(req = ctx.id, error = %e, "request preparation failed");
Box::new(json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
})
}
struct Slot {
_permit: tokio::sync::OwnedSemaphorePermit,
_active: ActiveGuard,
}
async fn acquire_slot(entry: &ModelEntry, ctx: &ReqCtx) -> Result<Slot, Box<Response>> {
let stats = &ctx.stats;
let queued = QueuedGuard::new(stats.clone());
let Ok(permit) = entry.slots.clone().acquire_owned().await else {
stats.fold_failure();
tracing::warn!(req = ctx.id, "rejected — server shutting down");
return Err(Box::new(json_error(
StatusCode::SERVICE_UNAVAILABLE,
"server shutting down".into(),
)));
};
drop(queued);
Ok(Slot {
_permit: permit,
_active: ActiveGuard::new(stats.clone()),
})
}
async fn run_unary<T: Send + 'static>(
entry: &ModelEntry,
ctx: &ReqCtx,
input: &'static str,
job: impl FnOnce(&dyn ChatGenerator, &Arc<AtomicBool>) -> anyhow::Result<T> + Send + 'static,
) -> Result<(T, bool), Box<Response>> {
let req_id = ctx.id;
let slot = acquire_slot(entry, ctx).await?;
let engine_arc = entry.engine.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<T> {
let _slot = slot;
let Some(engine) = engine_arc else {
anyhow::bail!("no engine loaded");
};
job(&*engine, &cancel_blk)
});
let mut deadline_hit = false;
let joined = match ctx.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
}
},
};
match joined.map_err(anyhow::Error::from).and_then(|r| r) {
Ok(out) => Ok((out, deadline_hit)),
Err(e) => {
ctx.stats.fold_failure();
tracing::warn!(req = req_id, error = %e, "request failed");
Err(Box::new(error_response(&e, input)))
}
}
}
struct StreamJob {
tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
cancel: Arc<AtomicBool>,
deadline_hit: Arc<AtomicBool>,
done: DoneGuard,
engine: Option<Arc<dyn ChatGenerator>>,
}
impl StreamJob {
fn send(&self, ev: Event) {
if self.tx.send(Ok(ev)).is_err() {
self.cancel.store(true, Ordering::Relaxed);
}
}
fn finish(&self, finish: Finish) -> Finish {
if self.deadline_hit.load(Ordering::Relaxed) {
Finish::Length
} else {
finish
}
}
fn fail(&mut self, e: &anyhow::Error, input: &'static str) {
match request_error_body(e, input) {
Some(body) => self.done.fail_with(body, &e.to_string()),
None => self.done.fail(&e.to_string()),
}
}
}
async fn run_streamed(
entry: &ModelEntry,
ctx: &ReqCtx,
job: impl FnOnce(StreamJob) + Send + 'static,
) -> Response {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
let slot = match acquire_slot(entry, ctx).await {
Ok(slot) => slot,
Err(resp) => return *resp,
};
let cancel = Arc::new(AtomicBool::new(false));
let hangup_done = cancel_on_hangup(&tx, cancel.clone());
let deadline_hit = Arc::new(AtomicBool::new(false));
let done_tx = ctx
.deadline
.map(|d| arm_deadline(d, cancel.clone(), deadline_hit.clone()));
let engine = entry.engine.clone();
let (req_id, stats) = (ctx.id, ctx.stats.clone());
tokio::task::spawn_blocking(move || {
let _slot = slot;
let _done_tx = done_tx;
let _hangup_done = hangup_done;
let done = DoneGuard {
tx: tx.clone(),
req_id,
stats,
settled: false,
};
job(StreamJob {
tx,
cancel,
deadline_hit,
done,
engine,
});
});
let stream = futures_util::stream::unfold(rx, |mut rx| async move {
rx.recv().await.map(|item| (item, rx))
});
let sse = Sse::new(stream);
match ctx.keep_alive {
Some(d) => sse.keep_alive(KeepAlive::new().interval(d)).into_response(),
None => sse.into_response(),
}
}
async fn non_streaming(
entry: ModelEntry,
prepared: Option<PreparedRequest>,
messages: Vec<ChatMessage>,
tools: Option<serde_json::Value>,
tool_choice: Option<String>,
params: GenParams,
ctx: ReqCtx,
) -> Response {
let cid_blk = ctx.cid.clone();
let stats_blk = ctx.stats.clone();
let want_logprobs = params.logprobs;
let ran = run_unary(&entry, &ctx, CHAT_INPUT, move |engine, cancel| {
let mut reasoning = String::new();
let mut content = String::new();
let mut tool_calls: Vec<OAIToolCall> = Vec::new();
let mut logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
let mut tally = ReqTally::new();
let outcome = generate(
engine,
prepared,
&messages,
tools.as_ref(),
tool_choice.as_deref(),
¶ms,
cancel,
&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 },
});
}
Delta::Logprob(t) => logprobs.push(t),
},
)?;
Ok((reasoning, content, tool_calls, logprobs, outcome, tally))
})
.await;
let ((reasoning, content, tool_calls, logprobs, outcome, tally), deadline_hit) = match ran {
Ok(ran) => ran,
Err(resp) => return *resp,
};
let ReqCtx {
id: req_id,
cid,
model_id,
created,
stream,
stats,
..
} = ctx;
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)
},
},
logprobs: want_logprobs.then(|| ChatLogprobs::from_tokens(&logprobs)),
finish_reason: finish.as_str().into(),
}],
usage: UsageInfo::from_outcome(&outcome),
})
.into_response()
}
async fn streaming(
entry: ModelEntry,
prepared: Option<PreparedRequest>,
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,
stream,
include_usage,
stats,
..
} = ctx.clone();
run_streamed(&entry, &ctx, move |mut job| {
job.send(sse_chunk(
&cid,
&model_id,
created,
DeltaPayload {
role: Some("assistant".into()),
..Default::default()
},
None,
None,
));
let Some(engine) = job.engine.clone() else {
job.done.fail("no engine loaded");
return;
};
let mut tc_index = 0usize;
let mut saw_tool_call = false;
let mut pending_logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
let mut tally = ReqTally::new();
let res = generate(
&*engine,
prepared,
&messages,
tools.as_ref(),
tool_choice.as_deref(),
¶ms,
&job.cancel,
&mut |delta| {
let payload = match delta {
Delta::Logprob(t) => {
pending_logprobs.push(t);
return;
}
Delta::Reasoning(t) => {
tally.on_text_delta(&stats);
DeltaPayload {
reasoning_content: Some(t),
..Default::default()
}
}
Delta::Content(t) => {
tally.on_text_delta(&stats);
DeltaPayload {
content: Some(t),
..Default::default()
}
}
Delta::ToolCall { name, arguments } => {
let tc = OAIToolCall {
index: tc_index,
id: tool_call_id(&cid, tc_index),
kind: "function",
function: OAIFunction { name, arguments },
};
tc_index += 1;
saw_tool_call = true;
DeltaPayload {
tool_calls: Some(vec![tc]),
..Default::default()
}
}
};
let logprobs = if pending_logprobs.is_empty() {
None
} else {
Some(ChatLogprobs::from_tokens(&std::mem::take(
&mut pending_logprobs,
)))
};
job.send(sse_chunk(&cid, &model_id, created, payload, logprobs, None));
},
);
match res {
Ok(outcome) => {
let finish = if saw_tool_call {
Finish::ToolCalls
} else {
job.finish(outcome.finish)
};
let last_logprobs = if pending_logprobs.is_empty() {
None
} else {
Some(ChatLogprobs::from_tokens(&pending_logprobs))
};
job.send(sse_chunk(
&cid,
&model_id,
created,
DeltaPayload::default(),
last_logprobs,
Some(finish.as_str().into()),
));
if include_usage {
job.send(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);
job.done.settled();
}
Err(e) => job.fail(&e, CHAT_INPUT),
}
})
.await
}
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,
logprobs: Option<ChatLogprobs>,
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,
logprobs,
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, input: &str) -> serde_json::Value {
invalid_request_body(Some(input), Some("context_length_exceeded"), &c.message)
}
fn request_error_body(e: &anyhow::Error, input: &str) -> Option<serde_json::Value> {
if let Some(c) = e.downcast_ref::<ContextLengthExceeded>() {
return Some(context_length_body(c, input));
}
e.downcast_ref::<ParamError>()
.map(|p| invalid_request_body(Some(p.param), None, &p.message))
}
fn error_response(e: &anyhow::Error, input: &str) -> Response {
match request_error_body(e, input) {
Some(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
None => json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
}
}
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 max_body_bytes(cfg: &Config) -> usize {
let n = match cfg.serve.max_body_bytes {
0 => Config::default().serve.max_body_bytes,
n => n,
};
usize::try_from(n).unwrap_or(usize::MAX)
}
fn sse_keep_alive(cfg: &Config) -> Option<Duration> {
let secs = cfg.serve.sse_keepalive_secs;
(secs > 0).then(|| Duration::from_secs(secs).min(MAX_SSE_KEEPALIVE))
}
const MAX_SSE_KEEPALIVE: Duration = Duration::from_secs(24 * 60 * 60);
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");
}
const TEST_VOCAB: usize = 1000;
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 vocab_size(&self) -> usize {
TEST_VOCAB
}
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,
})
}
}
struct LogprobGen;
impl ChatGenerator for LogprobGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
fn supports_logprobs(&self) -> bool {
true
}
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> {
assert!(params.logprobs, "the server only asks when requested");
let mut top = vec![infr_engine::TokenLogprobAlt {
token: 9,
text: "ho".into(),
bytes: b"ho".to_vec(),
logprob: -1.5,
}];
top.truncate(params.top_logprobs);
on_delta(Delta::Logprob(infr_engine::TokenLogprob {
token: 7,
text: "hi".into(),
bytes: b"hi".to_vec(),
logprob: -0.25,
top,
}));
on_delta(Delta::Content("hi".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 1,
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 replayed_tool_call_floats_survive_exactly() {
let floats = ["1e-25", "905046994.6356679", "2.5788702084023933e-304"];
let args = format!(
r#"{{"a":{},"b":{},"c":[{}]}}"#,
floats[0], floats[1], floats[2]
);
for arguments in [serde_json::to_string(&args).unwrap(), args.clone()] {
let raw = format!(
r#"{{"role":"assistant","content":null,"tool_calls":[
{{"type":"function","function":{{"name":"f","arguments":{arguments}}}}}]}}"#
);
let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(&raw).unwrap());
let a = &msg.tool_calls.expect("one call")[0].arguments;
let got = [&a["a"], &a["b"], &a["c"][0]].map(|v| v.as_f64().unwrap());
let want = floats.map(|f| f.parse::<f64>().unwrap());
assert_eq!(got.map(f64::to_bits), want.map(f64::to_bits), "{arguments}");
const PRINT: &str = "{% set a = messages[0].tool_calls[0].function.arguments %}\
{{ a.a }} {{ a.b }} {{ a.c[0] }}|{{ a | tojson }}";
let msgs = vec![serde_json::json!({"role": "assistant", "content": "",
"tool_calls": [{"type": "function",
"function": {"name": "f", "arguments": a}}]})];
let prompt = infr_chat::render_template(
PRINT,
msgs,
serde_json::Value::Null,
"",
"",
false,
true,
)
.unwrap();
assert_eq!(
prompt,
format!(
r#"{0} {1} {2}|{{"a": {0}, "b": {1}, "c": [{2}]}}"#,
floats[0], floats[1], floats[2]
)
);
}
}
#[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,
},
logprobs: 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,
},
logprobs: 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(),
},
}]),
},
logprobs: None,
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()
},
logprobs: None,
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()
},
logprobs: None,
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()
},
logprobs: None,
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()
},
logprobs: None,
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(), logprobs: None,
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":[],"user":"bob","response_format":{"type":"text"}}"#,
))
.unwrap();
assert_eq!(p, GenParams::default());
}
#[test]
fn neutral_choice_and_logprob_fields_are_accepted() {
for raw in [
r#"{"model":"m","messages":[],"n":1,"logprobs":false,"top_logprobs":0,"logit_bias":{}}"#,
r#"{"model":"m","messages":[],"n":null,"logprobs":null,"top_logprobs":null,
"logit_bias":null,"min_p":null}"#,
] {
let p = GenParams::from_request(&req(raw)).unwrap();
assert_eq!(p, GenParams::default(), "{raw}");
}
}
#[test]
fn min_p_and_logit_bias_parse() {
let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"min_p":0.05,
"logit_bias":{"50256":-100,"7":3.5,"12":100}}"#))
.unwrap();
assert_eq!(p.min_p, Some(0.05));
assert_eq!(p.logit_bias, vec![(7, 3.5), (12, 100.0), (50256, -100.0)]);
}
#[test]
fn zero_ids_and_whole_number_counts_are_accepted() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"n":1.0,"top_logprobs":0.0,"logit_bias":{"0":-1}}"#,
))
.unwrap();
assert_eq!(p.logit_bias, vec![(0, -1.0)]);
}
#[test]
fn logit_bias_ids_are_checked_against_the_vocabulary() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"logit_bias":{"999":1,"3":-1}}"#,
))
.unwrap();
assert_eq!(p.check_vocab(1000), Ok(()));
let e = p.check_vocab(999).unwrap_err();
assert_eq!(e.param, "logit_bias");
assert!(e.message.contains("999"), "{}", e.message);
}
#[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 logprobs_are_accepted_and_bounded() {
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":5}"#,
))
.unwrap();
assert!(p.logprobs);
assert_eq!(p.top_logprobs, 5);
let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"logprobs":true}"#))
.unwrap();
assert!(p.logprobs);
assert_eq!(p.top_logprobs, MAX_TOP_LOGPROBS);
let p = GenParams::from_request(&req(
r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":0}"#,
))
.unwrap();
assert!(p.logprobs);
assert_eq!(p.top_logprobs, 0);
}
#[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",
),
(r#"{"model":"m","messages":[],"min_p":-0.1}"#, "min_p"),
(r#"{"model":"m","messages":[],"min_p":1.5}"#, "min_p"),
(
r#"{"model":"m","messages":[],"logit_bias":[1]}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"a":1}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"-1":1}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"5":"x"}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"5":100.5}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"5":-101}}"#,
"logit_bias",
),
(r#"{"model":"m","messages":[],"n":2}"#, "n"),
(r#"{"model":"m","messages":[],"n":0}"#, "n"),
(
r#"{"model":"m","messages":[],"top_logprobs":3}"#,
"top_logprobs",
),
(
r#"{"model":"m","messages":[],"top_logprobs":-1}"#,
"top_logprobs",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"+5":-100}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"05":-100}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{" 5":-100}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"":-100}}"#,
"logit_bias",
),
(
r#"{"model":"m","messages":[],"logit_bias":{"5":-100,"5":-100}}"#,
"logit_bias",
),
(r#"{"model":"m","messages":[],"n":1.5}"#, "n"),
(r#"{"model":"m","messages":[],"n":"1"}"#, "n"),
(
r#"{"model":"m","messages":[],"top_logprobs":0.5}"#,
"top_logprobs",
),
(
r#"{"model":"m","messages":[],"top_logprobs":[]}"#,
"top_logprobs",
),
(
r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":21}"#,
"top_logprobs",
),
] {
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 vocab_size(&self) -> usize {
TEST_VOCAB
}
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,
keep_alive: None,
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)),
None,
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(),
None,
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"))),
None,
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)),
None,
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 vocab_size(&self) -> usize {
TEST_VOCAB
}
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 RefusingGen;
impl ChatGenerator for RefusingGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
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(ParamError {
param: "min_p",
message: "min_p is not supported by the test backend".into(),
}
.into())
}
}
#[tokio::test]
async fn a_generator_param_error_is_a_400_naming_the_field() {
let gen: Arc<dyn ChatGenerator> = Arc::new(RefusingGen);
let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
let resp = post_chat(router_for(gen.clone()), &format!("{{{base}}}")).await;
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"], "min_p");
let resp = post_chat(router_for(gen), &format!(r#"{{{base},"stream":true}}"#)).await;
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(text.contains(r#""param":"min_p""#), "{text}");
assert!(text.contains("invalid_request_error"), "{text}");
}
struct PanicGen;
impl ChatGenerator for PanicGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
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"))),
None,
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)),
None,
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()
}
struct VocabCountingGen(Arc<AtomicU64>);
impl ChatGenerator for VocabCountingGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
self.0.fetch_add(1, Ordering::Relaxed);
TEST_VOCAB
}
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: 1,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
#[tokio::test]
async fn the_vocab_size_is_read_only_for_a_logit_bias() {
let calls = Arc::new(AtomicU64::new(0));
let gen: Arc<dyn ChatGenerator> = Arc::new(VocabCountingGen(calls.clone()));
let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
for extra in ["", r#","logit_bias":{}"#, r#","logit_bias":null"#] {
let resp = post_chat(router_for(gen.clone()), &format!("{{{base}{extra}}}")).await;
assert_eq!(resp.status(), StatusCode::OK);
}
assert_eq!(calls.load(Ordering::Relaxed), 0, "asked without a bias");
let body = format!(r#"{{{base},"logit_bias":{{"3":-100}}}}"#);
let resp = post_chat(router_for(gen), &body).await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(calls.load(Ordering::Relaxed), 1, "the bias was not checked");
}
#[tokio::test]
async fn unsupported_and_invalid_sampling_fields_are_400s() {
let gen: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
let vocab = TEST_VOCAB;
for stream in [false, true] {
for (extra, param) in [
(r#""n":2"#.to_string(), "n"),
(r#""logprobs":true"#.to_string(), "logprobs"),
(r#""top_logprobs":2"#.to_string(), "top_logprobs"),
(r#""min_p":2"#.to_string(), "min_p"),
(r#""logit_bias":{"1":-150}"#.to_string(), "logit_bias"),
(format!(r#""logit_bias":{{"{vocab}":-100}}"#), "logit_bias"),
(
r#""logit_bias":{"5":-100,"+5":-100}"#.to_string(),
"logit_bias",
),
(r#""n":"2""#.to_string(), "n"),
(r#""top_logprobs":1.5"#.to_string(), "top_logprobs"),
] {
let body = format!(r#"{{{base},"stream":{stream},{extra}}}"#);
let resp = post_chat(router_for(gen.clone()), &body).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{body}");
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", "{body}");
assert_eq!(v["error"]["param"], param, "{body}");
}
}
let last = vocab - 1;
let body = format!(
r#"{{{base},"n":1.0,"logprobs":false,"top_logprobs":0,"min_p":0.1,
"logit_bias":{{"{last}":-100}}}}"#
);
let resp = post_chat(router_for(gen), &body).await;
assert_eq!(resp.status(), StatusCode::OK, "{body}");
}
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 vocab_size(&self) -> usize {
TEST_VOCAB
}
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:?}"
);
}
#[tokio::test]
async fn logprobs_are_returned_on_the_non_streaming_choice() {
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
"logprobs":true,"top_logprobs":1}"#;
let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
assert_eq!(v["choices"][0]["message"]["content"], "hi");
let lp = &v["choices"][0]["logprobs"]["content"][0];
assert_eq!(lp["id"], 7);
assert_eq!(lp["token"], "hi");
assert_eq!(lp["bytes"], serde_json::json!([104, 105]));
assert_eq!(lp["logprob"], -0.25);
assert_eq!(lp["top_logprobs"][0]["id"], 9);
assert_eq!(lp["top_logprobs"][0]["token"], "ho");
assert_eq!(lp["top_logprobs"][0]["logprob"], -1.5);
}
#[tokio::test]
async fn zero_top_logprobs_returns_entries_without_alternatives() {
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
"logprobs":true,"top_logprobs":0}"#;
let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
let lp = &v["choices"][0]["logprobs"]["content"][0];
assert_eq!(lp["token"], "hi");
assert_eq!(lp["logprob"], -0.25);
assert_eq!(lp["top_logprobs"], serde_json::json!([]));
}
#[tokio::test]
async fn logprobs_ride_the_streaming_text_chunk() {
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
"stream":true,"logprobs":true,"top_logprobs":1}"#;
let frames = sse_frames(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
let chunk = frames
.iter()
.filter(|f| *f != "[DONE]")
.map(|f| serde_json::from_str::<serde_json::Value>(f).unwrap())
.find(|v| v["choices"][0]["delta"]["content"] == "hi")
.expect("a content chunk");
let lp = &chunk["choices"][0]["logprobs"]["content"][0];
assert_eq!(lp["token"], "hi");
assert_eq!(lp["logprob"], -0.25);
assert_eq!(lp["top_logprobs"][0]["token"], "ho");
}
#[tokio::test]
async fn logprobs_on_a_backend_without_them_is_a_400() {
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
"logprobs":true}"#;
let resp = post_chat(router_for(Arc::new(EchoGen("a"))), body).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let v = body_json(resp).await;
assert_eq!(v["error"]["param"], "logprobs");
}
struct OverflowGen;
impl ChatGenerator for OverflowGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
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 vocab_size(&self) -> usize {
TEST_VOCAB
}
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);
}
fn format_of(raw: &str) -> Result<Option<ResponseFormat>, ParamError> {
GenParams::from_request(&req(&format!(
r#"{{"model":"m","messages":[],"response_format":{raw}}}"#
)))
.map(|p| p.response_format)
}
#[test]
fn response_format_parses_and_refuses_what_it_cannot_do() {
let schema =
serde_json::json!({"type": "object", "properties": {"a": {"type": "integer"}}});
assert_eq!(format_of("null"), Ok(None));
assert_eq!(format_of(r#"{"type":"text"}"#), Ok(None));
assert_eq!(
format_of(r#"{"type":"json_object"}"#),
Ok(Some(ResponseFormat::JsonObject))
);
assert_eq!(
format_of(&format!(
r#"{{"type":"json_schema",
"json_schema":{{"name":"x","strict":true,"schema":{schema}}}}}"#
)),
Ok(Some(ResponseFormat::JsonSchema(schema.clone())))
);
assert_eq!(
format_of(&format!(r#"{{"type":"json_object","schema":{schema}}}"#)),
Ok(Some(ResponseFormat::JsonSchema(schema)))
);
assert_eq!(
ResponseFormat::JsonObject.schema(),
serde_json::json!({"type": "object"})
);
for any in [
r#"{"type":"json_schema"}"#,
r#"{"type":"json_schema","json_schema":{"name":"x"}}"#,
r#"{"type":"json_schema","json_schema":{"name":"x","schema":null}}"#,
r#"{"type":"json_schema","json_schema":null}"#,
] {
assert_eq!(
format_of(any),
Ok(Some(ResponseFormat::JsonSchema(serde_json::json!({})))),
"{any}"
);
}
for bad in [
r#"{"type":"xml"}"#,
r#"{"type":"json_schema","json_schema":"x"}"#,
r#"{"type":"json_schema","json_schema":{"schema":"object"}}"#,
r#"{"type":"json_object","schema":[]}"#,
r#""json_object""#,
r#"{"kind":"json_object"}"#,
] {
let e = format_of(bad).expect_err(bad);
assert_eq!(e.param, "response_format", "{bad}");
}
assert!(format_of(r#"{"type":"xml"}"#)
.unwrap_err()
.message
.contains("\"xml\""));
}
#[derive(Default)]
struct FormatProbe(std::sync::Mutex<Vec<Option<ResponseFormat>>>);
impl ChatGenerator for FormatProbe {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
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.0.lock().unwrap().push(params.response_format.clone());
on_delta(Delta::Content("{}".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
#[tokio::test]
async fn response_format_reaches_the_generator_or_is_a_400() {
let probe = Arc::new(FormatProbe::default());
let router = router_for(probe.clone());
let ok = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
"response_format":{"type":"json_object"}}"#;
assert_eq!(post_chat(router.clone(), ok).await.status(), StatusCode::OK);
for stream in [false, true] {
let bad = format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream},
"response_format":{{"type":"yaml"}}}}"#
);
let resp = post_chat(router.clone(), &bad).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
let v = body_json(resp).await;
assert_eq!(v["error"]["type"], "invalid_request_error");
assert_eq!(v["error"]["param"], "response_format");
}
assert_eq!(
*probe.0.lock().unwrap(),
vec![Some(ResponseFormat::JsonObject)]
);
}
struct RefuseGen {
in_count: bool,
chats: AtomicU64,
}
impl RefuseGen {
fn refusal() -> anyhow::Error {
ParamError {
param: "response_format",
message: "response_format cannot be enforced: unsupported keyword".into(),
}
.into()
}
}
impl ChatGenerator for RefuseGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
fn prepare(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
) -> anyhow::Result<Option<PreparedRequest>> {
if self.in_count {
Err(Self::refusal())
} else {
Ok(None)
}
}
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.chats.fetch_add(1, Ordering::Relaxed);
Err(Self::refusal())
}
}
#[tokio::test]
async fn a_generator_param_error_is_a_400() {
let body = |stream: bool| {
format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
)
};
let early = Arc::new(RefuseGen {
in_count: true,
chats: AtomicU64::new(0),
});
for stream in [false, true] {
let resp = post_chat(router_for(early.clone()), &body(stream)).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
let v = body_json(resp).await;
assert_eq!(v["error"]["param"], "response_format");
assert_eq!(v["error"]["type"], "invalid_request_error");
}
assert_eq!(early.chats.load(Ordering::Relaxed), 0);
let late = Arc::new(RefuseGen {
in_count: false,
chats: AtomicU64::new(0),
});
let resp = post_chat(router_for(late.clone()), &body(false)).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_json(resp).await["error"]["param"], "response_format");
let frames = sse_frames(post_chat(router_for(late), &body(true)).await).await;
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"]["param"], "response_format");
}
#[derive(Default)]
struct CountGen {
tokens: u32,
limit: Option<u32>,
prepares: AtomicU64,
prepared: AtomicU64,
chats: AtomicU64,
}
struct CountState(u32);
impl ChatGenerator for CountGen {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
fn prepare(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
) -> anyhow::Result<Option<PreparedRequest>> {
self.prepares.fetch_add(1, Ordering::Relaxed);
Ok(Some(PreparedRequest::new(
self.tokens,
self.limit,
CountState(self.tokens),
)))
}
fn chat_prepared(
&self,
prepared: PreparedRequest,
_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> {
let CountState(tokens) = prepared.into_state().expect("our own prepared state");
self.prepared.fetch_add(1, Ordering::Relaxed);
on_delta(Delta::Content("ok".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: tokens,
completion_tokens: 1,
cached_tokens: 0,
})
}
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.chats.fetch_add(1, Ordering::Relaxed);
on_delta(Delta::Content("ok".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: self.tokens,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
#[tokio::test]
async fn an_over_long_prompt_is_refused_before_it_takes_a_slot() {
let long = Arc::new(CountGen {
tokens: 100,
limit: Some(99),
..Default::default()
});
let state = AppState::new(long.clone(), "m", 1, Arc::new(Config::default()));
let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
let router = build_router(state);
for stream in [false, true] {
let body = format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
);
let resp =
tokio::time::timeout(Duration::from_secs(2), post_chat(router.clone(), &body))
.await
.expect("an over-long prompt waited for a slot");
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], "context_length_exceeded");
assert_eq!(v["error"]["param"], "messages");
assert_eq!(
v["error"]["message"],
"This model's maximum context length is 99 tokens. However, your messages \
resulted in 100 tokens. Please reduce the length of the messages."
);
}
drop(held);
assert_eq!(long.prepared.load(Ordering::Relaxed), 0);
assert_eq!(long.chats.load(Ordering::Relaxed), 0);
for (tokens, limit) in [(99, Some(99)), (100_000, None)] {
let g = Arc::new(CountGen {
tokens,
limit,
..Default::default()
});
let resp = post_chat(
router_for(g.clone()),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::OK, "{tokens} / {limit:?}");
assert_eq!(body_json(resp).await["usage"]["prompt_tokens"], tokens);
}
}
struct SlowFirstToken(Duration);
impl ChatGenerator for SlowFirstToken {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
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> {
std::thread::sleep(self.0);
on_delta(Delta::Content("late".into()));
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
async fn slow_stream_body(secs: u64) -> String {
let mut cfg = Config::default();
cfg.serve.sse_keepalive_secs = secs;
let g: Arc<dyn ChatGenerator> = Arc::new(SlowFirstToken(Duration::from_millis(1600)));
let resp = post_chat(
build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
)
.await;
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn a_quiet_stream_carries_keep_alive_comments_unless_disabled() {
let comment = |body: &str| body.lines().any(|l| l.starts_with(':'));
let on = slow_stream_body(1).await;
assert!(comment(&on), "no keep-alive comment: {on:?}");
let off = slow_stream_body(0).await;
assert!(!comment(&off), "keep-alive sent while disabled: {off:?}");
for body in [&on, &off] {
assert!(body.contains("\"late\""), "{body:?}");
assert!(body.contains("[DONE]"), "{body:?}");
}
assert_eq!(
sse_keep_alive(&Config::default()),
Some(Duration::from_secs(15))
);
}
#[tokio::test]
async fn a_huge_keep_alive_interval_is_bounded_not_a_panic() {
let mut cfg = Config::default();
cfg.serve.sse_keepalive_secs = u64::MAX;
assert_eq!(sse_keep_alive(&cfg), Some(MAX_SSE_KEEPALIVE));
let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
let frames = sse_frames(
post_chat(
build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
)
.await,
)
.await;
assert_eq!(
frames.last().map(String::as_str),
Some("[DONE]"),
"{frames:?}"
);
}
#[tokio::test]
async fn a_request_is_prepared_once_and_generated_from_its_preparation() {
for stream in [false, true] {
let g = Arc::new(CountGen {
tokens: 7,
..Default::default()
});
let body = format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
);
let resp = post_chat(router_for(g.clone()), &body).await;
assert_eq!(resp.status(), StatusCode::OK);
let _ = resp.into_body().collect().await.unwrap();
let counts = |c: &AtomicU64| c.load(Ordering::Relaxed);
assert_eq!(
(counts(&g.prepares), counts(&g.prepared), counts(&g.chats)),
(1, 1, 0),
"stream={stream}"
);
}
let probe = Arc::new(FormatProbe::default());
let resp = post_chat(
router_for(probe.clone()),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
probe.0.lock().unwrap().len(),
1,
"a non-preparing generator still chats"
);
}
#[tokio::test]
async fn malformed_tools_and_unknown_tool_choices_are_400s_naming_the_field() {
let probe = Arc::new(FormatProbe::default());
for (extra, param) in [
(r#""tools":[{"type":"function","function":{}}]"#, "tools"),
(r#""tools":{"a":1}"#, "tools"),
(
r#""tools":[{"type":"function","function":{"name":"f"}}],
"tool_choice":{"type":"function","function":{"name":"g"}}"#,
"tool_choice",
),
] {
let body =
format!(r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],{extra}}}"#);
let resp = post_chat(router_for(probe.clone()), &body).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{extra}");
assert_eq!(body_json(resp).await["error"]["param"], param, "{extra}");
}
assert!(probe.0.lock().unwrap().is_empty());
}
#[tokio::test]
async fn the_body_limit_is_configurable() {
let mut cfg = Config::default();
cfg.serve.max_body_bytes = 1024;
let router = build_router(AppState::new(Arc::new(EchoGen("a")), "m", 1, Arc::new(cfg)));
let body = |n: usize| {
format!(
r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
"x".repeat(n)
)
};
let resp = post_chat(router.clone(), &body(2048)).await;
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
body_json(resp).await["error"]["type"],
"invalid_request_error"
);
assert_eq!(post_chat(router, &body(512)).await.status(), StatusCode::OK);
let mut zero = Config::default();
zero.serve.max_body_bytes = 0;
assert_eq!(max_body_bytes(&zero), 2 << 20);
}
#[derive(Default)]
struct SlowPrepare {
running: AtomicU64,
most: AtomicU64,
prepares: AtomicU64,
}
impl SlowPrepare {
fn slow_prepare(&self) {
self.prepares.fetch_add(1, Ordering::Relaxed);
let now = self.running.fetch_add(1, Ordering::SeqCst) + 1;
self.most.fetch_max(now, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(150));
self.running.fetch_sub(1, Ordering::SeqCst);
}
}
impl ChatGenerator for SlowPrepare {
fn status(&self) -> GeneratorStatus {
cpu_status()
}
fn vocab_size(&self) -> usize {
TEST_VOCAB
}
fn prepare(
&self,
_messages: &[ChatMessage],
_tools: Option<&serde_json::Value>,
_tool_choice: Option<&str>,
_params: &GenParams,
) -> anyhow::Result<Option<PreparedRequest>> {
self.slow_prepare();
Ok(None)
}
fn prepare_completion(&self, prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
self.slow_prepare();
Ok(Some((prompt.len() as u32, None)))
}
fn complete(
&self,
_prompt: &str,
_params: &GenParams,
_cancel: &Arc<AtomicBool>,
on_text: &mut dyn FnMut(&str),
) -> anyhow::Result<ChatOutcome> {
on_text("ok");
Ok(ChatOutcome {
finish: Finish::Stop,
prompt_tokens: 1,
completion_tokens: 1,
cached_tokens: 0,
})
}
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: 1,
completion_tokens: 1,
cached_tokens: 0,
})
}
}
#[tokio::test]
async fn concurrent_preparations_are_bounded_by_the_slots() {
let g = Arc::new(SlowPrepare::default());
let router = build_router(AppState::new(
g.clone(),
"m",
2,
Arc::new(Config::default()),
));
let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
let all = (0..5).map(|_| post_chat(router.clone(), body));
for resp in futures_util::future::join_all(all).await {
assert_eq!(resp.status(), StatusCode::OK);
}
assert_eq!(g.prepares.load(Ordering::Relaxed), 5);
assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
}
#[tokio::test]
async fn completion_preparations_share_the_chat_bound() {
let g = Arc::new(SlowPrepare::default());
let router = build_router(AppState::new(
g.clone(),
"m",
2,
Arc::new(Config::default()),
));
let chat = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
let raw = r#"{"model":"m","prompt":"hi"}"#;
let all = (0..6).map(|i| {
let router = router.clone();
async move {
let (uri, body) = if i % 2 == 0 {
("/v1/chat/completions", chat)
} else {
("/v1/completions", raw)
};
router
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap()
}
});
for resp in futures_util::future::join_all(all).await {
assert_eq!(resp.status(), StatusCode::OK);
}
assert_eq!(g.prepares.load(Ordering::Relaxed), 6);
assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
}
#[tokio::test]
async fn an_abandoned_wait_for_preparation_is_cancelled() {
let g = Arc::new(SlowPrepare::default());
let state = AppState::new(g.clone(), "m", 1, Arc::new(Config::default()));
let prepares = state.models[0].prepares.clone();
let held = prepares.clone().acquire_owned().await.unwrap();
let waited = tokio::time::timeout(
Duration::from_millis(200),
post_chat(
build_router(state),
r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
),
)
.await;
assert!(waited.is_err(), "the request must still be waiting");
drop(held);
assert_eq!(prepares.available_permits(), 1);
assert_eq!(g.prepares.load(Ordering::Relaxed), 0);
}
}