From c1d82e48fd833cf3ec75338addd217eb22f85e5a Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:08:36 -0800 Subject: [PATCH 01/14] feat(model): conversations of several turns, drawing a token from the scores, generation that continues from where the model stands --- crates/dluth-model/src/inkling/mod.rs | 1 + crates/dluth-model/src/inkling/model.rs | 87 ++++++++--- crates/dluth-model/src/inkling/prompt.rs | 109 ++++++++++++++ crates/dluth-model/src/inkling/sample.rs | 184 +++++++++++++++++++++++ 4 files changed, 360 insertions(+), 21 deletions(-) create mode 100644 crates/dluth-model/src/inkling/sample.rs diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 3315744..c3d3ee9 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -4,6 +4,7 @@ pub mod config; pub mod draft; pub mod model; pub mod prompt; +pub mod sample; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; pub use draft::{DraftStats, Drafter, LookupDrafter, NoDraft}; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 86093f8..a2e0d6c 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -1200,30 +1200,75 @@ impl<'w, O: Ops> Inkling<'w, O> { self.max_seq ))); } + let mut pos = 0; + if max_new > 0 { + for batch in prompt_ids.chunks(self.prompt_batch) { + self.advance(batch, pos)?; + pos += batch.len(); + } + } + let mut text = prompt_ids.to_vec(); + let mut emit = |token| { + on_token(token); + true + }; + let stats = + self.continue_drafted(&mut text, max_new, eos, drafter, most, &mut |scores| argmax(scores), &mut emit)?; + Ok((text.split_off(prompt_ids.len()), stats)) + } + + /// Generation from where the model stands: `text` is every token fed so far (at least + /// one), and up to `max_new` more are chosen, appended to `text` and reported. + /// + /// `pick` chooses a token from the scores of a position: the highest for greedy + /// generation, or a draw from them. Guesses are checked against what `pick` returns, so + /// the text is distributed exactly as without guesses whatever `pick` is. `on_token` is + /// given each token the moment it is chosen and returns false to stop there. Generation + /// also stops after `eos` (which is reported and appended). + /// + /// On return the model has been fed all of `text` except its last token, unless nothing + /// was generated. + #[allow(clippy::too_many_arguments)] + pub fn continue_drafted( + &mut self, + text: &mut Vec, + max_new: usize, + eos: u32, + drafter: &mut dyn Drafter, + most: usize, + pick: &mut dyn FnMut(&[f32]) -> u32, + on_token: &mut dyn FnMut(u32) -> bool, + ) -> Result { let mut stats = DraftStats::default(); - let mut generated = Vec::with_capacity(max_new); if max_new == 0 { - return Ok((generated, stats)); + return Ok(stats); } - let mut pos = 0; - for batch in prompt_ids.chunks(self.prompt_batch) { - self.advance(batch, pos)?; - pos += batch.len(); + let mut pos = text.len(); + if pos == 0 || pos != self.cached { + return Err(ModelError::Capacity(format!( + "generation continues a text of {pos} tokens, and the model has been fed {}", + self.cached + ))); + } + if max_new > self.max_seq - pos { + return Err(ModelError::Capacity(format!( + "a text of {pos} tokens plus {max_new} new tokens exceeds the history of {} positions", + self.max_seq + ))); } let (vocab, vocab_out) = (self.cfg.vocab, self.cfg.vocab_out); - let mut text = prompt_ids.to_vec(); - let mut next = argmax(&self.logits(true)?); - generated.push(next); + let mut generated = 1; + let mut next = pick(&self.logits(true)?); text.push(next); - on_token(next); - while next != eos && generated.len() < max_new { + let mut go_on = on_token(next); + while go_on && next != eos && generated < max_new { // A sweep with k guesses can produce k + 1 tokens: no more guesses than there - // is room for tokens. The positions fit, because the prompt and `max_new` + // is room for tokens. The positions fit, because the text and `max_new` // tokens do. - let room = (max_new - generated.len() - 1).min(most).min(MAX_DRAFT); + let room = (max_new - generated - 1).min(most).min(MAX_DRAFT); let mut batch = vec![next]; if room > 0 { - let guesses = drafter.draft(&text, room); + let guesses = drafter.draft(text, room); // A guess is only a guess: never more than asked for, never outside the // vocabulary. batch.extend(guesses.into_iter().take(room).take_while(|g| (*g as usize) < vocab)); @@ -1237,16 +1282,16 @@ impl<'w, O: Ops> Inkling<'w, O> { }; stats.sweeps += 1; stats.drafted += guessed; - // Position i's scores are for the token after batch[i]. While the model's - // choice is the next guess, that guess stands and the next position counts. + // Position i's scores are for the token after batch[i]. While the choice made + // from them is the next guess, that guess stands and the next position counts. let mut kept = 0; for (i, at) in scores.chunks_exact(vocab_out).enumerate() { - next = argmax(at); + next = pick(at); kept = i + 1; - generated.push(next); + generated += 1; text.push(next); - on_token(next); - if next == eos || generated.len() == max_new || batch.get(i + 1) != Some(&next) { + go_on = on_token(next); + if !go_on || next == eos || generated == max_new || batch.get(i + 1) != Some(&next) { break; } } @@ -1259,7 +1304,7 @@ impl<'w, O: Ops> Inkling<'w, O> { self.undo(batch.len() - kept)?; pos += kept; } - Ok((generated, stats)) + Ok(stats) } } diff --git a/crates/dluth-model/src/inkling/prompt.rs b/crates/dluth-model/src/inkling/prompt.rs index a591d26..9624ffb 100644 --- a/crates/dluth-model/src/inkling/prompt.rs +++ b/crates/dluth-model/src/inkling/prompt.rs @@ -63,10 +63,119 @@ pub fn single_turn(user: &str, effort: Effort) -> String { ) } +/// Who a message of a conversation is from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + System, + User, + Assistant, +} + +/// One message of a conversation. `reasoning` is what an assistant thought before its +/// answer, if that is known; it is only read for assistant messages. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Message { + pub role: Role, + pub content: String, + pub reasoning: Option, +} + +/// A conversation of text messages, ready for the model to answer, as the model's +/// published chat template writes it: system messages as they come, the effort level +/// before the first message that is not a system message (or at the end, if there is +/// none), each assistant turn closed by the token that ends a turn. Nothing follows the +/// last message; the model opens its own reply. +/// +/// As with `single_turn`, the text of a message is inserted as it is. +pub fn chat(messages: &[Message], effort: Effort) -> String { + let effort_line = + format!("<|message_system|><|content_text|>Thinking effort level: {}<|end_message|>", effort.level()); + let mut out = String::new(); + let mut effort_written = false; + for message in messages { + if !effort_written && message.role != Role::System { + out.push_str(&effort_line); + effort_written = true; + } + let role = match message.role { + Role::System => "<|message_system|>", + Role::User => "<|message_user|>", + Role::Assistant => "<|message_model|>", + }; + let reasoning = message.reasoning.as_deref().filter(|r| !r.is_empty() && message.role == Role::Assistant); + if let Some(reasoning) = reasoning { + out.push_str(&format!("{role}<|content_thinking|>{reasoning}<|end_message|>")); + } + // An assistant turn that is only reasoning has no empty text message after it. + if !message.content.is_empty() || reasoning.is_none() { + out.push_str(&format!("{role}<|content_text|>{}<|end_message|>", message.content)); + } + if message.role == Role::Assistant { + out.push_str("<|content_model_end_sampling|>"); + } + } + if !effort_written { + out.push_str(&effort_line); + } + out +} + #[cfg(test)] mod tests { use super::*; + fn message(role: Role, content: &str) -> Message { + Message { role, content: content.into(), reasoning: None } + } + + #[test] + fn a_chat_of_one_user_message_is_the_single_turn() { + assert_eq!(chat(&[message(Role::User, "Hi")], Effort::Low), single_turn("Hi", Effort::Low)); + } + + #[test] + fn a_chat_puts_the_effort_after_the_system_messages_and_closes_assistant_turns() { + let thought = Message { role: Role::Assistant, content: "4".into(), reasoning: Some("2 + 2".into()) }; + let only_thought = Message { role: Role::Assistant, content: String::new(), reasoning: Some("hm".into()) }; + let got = chat( + &[ + message(Role::System, "Be brief."), + message(Role::User, "2 + 2?"), + thought, + message(Role::User, "And 3 + 3?"), + only_thought, + message(Role::Assistant, ""), + message(Role::System, "Later note."), + ], + Effort::None, + ); + assert_eq!( + got, + "<|message_system|><|content_text|>Be brief.<|end_message|>\ + <|message_system|><|content_text|>Thinking effort level: 0<|end_message|>\ + <|message_user|><|content_text|>2 + 2?<|end_message|>\ + <|message_model|><|content_thinking|>2 + 2<|end_message|>\ + <|message_model|><|content_text|>4<|end_message|><|content_model_end_sampling|>\ + <|message_user|><|content_text|>And 3 + 3?<|end_message|>\ + <|message_model|><|content_thinking|>hm<|end_message|><|content_model_end_sampling|>\ + <|message_model|><|content_text|><|end_message|><|content_model_end_sampling|>\ + <|message_system|><|content_text|>Later note.<|end_message|>" + ); + // Only system messages, or none: the effort line still comes, last. + assert_eq!( + chat(&[message(Role::System, "S")], Effort::High), + "<|message_system|><|content_text|>S<|end_message|>\ + <|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|>" + ); + assert_eq!( + chat(&[], Effort::None), + "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>" + ); + // Reasoning on a message that is not the assistant's is not written. + let odd = Message { role: Role::User, content: "x".into(), reasoning: Some("y".into()) }; + assert!(!chat(&[odd], Effort::None).contains("thinking|>y")); + } + #[test] fn effort_names_parse_and_unknown_ones_are_refused() { assert_eq!(Effort::parse("high").unwrap(), Effort::High); diff --git a/crates/dluth-model/src/inkling/sample.rs b/crates/dluth-model/src/inkling/sample.rs new file mode 100644 index 0000000..6f875cc --- /dev/null +++ b/crates/dluth-model/src/inkling/sample.rs @@ -0,0 +1,184 @@ +//! Choosing a token from the scores of a position: the highest, or a draw. + +/// How a token is chosen. With a temperature of 0 the highest score wins; otherwise a +/// token is drawn with probability proportional to `exp(score / temperature)`, from the +/// smallest set of most likely tokens whose probabilities add up to `top_p`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sampling { + pub temperature: f32, + pub top_p: f32, + pub seed: u64, +} + +impl Sampling { + /// Always the highest score. + pub fn greedy() -> Self { + Sampling { temperature: 0.0, top_p: 1.0, seed: 0 } + } +} + +/// Draws tokens. The same seed and the same scores give the same tokens. +pub struct Sampler { + temperature: f32, + top_p: f32, + state: u64, +} + +/// A token whose score is this far (in units of the temperature) below the best has less +/// than a billionth of its probability and is never drawn. +const REACH: f32 = 21.0; + +impl Sampler { + /// Values outside their ranges are taken as the nearest allowed one: a temperature + /// below 0 or not a number as 0, a `top_p` outside (0, 1] or not a number as 1. + pub fn new(sampling: Sampling) -> Self { + let temperature = + if sampling.temperature > 0.0 && sampling.temperature.is_finite() { sampling.temperature } else { 0.0 }; + let top_p = if sampling.top_p > 0.0 && sampling.top_p <= 1.0 { sampling.top_p } else { 1.0 }; + Sampler { temperature, top_p, state: sampling.seed } + } + + /// Whether every choice is the highest score. + pub fn is_greedy(&self) -> bool { + self.temperature == 0.0 + } + + /// A number in [0, 1), the next of a fixed sequence for the seed (the splitmix64 + /// generator: Steele, Lea and Flood, "Fast splittable pseudorandom number generators", + /// 2014). + fn uniform(&mut self) -> f64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 11) as f64 / (1u64 << 53) as f64 + } + + /// The token chosen from `scores` (one per token, not empty). Ties for the highest + /// score go to the lowest token id, as in greedy generation everywhere else. + pub fn pick(&mut self, scores: &[f32]) -> u32 { + let mut best = 0; + for (i, v) in scores.iter().enumerate() { + if *v > scores[best] { + best = i; + } + } + if self.temperature == 0.0 { + return best as u32; + } + // Only tokens within reach of the best can be drawn: a few hundred of a vocabulary + // of hundreds of thousands, so sorting them is cheap. + let floor = scores[best] - REACH * self.temperature; + let mut near: Vec<(u32, f64)> = scores + .iter() + .enumerate() + .filter(|(_, s)| **s >= floor) + .map(|(i, s)| (i as u32, (((s - scores[best]) / self.temperature) as f64).exp())) + .collect(); + // Most likely first; equal weights by token id, so the order does not depend on + // anything but the scores. + near.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + let total: f64 = near.iter().map(|(_, w)| w).sum(); + if self.top_p < 1.0 { + let mut kept = 0.0; + let mut count = 0; + for (_, w) in &near { + kept += w; + count += 1; + if kept >= self.top_p as f64 * total { + break; + } + } + near.truncate(count); + } + let total: f64 = near.iter().map(|(_, w)| w).sum(); + let mut left = self.uniform() * total; + for (token, w) in &near { + if left < *w { + return *token; + } + left -= w; + } + // Rounding left a sliver past the last weight. + near[near.len() - 1].0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scores() -> Vec { + // Probabilities at temperature 1: 0.5, 0.25, 0.125, 0.125 for tokens 3, 0, 1, 2. + let p = [0.25f32, 0.125, 0.125, 0.5]; + p.iter().map(|p| p.ln() + 7.0).collect() + } + + fn draws(sampling: Sampling, n: usize) -> [usize; 4] { + let mut sampler = Sampler::new(sampling); + let mut counts = [0; 4]; + for _ in 0..n { + counts[sampler.pick(&scores()) as usize] += 1; + } + counts + } + + #[test] + fn temperature_zero_is_the_highest_score_and_ties_go_to_the_lowest_id() { + let mut greedy = Sampler::new(Sampling::greedy()); + assert!(greedy.is_greedy()); + assert_eq!(greedy.pick(&scores()), 3); + assert_eq!(greedy.pick(&[1.0, 5.0, 5.0, 2.0]), 1); + // Out-of-range settings fall back to greedy and to no cut. + for t in [-1.0, f32::NAN] { + assert!(Sampler::new(Sampling { temperature: t, top_p: 7.0, seed: 1 }).is_greedy()); + } + } + + #[test] + fn draws_follow_the_probabilities() { + let counts = draws(Sampling { temperature: 1.0, top_p: 1.0, seed: 42 }, 40_000); + // Expected 10000, 5000, 5000, 20000; three standard deviations are under 300. + for (got, want) in counts.iter().zip([10_000.0f64, 5_000.0, 5_000.0, 20_000.0]) { + assert!((*got as f64 - want).abs() < 300.0, "{counts:?}"); + } + // A lower temperature sharpens: at 0.5 the probabilities are squared and renormalized + // (16, 4, 1, 1 parts of 22 for tokens 3, 0, 1, 2). + let counts = draws(Sampling { temperature: 0.5, top_p: 1.0, seed: 42 }, 22_000); + assert!( + (counts[3] as f64 - 16_000.0).abs() < 250.0 && (counts[1] as f64 - 1_000.0).abs() < 120.0, + "{counts:?}" + ); + } + + #[test] + fn top_p_keeps_the_smallest_set_of_most_likely_tokens() { + // 0.5 is reached by token 3 alone; 0.6 needs token 0 too; 0.8 a third (the lower id + // of the two equal ones). + assert_eq!(draws(Sampling { temperature: 1.0, top_p: 0.5, seed: 7 }, 500), [0, 0, 0, 500]); + let counts = draws(Sampling { temperature: 1.0, top_p: 0.6, seed: 7 }, 3_000); + assert!(counts[1] == 0 && counts[2] == 0 && (counts[0] as f64 - 1_000.0).abs() < 100.0, "{counts:?}"); + let counts = draws(Sampling { temperature: 1.0, top_p: 0.8, seed: 7 }, 3_000); + assert!(counts[1] > 200 && counts[2] == 0, "{counts:?}"); + } + + #[test] + fn the_same_seed_gives_the_same_draws_and_another_seed_others() { + let run = |seed| { + let mut s = Sampler::new(Sampling { temperature: 1.0, top_p: 1.0, seed }); + (0..64).map(|_| s.pick(&scores())).collect::>() + }; + assert_eq!(run(5), run(5)); + assert_ne!(run(5), run(6)); + } + + #[test] + fn a_far_less_likely_token_is_never_drawn_and_one_token_is_always_it() { + let mut s = Sampler::new(Sampling { temperature: 1.0, top_p: 1.0, seed: 3 }); + for _ in 0..2_000 { + assert_eq!(s.pick(&[0.0, 40.0, -5.0]), 1); + } + assert_eq!(s.pick(&[2.5]), 0); + } +} From a0e92b914338e96a5a39290be07ce755e4594982 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:21 -0800 Subject: [PATCH 02/14] feat(serve): a chat-completions server: HTTP, the request and response formats, the reply reader, an engine that keeps its last conversation --- Cargo.lock | 8 + Cargo.toml | 11 +- crates/dluth-model/src/inkling/model.rs | 10 + crates/dluth-model/src/inkling/prompt.rs | 49 ++-- crates/dluth-serve/Cargo.toml | 18 ++ crates/dluth-serve/src/api.rs | 312 +++++++++++++++++++++++ crates/dluth-serve/src/engine.rs | 274 ++++++++++++++++++++ crates/dluth-serve/src/http.rs | 232 +++++++++++++++++ crates/dluth-serve/src/lib.rs | 21 ++ crates/dluth-serve/src/reply.rs | 212 +++++++++++++++ crates/dluth-serve/src/server.rs | 245 ++++++++++++++++++ crates/dluth-serve/tests/server.rs | 249 ++++++++++++++++++ 12 files changed, 1623 insertions(+), 18 deletions(-) create mode 100644 crates/dluth-serve/Cargo.toml create mode 100644 crates/dluth-serve/src/api.rs create mode 100644 crates/dluth-serve/src/engine.rs create mode 100644 crates/dluth-serve/src/http.rs create mode 100644 crates/dluth-serve/src/lib.rs create mode 100644 crates/dluth-serve/src/reply.rs create mode 100644 crates/dluth-serve/src/server.rs create mode 100644 crates/dluth-serve/tests/server.rs diff --git a/Cargo.lock b/Cargo.lock index eb27323..1db2072 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,6 +146,14 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "dluth-serve" +version = "0.0.0" +dependencies = [ + "dluth-model", + "serde_json", +] + [[package]] name = "either" version = "1.19.0" diff --git a/Cargo.toml b/Cargo.toml index 06e7557..e738fc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,10 +1,17 @@ [workspace] resolver = "2" -members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth", "crates/dluth-cuda"] +members = [ + "crates/dluth-core", + "crates/dluth-kernels", + "crates/dluth-model", + "crates/dluth-serve", + "crates/dluth", + "crates/dluth-cuda", +] # Plain `cargo build` and `cargo test` use these. A crate that needs a vendor # toolchain (dluth-cuda needs the CUDA toolkit) is in `members` only and is built # with `-p `. -default-members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth"] +default-members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth-serve", "crates/dluth"] [workspace.package] version = "0.0.0" diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index a2e0d6c..2fdd02c 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -1118,6 +1118,16 @@ impl<'w, O: Ops> Inkling<'w, O> { self.cached } + /// How many positions a sequence can have: the room reserved when the model was made. + pub fn capacity(&self) -> usize { + self.max_seq + } + + /// The model's configuration. + pub fn config(&self) -> &InklingConfig { + &self.cfg + } + /// Feeds one token at position `pos` and returns the scores for the token after it. /// Positions must be fed in order. Position 0 starts a new sequence. pub fn forward_token(&mut self, token: u32, pos: usize) -> Result, ModelError> { diff --git a/crates/dluth-model/src/inkling/prompt.rs b/crates/dluth-model/src/inkling/prompt.rs index 9624ffb..13239ad 100644 --- a/crates/dluth-model/src/inkling/prompt.rs +++ b/crates/dluth-model/src/inkling/prompt.rs @@ -97,22 +97,7 @@ pub fn chat(messages: &[Message], effort: Effort) -> String { out.push_str(&effort_line); effort_written = true; } - let role = match message.role { - Role::System => "<|message_system|>", - Role::User => "<|message_user|>", - Role::Assistant => "<|message_model|>", - }; - let reasoning = message.reasoning.as_deref().filter(|r| !r.is_empty() && message.role == Role::Assistant); - if let Some(reasoning) = reasoning { - out.push_str(&format!("{role}<|content_thinking|>{reasoning}<|end_message|>")); - } - // An assistant turn that is only reasoning has no empty text message after it. - if !message.content.is_empty() || reasoning.is_none() { - out.push_str(&format!("{role}<|content_text|>{}<|end_message|>", message.content)); - } - if message.role == Role::Assistant { - out.push_str("<|content_model_end_sampling|>"); - } + write_turn(&mut out, message); } if !effort_written { out.push_str(&effort_line); @@ -120,6 +105,35 @@ pub fn chat(messages: &[Message], effort: Effort) -> String { out } +/// More messages of a conversation whose beginning, with its effort level, has already +/// been written: what `chat` writes for them, without an effort line. +pub fn more_turns(messages: &[Message]) -> String { + let mut out = String::new(); + for message in messages { + write_turn(&mut out, message); + } + out +} + +fn write_turn(out: &mut String, message: &Message) { + let role = match message.role { + Role::System => "<|message_system|>", + Role::User => "<|message_user|>", + Role::Assistant => "<|message_model|>", + }; + let reasoning = message.reasoning.as_deref().filter(|r| !r.is_empty() && message.role == Role::Assistant); + if let Some(reasoning) = reasoning { + out.push_str(&format!("{role}<|content_thinking|>{reasoning}<|end_message|>")); + } + // An assistant turn that is only reasoning has no empty text message after it. + if !message.content.is_empty() || reasoning.is_none() { + out.push_str(&format!("{role}<|content_text|>{}<|end_message|>", message.content)); + } + if message.role == Role::Assistant { + out.push_str("<|content_model_end_sampling|>"); + } +} + #[cfg(test)] mod tests { use super::*; @@ -171,6 +185,9 @@ mod tests { chat(&[], Effort::None), "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>" ); + // A conversation written in two parts is the conversation written at once. + let all = [message(Role::User, "a"), message(Role::Assistant, "b"), message(Role::User, "c")]; + assert_eq!(format!("{}{}", chat(&all[..1], Effort::Low), more_turns(&all[1..])), chat(&all, Effort::Low)); // Reasoning on a message that is not the assistant's is not written. let odd = Message { role: Role::User, content: "x".into(), reasoning: Some("y".into()) }; assert!(!chat(&[odd], Effort::None).contains("thinking|>y")); diff --git a/crates/dluth-serve/Cargo.toml b/crates/dluth-serve/Cargo.toml new file mode 100644 index 0000000..90e1fc4 --- /dev/null +++ b/crates/dluth-serve/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "dluth-serve" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description.workspace = true + +[lints] +workspace = true + +[dependencies] +# The model, its tokenizer and its chat format: what a request is turned into and answered with. +dluth-model = { version = "0.0.0", path = "../dluth-model" } +# Requests and responses are JSON. Already a dependency of dluth-model. +serde_json = "1.0.154" diff --git a/crates/dluth-serve/src/api.rs b/crates/dluth-serve/src/api.rs new file mode 100644 index 0000000..0b08675 --- /dev/null +++ b/crates/dluth-serve/src/api.rs @@ -0,0 +1,312 @@ +//! The chat-completions request and its responses, as JSON. +//! +//! What is read from a request: `messages` (text only), `max_completion_tokens` or +//! `max_tokens`, `temperature`, `top_p`, `seed`, `stop`, `stream`, +//! `stream_options.include_usage`, `reasoning_effort`. What is refused, because answering +//! without it would not be what was asked for: tools, more than one choice, content that +//! is not text. Everything else is ignored. + +use dluth_model::inkling::prompt::{Effort, Message, Role}; +use serde_json::{json, Value}; + +#[derive(Clone, Debug, PartialEq)] +pub struct ChatRequest { + /// The name the client used for the model, echoed in the response. + pub model: Option, + pub messages: Vec, + pub max_tokens: Option, + pub temperature: Option, + pub top_p: Option, + pub seed: Option, + pub stop: Vec, + pub stream: bool, + pub include_usage: bool, + pub effort: Option, +} + +fn text_of(content: &Value, role: &str) -> Result { + match content { + Value::String(text) => Ok(text.clone()), + Value::Null => Ok(String::new()), + Value::Array(parts) => { + let mut out = String::new(); + for part in parts { + let kind = part.get("type").and_then(Value::as_str).unwrap_or("text"); + match (kind, part.get("text").and_then(Value::as_str)) { + ("text" | "input_text", Some(text)) => out.push_str(text), + _ => return Err(format!("a {role} message has content of type {kind:?}; only text is supported")), + } + } + Ok(out) + } + _ => Err(format!("the content of a {role} message is neither text nor a list of parts")), + } +} + +fn number(root: &Value, name: &str, read: impl Fn(&Value) -> Option) -> Result, String> { + match root.get(name) { + None | Some(Value::Null) => Ok(None), + Some(value) => read(value).map(Some).ok_or_else(|| format!("`{name}` is not a number this field takes")), + } +} + +/// Reads a chat-completions request. The error is a sentence for the client. +pub fn parse_chat(body: &[u8]) -> Result { + let root: Value = serde_json::from_slice(body).map_err(|e| format!("the body is not JSON: {e}"))?; + if !root.is_object() { + return Err("the body is not a JSON object".into()); + } + let Some(list) = root.get("messages").and_then(Value::as_array) else { + return Err("`messages` is missing or not a list".into()); + }; + if list.is_empty() { + return Err("`messages` is empty".into()); + } + let mut messages = Vec::with_capacity(list.len()); + for entry in list { + let name = entry.get("role").and_then(Value::as_str).unwrap_or(""); + let role = match name { + "system" | "developer" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + other => return Err(format!("a message has the role {other:?}; system, user and assistant are supported")), + }; + if entry.get("tool_calls").is_some_and(|t| t.as_array().is_some_and(|a| !a.is_empty())) { + return Err("a message has tool calls; tools are not supported".into()); + } + let content = text_of(entry.get("content").unwrap_or(&Value::Null), name)?; + let reasoning = entry.get("reasoning_content").and_then(Value::as_str).map(str::to_string); + messages.push(Message { role, content, reasoning }); + } + if root.get("tools").is_some_and(|t| t.as_array().is_some_and(|a| !a.is_empty())) { + return Err("the request declares tools; tools are not supported".into()); + } + if root.get("n").and_then(Value::as_u64).is_some_and(|n| n != 1) { + return Err("`n` other than 1 is not supported".into()); + } + let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()); + let max_tokens = match number(&root, "max_completion_tokens", count)? { + Some(n) => Some(n), + None => number(&root, "max_tokens", count)?, + }; + let real = |v: &Value| v.as_f64().map(|f| f as f32).filter(|f| f.is_finite() && *f >= 0.0); + let stop = match root.get("stop") { + None | Some(Value::Null) => Vec::new(), + Some(Value::String(one)) => vec![one.clone()], + Some(Value::Array(many)) => many + .iter() + .map(|s| s.as_str().map(str::to_string).ok_or("`stop` holds something that is not a string")) + .collect::>()?, + Some(_) => return Err("`stop` is neither a string nor a list of strings".into()), + }; + let effort = match root.get("reasoning_effort") { + None | Some(Value::Null) => None, + Some(Value::String(name)) => Some(Effort::parse(name).map_err(|e| e.to_string())?), + Some(_) => return Err("`reasoning_effort` is not a string".into()), + }; + Ok(ChatRequest { + model: root.get("model").and_then(Value::as_str).map(str::to_string), + messages, + max_tokens, + temperature: number(&root, "temperature", real)?, + top_p: number(&root, "top_p", real)?, + seed: number(&root, "seed", Value::as_u64)?, + stop, + stream: root.get("stream").and_then(Value::as_bool).unwrap_or(false), + include_usage: root + .get("stream_options") + .and_then(|o| o.get("include_usage")) + .and_then(Value::as_bool) + .unwrap_or(false), + effort, + }) +} + +/// Token counts of a finished request, and what the engine did to answer it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Usage { + pub prompt_tokens: usize, + pub completion_tokens: usize, + /// Tokens of the prompt that were not read again, because the model still held them. + pub reused_tokens: usize, + pub sweeps: usize, + pub guessed: usize, + pub guessed_right: usize, + pub prompt_seconds: f64, + pub generation_seconds: f64, +} + +impl Usage { + pub fn json(&self) -> Value { + json!({ + "prompt_tokens": self.prompt_tokens, + "completion_tokens": self.completion_tokens, + "total_tokens": self.prompt_tokens + self.completion_tokens, + "prompt_tokens_details": {"cached_tokens": self.reused_tokens}, + "dluth": { + "sweeps": self.sweeps, + "guessed": self.guessed, + "guessed_right": self.guessed_right, + "prompt_seconds": self.prompt_seconds, + "generation_seconds": self.generation_seconds, + }, + }) + } +} + +/// What every response to one request has in common. +#[derive(Clone, Debug)] +pub struct Envelope { + pub id: String, + pub model: String, + pub created: u64, +} + +/// The whole answer in one response. +pub fn completion(e: &Envelope, content: &str, reasoning: &str, finish: &str, usage: &Usage) -> String { + let mut message = json!({"role": "assistant", "content": content}); + if !reasoning.is_empty() { + message["reasoning_content"] = json!(reasoning); + } + json!({ + "id": e.id, + "object": "chat.completion", + "created": e.created, + "model": e.model, + "choices": [{"index": 0, "message": message, "finish_reason": finish}], + "usage": usage.json(), + }) + .to_string() +} + +/// One event of a streamed answer: a piece of the message, or (with `finish`) its end. +pub fn chunk(e: &Envelope, delta: Value, finish: Option<&str>) -> String { + json!({ + "id": e.id, + "object": "chat.completion.chunk", + "created": e.created, + "model": e.model, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], + }) + .to_string() +} + +/// The last event of a streamed answer when the client asked for the usage: no choices. +pub fn usage_chunk(e: &Envelope, usage: &Usage) -> String { + json!({ + "id": e.id, + "object": "chat.completion.chunk", + "created": e.created, + "model": e.model, + "choices": [], + "usage": usage.json(), + }) + .to_string() +} + +pub fn error(message: &str, kind: &str) -> String { + json!({"error": {"message": message, "type": kind}}).to_string() +} + +pub fn models(name: &str, created: u64) -> String { + json!({"object": "list", "data": [{"id": name, "object": "model", "created": created, "owned_by": "dluth"}]}) + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(text: &str) -> Result { + parse_chat(text.as_bytes()) + } + + #[test] + fn a_full_request_is_read() { + let r = parse( + r#"{"model":"m","messages":[ + {"role":"developer","content":"S"}, + {"role":"user","content":[{"type":"text","text":"a"},{"text":"b"}]}, + {"role":"assistant","content":null,"reasoning_content":"hm"}, + {"role":"user","content":"c"}], + "max_tokens":5,"max_completion_tokens":7,"temperature":0,"top_p":0.5,"seed":9, + "stop":["x","y"],"stream":true,"stream_options":{"include_usage":true}, + "reasoning_effort":"low","unknown":{"ignored":true},"tools":[],"n":1}"#, + ) + .unwrap(); + assert_eq!(r.model.as_deref(), Some("m")); + let roles: Vec = r.messages.iter().map(|m| m.role).collect(); + assert_eq!(roles, [Role::System, Role::User, Role::Assistant, Role::User]); + assert_eq!(r.messages[1].content, "ab"); + assert_eq!((r.messages[2].content.as_str(), r.messages[2].reasoning.as_deref()), ("", Some("hm"))); + assert_eq!((r.max_tokens, r.temperature, r.top_p, r.seed), (Some(7), Some(0.0), Some(0.5), Some(9))); + assert_eq!(r.stop, ["x", "y"]); + assert!(r.stream && r.include_usage); + assert_eq!(r.effort, Some(Effort::Low)); + } + + #[test] + fn a_minimal_request_has_no_settings() { + let r = parse(r#"{"messages":[{"role":"user","content":"hi"}],"stop":"END","max_tokens":3}"#).unwrap(); + assert_eq!((r.model, r.temperature, r.top_p, r.seed, r.effort), (None, None, None, None, None)); + assert_eq!((r.max_tokens, r.stop, r.stream, r.include_usage), (Some(3), vec!["END".to_string()], false, false)); + } + + #[test] + fn what_cannot_be_answered_as_asked_is_refused_in_words() { + for (body, word) in [ + ("not json", "not JSON"), + ("[1]", "not a JSON object"), + ("{}", "`messages`"), + (r#"{"messages":[]}"#, "empty"), + (r#"{"messages":[{"role":"tool","content":"x"}]}"#, "\"tool\""), + (r#"{"messages":[{"content":"x"}]}"#, "role"), + (r#"{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{}}]}]}"#, "image_url"), + (r#"{"messages":[{"role":"user","content":7}]}"#, "neither text"), + (r#"{"messages":[{"role":"assistant","content":"","tool_calls":[{"id":"1"}]}]}"#, "tool calls"), + (r#"{"messages":[{"role":"user","content":"x"}],"tools":[{"type":"function"}]}"#, "tools"), + (r#"{"messages":[{"role":"user","content":"x"}],"n":2}"#, "`n`"), + (r#"{"messages":[{"role":"user","content":"x"}],"temperature":-1}"#, "`temperature`"), + (r#"{"messages":[{"role":"user","content":"x"}],"max_tokens":"many"}"#, "`max_tokens`"), + (r#"{"messages":[{"role":"user","content":"x"}],"stop":[1]}"#, "`stop`"), + (r#"{"messages":[{"role":"user","content":"x"}],"reasoning_effort":"extreme"}"#, "extreme"), + ] { + let e = parse(body).unwrap_err(); + assert!(e.contains(word), "{body}: {e}"); + } + } + + #[test] + fn responses_are_the_shapes_clients_expect() { + let e = Envelope { id: "chatcmpl-1".into(), model: "m".into(), created: 5 }; + let usage = Usage { prompt_tokens: 3, completion_tokens: 4, reused_tokens: 2, ..Usage::default() }; + let v: Value = serde_json::from_str(&completion(&e, "hi \"you\"\n", "thought", "stop", &usage)).unwrap(); + assert_eq!(v["object"], "chat.completion"); + assert_eq!(v["choices"][0]["message"]["content"], "hi \"you\"\n"); + assert_eq!(v["choices"][0]["message"]["reasoning_content"], "thought"); + assert_eq!(v["choices"][0]["finish_reason"], "stop"); + assert_eq!( + (v["usage"]["total_tokens"].as_u64(), v["usage"]["prompt_tokens_details"]["cached_tokens"].as_u64()), + (Some(7), Some(2)) + ); + let v: Value = serde_json::from_str(&completion(&e, "x", "", "length", &usage)).unwrap(); + assert!(v["choices"][0]["message"].get("reasoning_content").is_none()); + + let text = chunk(&e, json!({"content": "a\nb"}), None); + assert!(!text.contains('\n'), "an event is one line"); + let v: Value = serde_json::from_str(&text).unwrap(); + assert_eq!( + (v["object"].as_str(), v["choices"][0]["delta"]["content"].as_str()), + (Some("chat.completion.chunk"), Some("a\nb")) + ); + assert!(v["choices"][0]["finish_reason"].is_null()); + let v: Value = serde_json::from_str(&chunk(&e, json!({}), Some("stop"))).unwrap(); + assert_eq!(v["choices"][0]["finish_reason"], "stop"); + let v: Value = serde_json::from_str(&usage_chunk(&e, &usage)).unwrap(); + assert!(v["choices"].as_array().unwrap().is_empty() && v["usage"]["completion_tokens"] == 4); + let v: Value = serde_json::from_str(&error("no \"such\" thing", "invalid_request_error")).unwrap(); + assert_eq!(v["error"]["message"], "no \"such\" thing"); + let v: Value = serde_json::from_str(&models("inkling-2-mini", 5)).unwrap(); + assert_eq!(v["data"][0]["id"], "inkling-2-mini"); + } +} diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs new file mode 100644 index 0000000..485f61a --- /dev/null +++ b/crates/dluth-serve/src/engine.rs @@ -0,0 +1,274 @@ +//! The model behind the server: a conversation in, pieces of a reply out. +//! +//! The engine remembers the conversation it answered last, as the exact tokens the model +//! was fed and produced. Chat clients send the whole conversation again with every turn. +//! When the next request is the remembered conversation plus the reply it was given plus +//! new messages, only the new messages are fed: the model still holds the rest. Anything +//! else starts the sequence from its first token. + +use crate::api::{ChatRequest, Usage}; +use crate::reply::{Delta, Markers, ReplyReader, StopFilter}; +use dluth_model::inkling::prompt::{chat, more_turns, Effort, Message, Role}; +use dluth_model::inkling::sample::{Sampler, Sampling}; +use dluth_model::inkling::{Drafter, Inkling, LookupDrafter, NoDraft, Ops}; +use dluth_model::tokenizer::Tokenizer; +use dluth_model::ModelError; +use std::time::Instant; + +/// Why a reply ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Finish { + /// The model ended its turn, or a stop string was reached. + Stop, + /// The limit on new tokens, or the end of the context, was reached. + Length, +} + +impl Finish { + pub fn name(self) -> &'static str { + match self { + Finish::Stop => "stop", + Finish::Length => "length", + } + } +} + +#[derive(Debug, PartialEq)] +pub enum EngineError { + /// The request cannot be answered as asked: the client's to fix. + Refused(String), + /// Something went wrong on this side. + Failed(String), +} + +/// Something that answers chat requests. +pub trait Engine { + /// The name the model is listed under. + fn name(&self) -> &str; + + /// Answers `request`, handing each piece of the reply to `sink` as it is produced. + /// `sink` returns false when nobody is listening any more, which ends the reply. + fn chat( + &mut self, + request: &ChatRequest, + sink: &mut dyn FnMut(Delta) -> bool, + ) -> Result<(Finish, Usage), EngineError>; +} + +/// How the engine generates. +#[derive(Clone, Debug)] +pub struct Options { + /// The name the model is listed under. + pub name: String, + /// Tokens fed at once when a prompt is read. + pub prompt_batch: usize, + /// Guessed tokens per sweep; 0 for none. + pub guesses: usize, + /// How many last tokens must have appeared before for a guess to be made. + pub match_run: usize, + /// Used when a request does not say. + pub temperature: f32, + /// Used when a request does not say. + pub effort: Effort, +} + +impl Default for Options { + fn default() -> Self { + Options { + name: "dluth".into(), + prompt_batch: 16, + guesses: 4, + match_run: 2, + temperature: 1.0, + effort: Effort::High, + } + } +} + +/// The conversation answered last. +struct Served { + messages: Vec, + effort: Effort, + /// The prompt's tokens and the reply's, ending with the token that ends a turn. + text: Vec, + /// The reply as the client was given it. + content: String, +} + +/// An Inkling model answering chat requests. +pub struct InklingEngine<'w, 't, O: Ops> { + model: Inkling<'w, O>, + tokenizer: &'t Tokenizer, + markers: Markers, + options: Options, + /// The tokens the model has been fed, in order. Empty when that is not known. + held: Vec, + served: Option, + requests: u64, +} + +fn refused(e: ModelError) -> EngineError { + match e { + ModelError::Capacity(m) | ModelError::Unsupported(m) => EngineError::Refused(m), + other => EngineError::Failed(other.to_string()), + } +} + +impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + pub fn new(model: Inkling<'w, O>, tokenizer: &'t Tokenizer, options: Options) -> Self { + let markers = Markers::of(tokenizer); + InklingEngine { model, tokenizer, markers, options, held: Vec::new(), served: None, requests: 0 } + } + + /// The prompt's tokens. If the request continues the conversation answered last, they + /// begin with that conversation's exact tokens, the model's own reply included. + fn prompt(&self, request: &ChatRequest, effort: Effort) -> Result, EngineError> { + if let Some(served) = &self.served { + let n = served.messages.len(); + let continues = served.effort == effort + && request.messages.len() > n + && request.messages[..n] == served.messages[..] + && request.messages[n].role == Role::Assistant + && request.messages[n].content.trim() == served.content.trim(); + if continues { + let more = more_turns(&request.messages[n + 1..]); + let mut tokens = served.text.clone(); + tokens.extend(self.tokenizer.encode(&more).map_err(refused)?); + return Ok(tokens); + } + } + self.tokenizer.encode(&chat(&request.messages, effort)).map_err(refused) + } + + /// Feeds `tokens`, of which the model may already hold a beginning. Returns how many + /// it held. + fn feed(&mut self, tokens: &[u32]) -> Result { + let reuse = !self.held.is_empty() + && tokens.len() > self.held.len() + && tokens.starts_with(&self.held) + && self.model.next_position() == self.held.len(); + let start = if reuse { self.held.len() } else { 0 }; + // Not known again until everything is fed: a failure half way must not leave a + // claim about what the model holds. + self.held.clear(); + let mut pos = start; + for batch in tokens[start..].chunks(self.options.prompt_batch.max(1)) { + self.model.feed(batch, pos)?; + pos += batch.len(); + } + Ok(start) + } +} + +impl Engine for InklingEngine<'_, '_, O> { + fn name(&self) -> &str { + &self.options.name + } + + fn chat( + &mut self, + request: &ChatRequest, + sink: &mut dyn FnMut(Delta) -> bool, + ) -> Result<(Finish, Usage), EngineError> { + self.requests += 1; + let effort = request.effort.unwrap_or(self.options.effort); + let tokens = self.prompt(request, effort)?; + let capacity = self.model.capacity(); + if tokens.len() >= capacity { + return Err(EngineError::Refused(format!( + "the conversation is {} tokens long, and the context holds {capacity}", + tokens.len() + ))); + } + let room = capacity - tokens.len(); + let max_new = request.max_tokens.unwrap_or(room).min(room); + if max_new == 0 { + return Err(EngineError::Refused("no new tokens were asked for".into())); + } + // The remembered conversation is gone from here on: either this request replaces + // it, or it fails and nothing is known. + self.served = None; + + let started = Instant::now(); + let reused = self.feed(&tokens).map_err(refused)?; + let prompt_seconds = started.elapsed().as_secs_f64(); + + let eos = self.model.config().eos; + let mut sampler = Sampler::new(Sampling { + temperature: request.temperature.unwrap_or(self.options.temperature), + top_p: request.top_p.unwrap_or(1.0), + // Without a seed from the client, each request draws differently. + seed: request.seed.unwrap_or_else(|| { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); + nanos ^ self.requests.wrapping_mul(0x9E37_79B9_7F4A_7C15) + }), + }); + let mut lookup = LookupDrafter::new(self.options.match_run.max(4), self.options.match_run); + let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut NoDraft } else { &mut lookup }; + + let mut reader = ReplyReader::new(self.tokenizer, self.markers); + let mut stops = StopFilter::new(&request.stop); + let mut content = String::new(); + let mut stopped = false; + let mut pass_on = |delta: Delta, content: &mut String, stopped: &mut bool| -> bool { + match delta { + Delta::Content(text) => { + let (text, hit) = stops.push(&text); + *stopped |= hit; + content.push_str(&text); + (text.is_empty() || sink(Delta::Content(text))) && !hit + } + reasoning => sink(reasoning), + } + }; + let mut text = tokens.clone(); + let started = Instant::now(); + let result = self.model.continue_drafted( + &mut text, + max_new, + eos, + drafter, + self.options.guesses, + &mut |scores| sampler.pick(scores), + &mut |token| match reader.push(token) { + Some(delta) => pass_on(delta, &mut content, &mut stopped), + None => true, + }, + ); + let stats = result.map_err(refused)?; + let generation_seconds = started.elapsed().as_secs_f64(); + // What was still held back: half a character, or the possible start of a stop string. + if !stopped { + if let Some(delta) = reader.finish() { + pass_on(delta, &mut content, &mut stopped); + } + let rest = stops.finish(); + if !rest.is_empty() { + content.push_str(&rest); + sink(Delta::Content(rest)); + } + } + + let generated = text.len() - tokens.len(); + let ended = text.last() == Some(&eos); + // The model has been fed everything but the last token chosen. + self.held = text[..text.len() - 1].to_vec(); + let finish = if ended || stopped || generated < max_new { Finish::Stop } else { Finish::Length }; + if ended { + self.served = Some(Served { messages: request.messages.clone(), effort, text, content }); + } + let usage = Usage { + prompt_tokens: tokens.len(), + completion_tokens: generated, + reused_tokens: reused, + sweeps: stats.sweeps, + guessed: stats.drafted, + guessed_right: stats.accepted, + prompt_seconds, + generation_seconds, + }; + Ok((finish, usage)) + } +} diff --git a/crates/dluth-serve/src/http.rs b/crates/dluth-serve/src/http.rs new file mode 100644 index 0000000..51b301c --- /dev/null +++ b/crates/dluth-serve/src/http.rs @@ -0,0 +1,232 @@ +//! Just enough HTTP/1.1: read one request, write one response, close. +//! +//! No keep-alive, no chunked request bodies, no compression. A request's head and body +//! have fixed limits, and whatever does not fit is refused, not buffered. + +use std::io::{self, BufRead, Write}; + +/// The most bytes of request line and headers. +pub const MAX_HEAD: usize = 16 * 1024; +/// The most bytes of body. +pub const MAX_BODY: usize = 16 * 1024 * 1024; + +#[derive(Debug, PartialEq, Eq)] +pub struct Request { + pub method: String, + /// The path without a query string. + pub path: String, + /// Names in lower case. + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) + } +} + +/// Why a request could not be read, as the status to answer with. +#[derive(Debug, PartialEq, Eq)] +pub enum Refusal { + /// 400. + Malformed(&'static str), + /// 411: a body without a stated length. + LengthRequired, + /// 413. + TooLarge(&'static str), + /// The connection ended or failed before a whole request arrived: nothing to answer. + Gone, +} + +impl Refusal { + pub fn status(&self) -> u16 { + match self { + Refusal::Malformed(_) => 400, + Refusal::LengthRequired => 411, + Refusal::TooLarge(_) => 413, + Refusal::Gone => 400, + } + } + + pub fn message(&self) -> &'static str { + match self { + Refusal::Malformed(why) | Refusal::TooLarge(why) => why, + Refusal::LengthRequired => "a request with a body needs a Content-Length", + Refusal::Gone => "the connection ended before the request did", + } + } +} + +/// One line ending in LF (CR before it dropped), or None at the end of the stream. Counts +/// against `left`. +fn line(reader: &mut impl BufRead, left: &mut usize) -> Result, Refusal> { + let mut bytes = Vec::new(); + loop { + let available = reader.fill_buf().map_err(|_| Refusal::Gone)?; + if available.is_empty() { + return if bytes.is_empty() { Ok(None) } else { Err(Refusal::Gone) }; + } + let (take, done) = match available.iter().position(|b| *b == b'\n') { + Some(at) => (at + 1, true), + None => (available.len(), false), + }; + if take > *left { + return Err(Refusal::TooLarge("the request line and headers are too long")); + } + *left -= take; + bytes.extend_from_slice(&available[..take]); + reader.consume(take); + if done { + break; + } + } + bytes.pop(); + if bytes.last() == Some(&b'\r') { + bytes.pop(); + } + String::from_utf8(bytes).map(Some).map_err(|_| Refusal::Malformed("the request head is not UTF-8")) +} + +/// Reads one request. +pub fn read_request(reader: &mut impl BufRead) -> Result { + let mut left = MAX_HEAD; + let first = line(reader, &mut left)?.ok_or(Refusal::Gone)?; + let mut parts = first.split(' '); + let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(Refusal::Malformed("the request line is not `METHOD path HTTP/1.x`")); + }; + if !version.starts_with("HTTP/1.") || method.is_empty() || !target.starts_with('/') { + return Err(Refusal::Malformed("the request line is not `METHOD path HTTP/1.x`")); + } + let path = target.split('?').next().unwrap_or(target).to_string(); + let mut headers = Vec::new(); + loop { + let header = line(reader, &mut left)?.ok_or(Refusal::Gone)?; + if header.is_empty() { + break; + } + let Some((name, value)) = header.split_once(':') else { + return Err(Refusal::Malformed("a header without a colon")); + }; + headers.push((name.trim().to_ascii_lowercase(), value.trim().to_string())); + } + let mut request = Request { method: method.to_string(), path, headers, body: Vec::new() }; + if request.header("transfer-encoding").is_some() { + return Err(Refusal::LengthRequired); + } + let length = match request.header("content-length") { + None if request.method == "POST" || request.method == "PUT" => return Err(Refusal::LengthRequired), + None => 0, + Some(text) => text.parse::().map_err(|_| Refusal::Malformed("Content-Length is not a number"))?, + }; + if length > MAX_BODY { + return Err(Refusal::TooLarge("the request body is too large")); + } + request.body.resize(length, 0); + reader.read_exact(&mut request.body).map_err(|_| Refusal::Gone)?; + Ok(request) +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 400 => "Bad Request", + 401 => "Unauthorized", + 404 => "Not Found", + 405 => "Method Not Allowed", + 411 => "Length Required", + 413 => "Payload Too Large", + 500 => "Internal Server Error", + 503 => "Service Unavailable", + _ => "Status", + } +} + +/// Writes a whole response with a JSON body. +pub fn write_json(w: &mut impl Write, status: u16, body: &str) -> io::Result<()> { + write!( + w, + "HTTP/1.1 {status} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + reason(status), + body.len() + )?; + w.flush() +} + +/// Starts a response that is a stream of server-sent events. It ends when the connection +/// is closed. +pub fn start_events(w: &mut impl Write) -> io::Result<()> { + w.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n", + )?; + w.flush() +} + +/// Writes one event. `data` must not contain a line break (JSON on one line does not). +pub fn write_event(w: &mut impl Write, data: &str) -> io::Result<()> { + debug_assert!(!data.contains('\n')); + write!(w, "data: {data}\n\n")?; + w.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read(text: &str) -> Result { + read_request(&mut text.as_bytes()) + } + + #[test] + fn a_post_with_a_body_is_read_whole() { + let r = read("POST /v1/chat/completions?x=1 HTTP/1.1\r\nHost: a\r\nContent-Length: 7\r\nX-Odd: spaced \r\n\r\n{\"a\":1}extra").unwrap(); + assert_eq!((r.method.as_str(), r.path.as_str()), ("POST", "/v1/chat/completions")); + assert_eq!(r.body, b"{\"a\":1}"); + assert_eq!(r.header("x-odd"), Some("spaced")); + assert_eq!(r.header("host"), Some("a")); + assert_eq!(r.header("missing"), None); + // Bare line feeds are accepted too. + let r = read("GET /health HTTP/1.0\n\n").unwrap(); + assert_eq!((r.method.as_str(), r.path.as_str(), r.body.len()), ("GET", "/health", 0)); + } + + #[test] + fn what_is_not_a_request_is_refused_with_its_status() { + assert_eq!(read(""), Err(Refusal::Gone)); + assert_eq!(read("GET /health HTTP/1.1\r\nHost: a\r\n"), Err(Refusal::Gone)); + assert_eq!(read("POST /x HTTP/1.1\r\nContent-Length: 9\r\n\r\nshort"), Err(Refusal::Gone)); + assert_eq!(read("GET /x\r\n\r\n").unwrap_err().status(), 400); + assert_eq!(read("GET x HTTP/1.1\r\n\r\n").unwrap_err().status(), 400); + assert_eq!(read("GET /x HTTP/2\r\n\r\n").unwrap_err().status(), 400); + assert_eq!(read("GET /x HTTP/1.1\r\nno colon\r\n\r\n").unwrap_err().status(), 400); + assert_eq!(read("POST /x HTTP/1.1\r\nContent-Length: many\r\n\r\n").unwrap_err().status(), 400); + assert_eq!(read("POST /x HTTP/1.1\r\n\r\n"), Err(Refusal::LengthRequired)); + assert_eq!(read("POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"), Err(Refusal::LengthRequired)); + let huge = format!("POST /x HTTP/1.1\r\nContent-Length: {}\r\n\r\n", MAX_BODY + 1); + assert_eq!(read(&huge).unwrap_err().status(), 413); + let long = format!("GET /x HTTP/1.1\r\nA: {}\r\n\r\n", "a".repeat(MAX_HEAD)); + assert_eq!(read(&long).unwrap_err().status(), 413); + // Exactly at the limits is fine. + let head = "GET /x HTTP/1.1\r\nA: "; + let fits = format!("{head}{}\r\n\r\n", "a".repeat(MAX_HEAD - head.len() - 4)); + assert!(read(&fits).is_ok()); + } + + #[test] + fn responses_have_a_length_and_events_a_blank_line() { + let mut out = Vec::new(); + write_json(&mut out, 404, "{\"e\":1}").unwrap(); + assert_eq!( + String::from_utf8(out).unwrap(), + "HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: 7\r\nConnection: close\r\n\r\n{\"e\":1}" + ); + let mut out = Vec::new(); + start_events(&mut out).unwrap(); + write_event(&mut out, "{\"a\":2}").unwrap(); + let text = String::from_utf8(out).unwrap(); + assert!(text.starts_with("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n")); + assert!(text.ends_with("\r\n\r\ndata: {\"a\":2}\n\n")); + } +} diff --git a/crates/dluth-serve/src/lib.rs b/crates/dluth-serve/src/lib.rs new file mode 100644 index 0000000..6595b6a --- /dev/null +++ b/crates/dluth-serve/src/lib.rs @@ -0,0 +1,21 @@ +//! Serves a model over HTTP in the chat-completions format that most clients and routers +//! speak, so that the engine can be called like any other model server. +//! +//! The pieces, from the outside in: +//! +//! - `http`: just enough of HTTP/1.1 to read one request and write one response or a +//! stream of server-sent events. One request per connection. +//! - `api`: the chat-completions request as JSON, and the responses. +//! - `reply`: the model's token stream cut into what it thought and what it said. +//! - `engine`: the model behind a trait, with the conversation it served last kept, so +//! that the next turn of the same conversation is not read again from the start. +//! - `server`: connections are read on their own threads; generation happens on the +//! thread that owns the model, one request at a time. +//! +//! There is one model and one sequence in it at a time. A second request waits its turn. + +pub mod api; +pub mod engine; +pub mod http; +pub mod reply; +pub mod server; diff --git a/crates/dluth-serve/src/reply.rs b/crates/dluth-serve/src/reply.rs new file mode 100644 index 0000000..4c271a4 --- /dev/null +++ b/crates/dluth-serve/src/reply.rs @@ -0,0 +1,212 @@ +//! The model's reply, token by token, cut into what it thought and what it said. +//! +//! A reply is a run of messages. Each opens with the model's role token and a token saying +//! what kind of content follows, and closes with an end-of-message token; after the last +//! one comes the token that ends the turn. Thinking and text are the kinds passed on; any +//! other kind is dropped. + +use dluth_model::tokenizer::Tokenizer; + +/// A piece of a reply, in the order the model produced it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Delta { + Reasoning(String), + Content(String), +} + +/// The ids of the tokens that structure a reply. One a tokenizer does not have is None and +/// never matches. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Markers { + pub message_model: Option, + pub content_text: Option, + pub content_thinking: Option, + pub end_message: Option, + pub end_turn: Option, +} + +impl Markers { + pub fn of(tokenizer: &Tokenizer) -> Self { + Markers { + message_model: tokenizer.token_id("<|message_model|>"), + content_text: tokenizer.token_id("<|content_text|>"), + content_thinking: tokenizer.token_id("<|content_thinking|>"), + end_message: tokenizer.token_id("<|end_message|>"), + end_turn: tokenizer.token_id("<|content_model_end_sampling|>"), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Channel { + /// Between messages. Text here (a reply that does not open a message) is taken as text. + Outside, + /// After the role token, before the kind of content is known. + Header, + Thinking, + Text, +} + +/// Tokens of text held back at most while their bytes end in the middle of a character. +const HELD_TOKENS: usize = 8; + +/// Turns a reply's tokens into pieces of text. +pub struct ReplyReader<'t> { + tokenizer: &'t Tokenizer, + markers: Markers, + channel: Channel, + pending: Vec, +} + +impl<'t> ReplyReader<'t> { + pub fn new(tokenizer: &'t Tokenizer, markers: Markers) -> Self { + ReplyReader { tokenizer, markers, channel: Channel::Outside, pending: Vec::new() } + } + + fn flush(&mut self) -> Option { + if self.pending.is_empty() { + return None; + } + let text = self.tokenizer.decode(&self.pending); + self.pending.clear(); + Some(match self.channel { + Channel::Thinking => Delta::Reasoning(text), + _ => Delta::Content(text), + }) + } + + /// The next token of the reply. Returns the text that is now complete, if any. + pub fn push(&mut self, token: u32) -> Option { + let is = |marker: Option| marker == Some(token); + let m = self.markers; + if is(m.message_model) { + let out = self.flush(); + self.channel = Channel::Header; + return out; + } + if is(m.end_message) || is(m.end_turn) { + let out = self.flush(); + self.channel = Channel::Outside; + return out; + } + if self.channel == Channel::Header { + if is(m.content_text) { + self.channel = Channel::Text; + } else if is(m.content_thinking) { + self.channel = Channel::Thinking; + } + // Anything else in a header (a name, another kind of content) is dropped, and + // so is that message's content: the channel stays Header until it ends. + return None; + } + if is(m.content_text) || is(m.content_thinking) { + // A kind-of-content token outside a header is not text to show. + return None; + } + self.pending.push(token); + // A character can be split across tokens. Hold the tokens back while their bytes + // end in half a character, but not forever: bytes that never become one are shown + // as the replacement character. + let text = self.tokenizer.decode(&self.pending); + if text.ends_with('\u{FFFD}') && self.pending.len() < HELD_TOKENS { + return None; + } + self.flush() + } + + /// The end of the reply: whatever was still held back. + pub fn finish(&mut self) -> Option { + self.flush() + } +} + +/// Watches the text of a reply for strings that end it. Text is passed on a little late: +/// what might still turn out to be the beginning of such a string is held back. +pub struct StopFilter { + stops: Vec, + held: String, + longest: usize, +} + +impl StopFilter { + /// Empty strings are ignored. + pub fn new(stops: &[String]) -> Self { + let stops: Vec = stops.iter().filter(|s| !s.is_empty()).cloned().collect(); + let longest = stops.iter().map(|s| s.len()).max().unwrap_or(0); + StopFilter { stops, held: String::new(), longest } + } + + /// More text. Returns what can be passed on, and whether a stop string was reached (in + /// which case nothing more should be pushed; the stop string itself is not passed on). + pub fn push(&mut self, text: &str) -> (String, bool) { + if self.stops.is_empty() { + return (text.to_string(), false); + } + self.held.push_str(text); + if let Some(at) = self.stops.iter().filter_map(|s| self.held.find(s.as_str())).min() { + let out = self.held[..at].to_string(); + self.held.clear(); + return (out, true); + } + // The last `longest - 1` bytes could be the start of a stop string. + let mut keep_from = self.held.len().saturating_sub(self.longest - 1); + while !self.held.is_char_boundary(keep_from) { + keep_from -= 1; + } + let out = self.held[..keep_from].to_string(); + self.held.drain(..keep_from); + (out, false) + } + + /// The end of the text: what was held back. + pub fn finish(&mut self) -> String { + std::mem::take(&mut self.held) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn filtered(stops: &[&str], pieces: &[&str]) -> (String, bool) { + let stops: Vec = stops.iter().map(|s| s.to_string()).collect(); + let mut filter = StopFilter::new(&stops); + let mut out = String::new(); + for piece in pieces { + let (text, stopped) = filter.push(piece); + out.push_str(&text); + if stopped { + return (out, true); + } + } + out.push_str(&filter.finish()); + (out, false) + } + + #[test] + fn text_passes_unchanged_without_stop_strings_or_matches() { + assert_eq!(filtered(&[], &["ab", "cd"]), ("abcd".into(), false)); + assert_eq!(filtered(&[""], &["ab", "cd"]), ("abcd".into(), false)); + assert_eq!(filtered(&["xyz"], &["ab", "cx", "y", "d"]), ("abcxyd".into(), false)); + // Text that ends in the beginning of a stop string is still passed on at the end. + assert_eq!(filtered(&["END"], &["the EN"]), ("the EN".into(), false)); + } + + #[test] + fn a_stop_string_ends_the_text_before_it_even_across_pieces() { + assert_eq!(filtered(&["END"], &["one EN", "D two"]), ("one ".into(), true)); + assert_eq!(filtered(&["END"], &["END"]), (String::new(), true)); + // The earliest of several. + assert_eq!(filtered(&["two", "one"], &["a one a two"]), ("a ".into(), true)); + // Held-back text never splits a character: é is two bytes. + assert_eq!(filtered(&["STOP"], &["é", "é", "éST", "OPx"]), ("ééé".into(), true)); + } + + #[test] + fn held_back_text_is_only_as_long_as_a_stop_string_could_need() { + let mut filter = StopFilter::new(&["abc".to_string()]); + assert_eq!(filter.push("hello"), ("hel".to_string(), false)); + assert_eq!(filter.push("!"), ("l".to_string(), false)); + assert_eq!(filter.finish(), "o!"); + } +} diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs new file mode 100644 index 0000000..ff18440 --- /dev/null +++ b/crates/dluth-serve/src/server.rs @@ -0,0 +1,245 @@ +//! The server: connections in, one generation at a time. +//! +//! Each connection is read and checked on a thread of its own, so that a slow client, a +//! health check or a bad request never waits for a generation. A chat request that checks +//! out is put in a short queue. The thread that called `serve` owns the model, takes the +//! requests one at a time and writes each reply to its connection as it is produced. +//! When the queue is full, a request is told so at once instead of waiting unseen. + +use crate::api::{self, ChatRequest, Envelope, Usage}; +use crate::engine::{Engine, EngineError}; +use crate::http::{self, Request}; +use crate::reply::Delta; +use serde_json::json; +use std::io::{self, BufReader, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{sync_channel, SyncSender, TrySendError}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +#[derive(Clone, Debug)] +pub struct Config { + /// If set, requests under `/v1/` must carry `Authorization: Bearer `. + pub api_key: Option, + /// Chat requests that may wait for the model. One more is being answered. + pub queue: usize, + /// How long a connection may take to send its request, and to accept each write. + pub patience: Duration, + /// Connections being read at once; more are turned away. + pub connections: usize, +} + +impl Default for Config { + fn default() -> Self { + Config { api_key: None, queue: 8, patience: Duration::from_secs(30), connections: 64 } + } +} + +/// Asks a running `serve` to return: set the flag, then make one connection so that the +/// wait for connections wakes up and sees it. +pub fn stop(addr: SocketAddr, flag: &AtomicBool) { + flag.store(true, Ordering::SeqCst); + let _ = TcpStream::connect(addr); +} + +struct Job { + request: ChatRequest, + stream: TcpStream, +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// Whether two strings are equal, in time that depends only on their lengths. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn refuse(stream: &mut TcpStream, status: u16, message: &str) { + let kind = if status >= 500 { "server_error" } else { "invalid_request_error" }; + let _ = http::write_json(stream, status, &api::error(message, kind)); +} + +/// Reads one connection's request and answers it, or queues it for the model. +fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender) { + let _ = stream.set_read_timeout(Some(config.patience)); + let _ = stream.set_write_timeout(Some(config.patience)); + let request = match http::read_request(&mut BufReader::new(&stream)) { + Ok(request) => request, + Err(http::Refusal::Gone) => return, + Err(refusal) => return refuse(&mut stream, refusal.status(), refusal.message()), + }; + let Request { method, path, .. } = &request; + if path == "/health" || path == "/healthz" { + let _ = http::write_json(&mut stream, 200, &json!({"status": "ok"}).to_string()); + return; + } + let known = path == "/v1/models" || path == "/v1/chat/completions"; + if !known { + return refuse(&mut stream, 404, "there is nothing at this path"); + } + if let Some(key) = &config.api_key { + let given = request.header("authorization").and_then(|h| h.strip_prefix("Bearer ")).unwrap_or(""); + if !same(given, key) { + return refuse(&mut stream, 401, "a valid API key is needed"); + } + } + match (method.as_str(), path.as_str()) { + ("GET", "/v1/models") => { + let _ = http::write_json(&mut stream, 200, &api::models(name, now())); + } + ("POST", "/v1/chat/completions") => match api::parse_chat(&request.body) { + Err(why) => refuse(&mut stream, 400, &why), + Ok(chat) => match jobs.try_send(Job { request: chat, stream }) { + Ok(()) => {} + Err(TrySendError::Full(mut job)) => { + refuse(&mut job.stream, 503, "the model is busy and its queue is full; try again shortly") + } + Err(TrySendError::Disconnected(mut job)) => refuse(&mut job.stream, 503, "the server is stopping"), + }, + }, + _ => refuse(&mut stream, 405, "this path does not take that method"), + } +} + +/// Answers one chat request on its connection. Returns a line for the log. +fn answer(engine: &mut dyn Engine, job: Job, number: u64) -> String { + let Job { request, mut stream } = job; + let envelope = Envelope { + id: format!("chatcmpl-{:x}-{number}", now()), + model: request.model.clone().unwrap_or_else(|| engine.name().to_string()), + created: now(), + }; + let (mut content, mut reasoning) = (String::new(), String::new()); + // A streamed reply's first bytes are written with its first piece, so that a request + // refused before anything was produced can still get an error status. + let mut started = false; + let begin = |stream: &mut TcpStream| -> io::Result<()> { + http::start_events(stream)?; + http::write_event(stream, &api::chunk(&envelope, json!({"role": "assistant", "content": ""}), None)) + }; + let result = engine.chat(&request, &mut |delta| { + if !request.stream { + match delta { + Delta::Content(text) => content.push_str(&text), + Delta::Reasoning(text) => reasoning.push_str(&text), + } + return true; + } + let piece = match delta { + Delta::Content(text) => json!({"content": text}), + Delta::Reasoning(text) => json!({"reasoning_content": text}), + }; + let written = (|| { + if !started { + started = true; + begin(&mut stream)?; + } + http::write_event(&mut stream, &api::chunk(&envelope, piece, None)) + })(); + written.is_ok() + }); + match result { + Err(e) => { + let (status, message) = match &e { + EngineError::Refused(m) => (400, m.as_str()), + EngineError::Failed(m) => (500, m.as_str()), + }; + if started { + let kind = if status == 500 { "server_error" } else { "invalid_request_error" }; + let _ = http::write_event(&mut stream, &api::error(message, kind)); + } else { + refuse(&mut stream, status, message); + } + format!("chat {number}: {status}: {message}") + } + Ok((finish, usage)) => { + let written = if request.stream { + (|| { + if !started { + begin(&mut stream)?; + } + http::write_event(&mut stream, &api::chunk(&envelope, json!({}), Some(finish.name())))?; + if request.include_usage { + http::write_event(&mut stream, &api::usage_chunk(&envelope, &usage))?; + } + stream.write_all(b"data: [DONE]\n\n")?; + stream.flush() + })() + } else { + http::write_json( + &mut stream, + 200, + &api::completion(&envelope, &content, &reasoning, finish.name(), &usage), + ) + }; + log_line(number, &usage, finish.name(), written.is_ok()) + } + } +} + +fn log_line(number: u64, u: &Usage, finish: &str, delivered: bool) -> String { + format!( + "chat {number}: {} prompt tokens ({} held) in {:.2} s; {} new in {:.2} s, {:.1} per second; {} sweeps, {} guessed, {} right; {finish}{}", + u.prompt_tokens, + u.reused_tokens, + u.prompt_seconds, + u.completion_tokens, + u.generation_seconds, + u.completion_tokens as f64 / u.generation_seconds.max(1e-9), + u.sweeps, + u.guessed, + u.guessed_right, + if delivered { "" } else { "; the client had gone" } + ) +} + +/// Serves `engine` on `listener` until `stop_flag` is set (see `stop`). Each finished +/// request is reported to `log` in one line that says nothing of what was asked or +/// answered. +pub fn serve( + listener: TcpListener, + engine: &mut dyn Engine, + config: Config, + stop_flag: Arc, + log: &mut dyn FnMut(&str), +) -> io::Result<()> { + let (jobs, queue) = sync_channel::(config.queue.max(1)); + let name = engine.name().to_string(); + let acceptor = { + let stop_flag = stop_flag.clone(); + let config = config.clone(); + let reading = Arc::new(AtomicUsize::new(0)); + std::thread::Builder::new().name("dluth-accept".into()).spawn(move || { + for connection in listener.incoming() { + if stop_flag.load(Ordering::SeqCst) { + break; + } + let Ok(mut stream) = connection else { continue }; + if reading.load(Ordering::SeqCst) >= config.connections { + refuse(&mut stream, 503, "too many connections; try again shortly"); + continue; + } + reading.fetch_add(1, Ordering::SeqCst); + let (config, name, jobs, done) = (config.clone(), name.clone(), jobs.clone(), reading.clone()); + let spawned = std::thread::Builder::new().name("dluth-read".into()).spawn(move || { + receive(stream, &config, &name, &jobs); + done.fetch_sub(1, Ordering::SeqCst); + }); + if spawned.is_err() { + reading.fetch_sub(1, Ordering::SeqCst); + } + } + // Dropping the last sender here ends the loop below once the readers are done. + })? + }; + let mut number = 0; + while let Ok(job) = queue.recv() { + number += 1; + log(&answer(engine, job, number)); + } + let _ = acceptor.join(); + Ok(()) +} diff --git a/crates/dluth-serve/tests/server.rs b/crates/dluth-serve/tests/server.rs new file mode 100644 index 0000000..9f5fe70 --- /dev/null +++ b/crates/dluth-serve/tests/server.rs @@ -0,0 +1,249 @@ +//! The server over real sockets, with an engine that says what it is told to. + +use dluth_serve::api::{ChatRequest, Usage}; +use dluth_serve::engine::{Engine, EngineError, Finish}; +use dluth_serve::reply::Delta; +use dluth_serve::server::{serve, stop, Config}; +use serde_json::Value; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// Answers by the last message's text: "refuse", "fail", "fail late", "slow", or anything +/// else for a reply of some thinking and two pieces of text. +struct Scripted { + log: Arc>>, +} + +impl Engine for Scripted { + fn name(&self) -> &str { + "scripted" + } + + fn chat( + &mut self, + request: &ChatRequest, + sink: &mut dyn FnMut(Delta) -> bool, + ) -> Result<(Finish, Usage), EngineError> { + let asked = request.messages.last().map(|m| m.content.clone()).unwrap_or_default(); + self.log.lock().unwrap().push(asked.clone()); + match asked.as_str() { + "refuse" => return Err(EngineError::Refused("that is too long".into())), + "fail" => return Err(EngineError::Failed("the device fell over".into())), + "slow" => std::thread::sleep(Duration::from_millis(600)), + _ => {} + } + let mut heard = sink(Delta::Reasoning("thinking ".into())); + if asked == "fail late" { + return Err(EngineError::Failed("the device fell over".into())); + } + for piece in ["Hello", " \"world\"\n"] { + heard = heard && sink(Delta::Content(piece.into())); + } + if !heard { + self.log.lock().unwrap().push("nobody listening".into()); + } + let finish = if request.max_tokens == Some(1) { Finish::Length } else { Finish::Stop }; + Ok((finish, Usage { prompt_tokens: 3, completion_tokens: 2, ..Usage::default() })) + } +} + +struct Running { + addr: SocketAddr, + flag: Arc, + thread: Option>>, + asked: Arc>>, +} + +fn start(config: Config) -> Running { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let flag = Arc::new(AtomicBool::new(false)); + let asked = Arc::new(Mutex::new(Vec::new())); + let (stop_flag, log) = (flag.clone(), asked.clone()); + let thread = std::thread::spawn(move || { + let mut lines = Vec::new(); + serve(listener, &mut Scripted { log }, config, stop_flag, &mut |line| lines.push(line.to_string())).unwrap(); + lines + }); + Running { addr, flag, thread: Some(thread), asked } +} + +impl Running { + /// Stops the server and returns its log lines. + fn finish(mut self) -> Vec { + stop(self.addr, &self.flag); + self.thread.take().unwrap().join().unwrap() + } +} + +/// Sends raw bytes and returns (status, body). +fn send(addr: SocketAddr, raw: &str) -> (u16, String) { + let mut stream = TcpStream::connect(addr).unwrap(); + stream.write_all(raw.as_bytes()).unwrap(); + let mut text = String::new(); + stream.read_to_string(&mut text).unwrap(); + let status = text.split(' ').nth(1).and_then(|s| s.parse().ok()).unwrap_or(0); + let body = text.split_once("\r\n\r\n").map_or(String::new(), |(_, b)| b.to_string()); + (status, body) +} + +fn get(addr: SocketAddr, path: &str) -> (u16, String) { + send(addr, &format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")) +} + +fn post(addr: SocketAddr, body: &str, extra: &str) -> (u16, String) { + let head = + format!("POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\n{extra}Content-Length: {}\r\n\r\n", body.len()); + send(addr, &format!("{head}{body}")) +} + +fn chat(text: &str, more: &str) -> String { + format!(r#"{{"model":"mine","messages":[{{"role":"user","content":"{text}"}}]{more}}}"#) +} + +fn json(body: &str) -> Value { + serde_json::from_str(body).unwrap_or_else(|e| panic!("{e}: {body}")) +} + +#[test] +fn the_small_routes_answer_without_the_model() { + let server = start(Config::default()); + let (status, body) = get(server.addr, "/health"); + assert_eq!((status, json(&body)["status"].as_str()), (200, Some("ok"))); + let (status, body) = get(server.addr, "/v1/models?x=1"); + assert_eq!((status, json(&body)["data"][0]["id"].as_str()), (200, Some("scripted"))); + assert_eq!(get(server.addr, "/nothing").0, 404); + assert_eq!(get(server.addr, "/v1/chat/completions").0, 405); + assert_eq!(send(server.addr, "POST /v1/models HTTP/1.1\r\nContent-Length: 0\r\n\r\n").0, 405); + assert_eq!(send(server.addr, "POST /v1/chat/completions HTTP/1.1\r\n\r\n").0, 411); + assert_eq!(send(server.addr, "nonsense\r\n\r\n").0, 400); + let (status, body) = post(server.addr, "{\"messages\":[]}", ""); + assert_eq!(status, 400); + assert!(json(&body)["error"]["message"].as_str().unwrap().contains("empty")); + // None of that reached the engine, and none of it is a chat in the log. + assert!(server.asked.lock().unwrap().is_empty()); + assert!(server.finish().is_empty()); +} + +#[test] +fn a_reply_comes_whole_or_as_events() { + let server = start(Config::default()); + let (status, body) = post(server.addr, &chat("hi", ""), ""); + let v = json(&body); + assert_eq!(status, 200); + assert_eq!(v["object"], "chat.completion"); + assert_eq!(v["model"], "mine"); + assert_eq!(v["choices"][0]["message"]["content"], "Hello \"world\"\n"); + assert_eq!(v["choices"][0]["message"]["reasoning_content"], "thinking "); + assert_eq!(v["choices"][0]["finish_reason"], "stop"); + assert_eq!(v["usage"]["total_tokens"], 5); + assert_eq!( + json(&post(server.addr, &chat("hi", r#","max_tokens":1"#), "").1)["choices"][0]["finish_reason"], + "length" + ); + + let (status, body) = + post(server.addr, &chat("hi", r#","stream":true,"stream_options":{"include_usage":true}"#), ""); + assert_eq!(status, 200); + let events: Vec<&str> = + body.split("\n\n").filter(|e| !e.is_empty()).map(|e| e.strip_prefix("data: ").unwrap()).collect(); + assert_eq!(events.len(), 7, "{events:?}"); + assert_eq!(*events.last().unwrap(), "[DONE]"); + let parsed: Vec = events[..6].iter().map(|e| json(e)).collect(); + assert_eq!(parsed[0]["choices"][0]["delta"]["role"], "assistant"); + assert_eq!(parsed[1]["choices"][0]["delta"]["reasoning_content"], "thinking "); + assert_eq!(parsed[2]["choices"][0]["delta"]["content"], "Hello"); + assert_eq!(parsed[3]["choices"][0]["delta"]["content"], " \"world\"\n"); + assert_eq!(parsed[4]["choices"][0]["finish_reason"], "stop"); + assert!(parsed[3]["choices"][0]["finish_reason"].is_null()); + assert_eq!(parsed[5]["usage"]["completion_tokens"], 2); + assert!(parsed.iter().all(|p| p["object"] == "chat.completion.chunk" && p["id"] == parsed[0]["id"])); + // Without the option there is no usage event. + let (_, body) = post(server.addr, &chat("hi", r#","stream":true"#), ""); + assert_eq!(body.matches("data: ").count(), 6); + assert!(!body.contains("\"usage\"")); + + let lines = server.finish(); + assert_eq!(lines.len(), 4); + assert!(lines[0].starts_with("chat 1: 3 prompt tokens") && lines[0].ends_with("stop"), "{}", lines[0]); + // The log says how much, never what. + assert!(lines.iter().all(|l| !l.contains("Hello") && !l.contains("hi"))); +} + +#[test] +fn failures_get_a_status_while_one_can_still_be_sent() { + let server = start(Config::default()); + for stream in ["", r#","stream":true"#] { + let (status, body) = post(server.addr, &chat("refuse", stream), ""); + assert_eq!((status, json(&body)["error"]["message"].as_str()), (400, Some("that is too long"))); + assert_eq!(json(&body)["error"]["type"], "invalid_request_error"); + let (status, body) = post(server.addr, &chat("fail", stream), ""); + assert_eq!((status, json(&body)["error"]["type"].as_str()), (500, Some("server_error"))); + } + // After the first piece of a streamed reply the status is sent: the error is an event. + let (status, body) = post(server.addr, &chat("fail late", r#","stream":true"#), ""); + assert_eq!(status, 200); + let last = body.split("\n\n").filter(|e| !e.is_empty()).last().unwrap(); + assert_eq!(json(last.strip_prefix("data: ").unwrap())["error"]["message"], "the device fell over"); + assert!(!body.contains("[DONE]")); + // Not streamed, the same failure is a plain 500. + assert_eq!(post(server.addr, &chat("fail late", ""), "").0, 500); + let lines = server.finish(); + assert!(lines[0].contains("400") && lines[1].contains("500"), "{lines:?}"); +} + +#[test] +fn a_key_is_asked_for_when_one_is_set() { + let server = start(Config { api_key: Some("s3cret-key".into()), ..Config::default() }); + assert_eq!(get(server.addr, "/health").0, 200); + assert_eq!(get(server.addr, "/v1/models").0, 401); + assert_eq!(post(server.addr, &chat("hi", ""), "").0, 401); + assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: Bearer s3cret-kez\r\n").0, 401); + assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: Bearer s3cret-key-and-more\r\n").0, 401); + assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: s3cret-key\r\n").0, 401); + assert_eq!(post(server.addr, &chat("hi", ""), "authorization: Bearer s3cret-key\r\n").0, 200); + assert_eq!(send(server.addr, "GET /v1/models HTTP/1.1\r\nAuthorization: Bearer s3cret-key\r\n\r\n").0, 200); + assert_eq!(*server.asked.lock().unwrap(), ["hi"]); + server.finish(); +} + +#[test] +fn requests_wait_their_turn_and_a_full_queue_says_so() { + let server = start(Config { queue: 1, ..Config::default() }); + let addr = server.addr; + let slow = |name: &'static str| std::thread::spawn(move || post(addr, &chat(name, ""), "")); + // The first is being answered (it takes 0.6 s), the second waits in the queue of one. + let first = slow("slow"); + std::thread::sleep(Duration::from_millis(150)); + let second = slow("second"); + std::thread::sleep(Duration::from_millis(150)); + // The third finds the queue full, and is told at once; the small routes still answer. + let started = std::time::Instant::now(); + let (status, body) = post(addr, &chat("third", ""), ""); + assert_eq!(status, 503); + assert!(json(&body)["error"]["message"].as_str().unwrap().contains("busy")); + assert_eq!(get(addr, "/health").0, 200); + assert!(started.elapsed() < Duration::from_millis(250), "the refusal waited for the model"); + assert_eq!(first.join().unwrap().0, 200); + assert_eq!(second.join().unwrap().0, 200); + assert_eq!(*server.asked.lock().unwrap(), ["slow", "second"]); + server.finish(); +} + +#[test] +fn a_client_that_leaves_ends_its_reply_and_the_next_is_served() { + let server = start(Config::default()); + // Ask for a slow streamed reply and hang up before it starts. + let body = chat("slow", r#","stream":true"#); + let mut stream = TcpStream::connect(server.addr).unwrap(); + write!(stream, "POST /v1/chat/completions HTTP/1.1\r\nContent-Length: {}\r\n\r\n{body}", body.len()).unwrap(); + std::thread::sleep(Duration::from_millis(100)); + drop(stream); + assert_eq!(post(server.addr, &chat("hi", ""), "").0, 200); + let lines = server.finish(); + assert_eq!(lines.len(), 2); + assert!(lines[1].ends_with("stop"), "{}", lines[1]); +} From 139b2c0215c81d0b308605ab8fb620a53d7b96a4 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:43 -0800 Subject: [PATCH 03/14] test(serve): the engine against the model used directly --- crates/dluth-serve/tests/engine.rs | 231 +++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 crates/dluth-serve/tests/engine.rs diff --git a/crates/dluth-serve/tests/engine.rs b/crates/dluth-serve/tests/engine.rs new file mode 100644 index 0000000..7347e98 --- /dev/null +++ b/crates/dluth-serve/tests/engine.rs @@ -0,0 +1,231 @@ +//! The engine with the tiny model on the CPU: what it hands out is what the model, used +//! directly, produces for the same tokens; and a conversation that goes on is not read again. + +use dluth_model::inkling::prompt::{chat, more_turns, Effort, Message, Role}; +use dluth_model::inkling::sample::{Sampler, Sampling}; +use dluth_model::inkling::{load_config, InklingCpu, NoDraft}; +use dluth_model::tokenizer::Tokenizer; +use dluth_model::weights::Weights; +use dluth_serve::api::ChatRequest; +use dluth_serve::engine::{Engine, EngineError, Finish, InklingEngine, Options}; +use dluth_serve::reply::{Delta, Markers, ReplyReader}; +use std::path::{Path, PathBuf}; + +fn tiny() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling") +} + +fn user(text: &str) -> Message { + Message { role: Role::User, content: text.into(), reasoning: None } +} + +fn request(messages: Vec, max_tokens: usize, temperature: f32, seed: u64) -> ChatRequest { + ChatRequest { + model: None, + messages, + max_tokens: Some(max_tokens), + temperature: Some(temperature), + top_p: None, + seed: Some(seed), + stop: Vec::new(), + stream: false, + include_usage: false, + effort: Some(Effort::None), + } +} + +/// What the model produces for `prompt` used directly, without guesses: the new tokens and +/// the text a reply reader makes of them. +fn direct( + model: &mut InklingCpu, + tokenizer: &Tokenizer, + prompt: &[u32], + max_new: usize, + sampling: Sampling, +) -> (Vec, String) { + let mut pos = 0; + for batch in prompt.chunks(5) { + model.feed(batch, pos).unwrap(); + pos += batch.len(); + } + let mut text = prompt.to_vec(); + let mut sampler = Sampler::new(sampling); + let eos = model.config().eos; + model.continue_drafted(&mut text, max_new, eos, &mut NoDraft, 0, &mut |s| sampler.pick(s), &mut |_| true).unwrap(); + let new = text.split_off(prompt.len()); + let mut reader = ReplyReader::new(tokenizer, Markers::of(tokenizer)); + let mut out = String::new(); + let mut deltas: Vec = new.iter().filter_map(|t| reader.push(*t)).collect(); + deltas.extend(reader.finish()); + for delta in deltas { + match delta { + Delta::Content(t) | Delta::Reasoning(t) => out.push_str(&t), + } + } + (new, out) +} + +fn ask(engine: &mut dyn Engine, request: &ChatRequest) -> (String, Finish, dluth_serve::api::Usage) { + let mut out = String::new(); + let (finish, usage) = engine + .chat(request, &mut |delta| { + match delta { + Delta::Content(t) | Delta::Reasoning(t) => out.push_str(&t), + } + true + }) + .unwrap(); + (out, finish, usage) +} + +#[test] +fn the_engine_hands_out_what_the_model_produces() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).unwrap(); + let model = || InklingCpu::new(load_config(&dir).unwrap(), &weights, 256).unwrap(); + let mut plain = model(); + let messages = + vec![Message { role: Role::System, content: "be brief".into(), reasoning: None }, user("hello there")]; + let prompt = tokenizer.encode(&chat(&messages, Effort::None)).unwrap(); + + for (temperature, seed) in [(0.0, 0), (1.0, 11), (0.7, 12)] { + let sampling = Sampling { temperature, top_p: 1.0, seed }; + let (new, want) = direct(&mut plain, &tokenizer, &prompt, 40, sampling); + // With guesses and without, in prompt batches of 16 and of 3: the same reply. + for (guesses, prompt_batch) in [(0, 16), (4, 16), (15, 3)] { + let options = Options { guesses, prompt_batch, match_run: 1, ..Options::default() }; + let mut engine = InklingEngine::new(model(), &tokenizer, options); + let (got, finish, usage) = ask(&mut engine, &request(messages.clone(), 40, temperature, seed)); + assert_eq!(got, want, "temperature {temperature}, {guesses} guesses"); + assert_eq!( + (usage.prompt_tokens, usage.completion_tokens, usage.reused_tokens), + (prompt.len(), new.len(), 0) + ); + let ended = new.last() == Some(&plain.config().eos); + assert_eq!(finish, if ended { Finish::Stop } else { Finish::Length }); + assert_eq!(usage.sweeps + usage.guessed_right + 1, new.len()); + if guesses == 0 { + assert_eq!(usage.guessed, 0); + } + } + } + // Different seeds draw different replies. + let (a, _) = direct(&mut plain, &tokenizer, &prompt, 40, Sampling { temperature: 1.0, top_p: 1.0, seed: 1 }); + let (b, _) = direct(&mut plain, &tokenizer, &prompt, 40, Sampling { temperature: 1.0, top_p: 1.0, seed: 2 }); + assert_ne!(a, b); +} + +#[test] +fn a_conversation_that_goes_on_is_not_read_again() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).unwrap(); + let model = || InklingCpu::new(load_config(&dir).unwrap(), &weights, 256).unwrap(); + let mut plain = model(); + let eos = plain.config().eos; + let first = vec![user("hello there")]; + let prompt = tokenizer.encode(&chat(&first, Effort::None)).unwrap(); + // The tiny model's weights are random, so whether a reply ends is luck: take the first + // seed whose reply ends within 60 tokens. + let (seed, reply_tokens, reply) = (0..400u64) + .find_map(|seed| { + let sampling = Sampling { temperature: 1.0, top_p: 1.0, seed }; + let (new, text) = direct(&mut plain, &tokenizer, &prompt, 60, sampling); + (new.last() == Some(&eos) && new.len() > 3).then_some((seed, new, text)) + }) + .expect("a reply that ends"); + + let mut engine = InklingEngine::new(model(), &tokenizer, Options::default()); + let (got, finish, usage) = ask(&mut engine, &request(first.clone(), 60, 1.0, seed)); + assert_eq!((got.as_str(), finish, usage.reused_tokens), (reply.as_str(), Finish::Stop, 0)); + + // The client sends the conversation back with the reply it was given and a new message. + let mut longer = first.clone(); + longer.push(Message { role: Role::Assistant, content: reply.clone(), reasoning: None }); + longer.push(user("and then?")); + let (got, _, usage) = ask(&mut engine, &request(longer.clone(), 20, 0.0, 0)); + // The model held everything but the reply's last token; only that and the new turn were fed. + let held = prompt.len() + reply_tokens.len() - 1; + let more = tokenizer.encode(&more_turns(&longer[2..])).unwrap(); + assert_eq!((usage.reused_tokens, usage.prompt_tokens), (held, held + 1 + more.len())); + // And the answer is what the model gives for exactly those tokens read from the start. + let mut whole = prompt.clone(); + whole.extend(&reply_tokens); + whole.extend(&more); + let (_, want) = direct(&mut plain, &tokenizer, &whole, 20, Sampling::greedy()); + assert_eq!(got, want); + + // A conversation that does not continue the last one is read from its first token: + // another reply than the one given, another first message, another effort. + let mut other_reply = longer.clone(); + other_reply[1].content.push_str(" (edited)"); + let mut other_start = longer.clone(); + other_start[0].content = "hello here".into(); + let mut other_effort = request(longer.clone(), 5, 0.0, 0); + other_effort.effort = Some(Effort::High); + for (what, request) in [ + ("an edited reply", request(other_reply, 5, 0.0, 0)), + ("another first message", request(other_start, 5, 0.0, 0)), + ("another effort", other_effort), + ("the first conversation again", request(first.clone(), 5, 0.0, 0)), + ] { + // Each time, make the engine hold the finished conversation first. + let mut engine = InklingEngine::new(model(), &tokenizer, Options::default()); + ask(&mut engine, &self::request(first.clone(), 60, 1.0, seed)); + let (got, _, usage) = ask(&mut engine, &request); + assert_eq!(usage.reused_tokens, 0, "{what}"); + let effort = request.effort.unwrap(); + let tokens = tokenizer.encode(&chat(&request.messages, effort)).unwrap(); + assert_eq!(got, direct(&mut plain, &tokenizer, &tokens, 5, Sampling::greedy()).1, "{what}"); + } +} + +#[test] +fn stop_strings_limits_and_refusals() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).unwrap(); + let mut plain = InklingCpu::new(load_config(&dir).unwrap(), &weights, 128).unwrap(); + let model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 128).unwrap(); + let mut engine = InklingEngine::new(model, &tokenizer, Options::default()); + let messages = vec![user("hello there")]; + let prompt = tokenizer.encode(&chat(&messages, Effort::None)).unwrap(); + let (_, whole) = direct(&mut plain, &tokenizer, &prompt, 30, Sampling::greedy()); + assert!(whole.chars().count() > 6, "the reply is long enough to cut: {whole:?}"); + + // A stop string from the middle of the reply ends it there, and it counts as a stop. + let cut: String = whole.chars().skip(3).take(2).collect(); + let before = &whole[..whole.find(&cut).unwrap()]; + let mut stopping = request(messages.clone(), 30, 0.0, 0); + stopping.stop = vec!["never appears".into(), cut]; + let (got, finish, usage) = ask(&mut engine, &stopping); + assert_eq!((got.as_str(), finish), (before, Finish::Stop)); + assert!(usage.completion_tokens < 30); + + // The limit on new tokens, and the room left in the context when none is given. + let (_, finish, usage) = ask(&mut engine, &request(messages.clone(), 4, 0.0, 0)); + assert_eq!((finish, usage.completion_tokens), (Finish::Length, 4)); + let mut unlimited = request(messages.clone(), 0, 0.0, 0); + unlimited.max_tokens = None; + let (_, _, usage) = ask(&mut engine, &unlimited); + assert!(usage.completion_tokens <= 128 - prompt.len()); + + // A listener that leaves ends the reply early. + let mut pieces = 0; + let (_, usage) = engine + .chat(&request(messages.clone(), 30, 0.0, 0), &mut |_| { + pieces += 1; + pieces < 3 + }) + .unwrap(); + assert!(pieces == 3 && usage.completion_tokens < 30, "{pieces} pieces, {usage:?}"); + + // What does not fit, or asks for nothing, is refused, and the engine goes on working. + let long = request(vec![user(&"word ".repeat(80))], 5, 0.0, 0); + assert!(matches!(engine.chat(&long, &mut |_| true), Err(EngineError::Refused(m)) if m.contains("context"))); + let none = request(messages.clone(), 0, 0.0, 0); + assert!(matches!(engine.chat(&none, &mut |_| true), Err(EngineError::Refused(_)))); + let (got, _, _) = ask(&mut engine, &request(messages, 30, 0.0, 0)); + assert_eq!(got, whole); +} From 1f7969d6143f99b8782f232aaf804e21e3e20331 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:23:43 -0800 Subject: [PATCH 04/14] feat(cli): dluth serve --- Cargo.lock | 1 + crates/dluth-serve/src/cli.rs | 139 +++++++++++++++++++++++++++++++ crates/dluth-serve/src/engine.rs | 2 +- crates/dluth-serve/src/lib.rs | 2 + crates/dluth/Cargo.toml | 2 + crates/dluth/src/main.rs | 19 ++++- 6 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 crates/dluth-serve/src/cli.rs diff --git a/Cargo.lock b/Cargo.lock index 1db2072..5b19a41 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -108,6 +108,7 @@ name = "dluth" version = "0.0.0" dependencies = [ "dluth-model", + "dluth-serve", ] [[package]] diff --git a/crates/dluth-serve/src/cli.rs b/crates/dluth-serve/src/cli.rs new file mode 100644 index 0000000..301d544 --- /dev/null +++ b/crates/dluth-serve/src/cli.rs @@ -0,0 +1,139 @@ +//! What the programs that serve a model share: their arguments, and the run itself. + +use crate::engine::{InklingEngine, Options}; +use crate::server::{serve, Config}; +use dluth_model::inkling::prompt::Effort; +use dluth_model::inkling::{Inkling, Ops}; +use dluth_model::tokenizer::Tokenizer; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; + +pub const USAGE: &str = "serve --model [--listen ] [--context ] \ +[--name ] [--guesses ] [--match ] [--prompt-batch ] \ +[--temperature ] [--effort ] [--queue ]"; + +/// The environment variable that, when set, is the key clients must send. +pub const KEY_VARIABLE: &str = "DLUTH_API_KEY"; + +#[derive(Clone, Debug, PartialEq)] +pub struct ServeArgs { + pub model: PathBuf, + /// Only this machine unless told otherwise. + pub listen: String, + /// The longest conversation, in tokens, prompt and reply together. + pub context: usize, + pub queue: usize, + pub options: Options, +} + +/// Reads the arguments after `serve`. The error is a sentence for the person who typed them. +pub fn parse(args: &[String]) -> Result { + let mut out = ServeArgs { + model: PathBuf::new(), + listen: "127.0.0.1:8080".into(), + context: 8192, + queue: Config::default().queue, + options: Options::default(), + }; + let mut name = None; + let mut it = args.iter(); + while let Some(flag) = it.next() { + let value = it.next().ok_or_else(|| format!("{flag} needs a value; {USAGE}"))?; + let count = |least: usize| -> Result { + value + .parse::() + .ok() + .filter(|n| *n >= least) + .ok_or_else(|| format!("{flag} {value}: a number of at least {least} is needed")) + }; + match flag.as_str() { + "--model" => out.model = PathBuf::from(value), + "--listen" => out.listen = value.clone(), + "--context" => out.context = count(2)?, + "--name" => name = Some(value.clone()), + "--guesses" => out.options.guesses = count(0)?, + "--match" => out.options.match_run = count(1)?, + "--prompt-batch" => out.options.prompt_batch = count(1)?, + "--queue" => out.queue = count(1)?, + "--temperature" => { + out.options.temperature = value + .parse::() + .ok() + .filter(|t| t.is_finite() && *t >= 0.0) + .ok_or_else(|| format!("--temperature {value}: a number of at least 0 is needed"))? + } + "--effort" => out.options.effort = Effort::parse(value).map_err(|e| e.to_string())?, + other => return Err(format!("unknown argument {other}; {USAGE}")), + } + } + if out.model.as_os_str().is_empty() { + return Err(format!("--model is needed; {USAGE}")); + } + // Listed under the directory's name unless told otherwise. + out.options.name = name + .or_else(|| out.model.file_name().map(|n| n.to_string_lossy().into_owned())) + .unwrap_or_else(|| "dluth".into()); + Ok(out) +} + +/// Serves `model` until the process ends. Prints where it listens and one line per request +/// to standard error; never a key, a prompt or a reply. +pub fn run(model: Inkling<'_, O>, tokenizer: &Tokenizer, args: &ServeArgs) -> Result<(), String> { + let listener = TcpListener::bind(&args.listen).map_err(|e| format!("cannot listen on {}: {e}", args.listen))?; + let address = listener.local_addr().map_err(|e| e.to_string())?; + let api_key = std::env::var(KEY_VARIABLE).ok().filter(|k| !k.is_empty()); + eprintln!( + "serving {} on http://{address}/v1 (context {} tokens, {} guesses per sweep, {})", + args.options.name, + model.capacity(), + args.options.guesses, + if api_key.is_some() { "a key is required" } else { "no key is required" } + ); + let mut engine = InklingEngine::new(model, tokenizer, args.options.clone()); + let config = Config { api_key, queue: args.queue, ..Config::default() }; + serve(listener, &mut engine, config, Arc::new(AtomicBool::new(false)), &mut |line| eprintln!("{line}")) + .map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(text: &str) -> Vec { + text.split_whitespace().map(str::to_string).collect() + } + + #[test] + fn arguments_are_read_and_the_rest_defaults() { + let a = parse(&args("--model /models/Inkling-2-Mini")).unwrap(); + assert_eq!((a.listen.as_str(), a.context, a.options.name.as_str()), ("127.0.0.1:8080", 8192, "Inkling-2-Mini")); + assert_eq!((a.options.guesses, a.options.match_run, a.options.prompt_batch), (4, 2, 16)); + let a = parse(&args( + "--listen 0.0.0.0:9000 --model m --context 4096 --name mine --guesses 0 --match 3 --prompt-batch 8 \ + --temperature 0 --effort low --queue 2", + )) + .unwrap(); + assert_eq!((a.listen.as_str(), a.context, a.queue, a.options.name.as_str()), ("0.0.0.0:9000", 4096, 2, "mine")); + assert_eq!((a.options.guesses, a.options.match_run, a.options.prompt_batch), (0, 3, 8)); + assert_eq!((a.options.temperature, a.options.effort), (0.0, Effort::Low)); + } + + #[test] + fn bad_arguments_are_refused_in_words() { + for (text, word) in [ + ("", "--model is needed"), + ("--model", "needs a value"), + ("--model m --context 1", "at least 2"), + ("--model m --context many", "--context many"), + ("--model m --match 0", "at least 1"), + ("--model m --temperature -1", "--temperature -1"), + ("--model m --effort extreme", "extreme"), + ("--model m --port 80", "unknown argument --port"), + ] { + let e = parse(&args(text)).unwrap_err(); + assert!(e.contains(word), "{text}: {e}"); + } + } +} diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs index 485f61a..e6fff2e 100644 --- a/crates/dluth-serve/src/engine.rs +++ b/crates/dluth-serve/src/engine.rs @@ -56,7 +56,7 @@ pub trait Engine { } /// How the engine generates. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct Options { /// The name the model is listed under. pub name: String, diff --git a/crates/dluth-serve/src/lib.rs b/crates/dluth-serve/src/lib.rs index 6595b6a..98c6770 100644 --- a/crates/dluth-serve/src/lib.rs +++ b/crates/dluth-serve/src/lib.rs @@ -11,10 +11,12 @@ //! that the next turn of the same conversation is not read again from the start. //! - `server`: connections are read on their own threads; generation happens on the //! thread that owns the model, one request at a time. +//! - `cli`: the arguments and the run that the serving programs share. //! //! There is one model and one sequence in it at a time. A second request waits its turn. pub mod api; +pub mod cli; pub mod engine; pub mod http; pub mod reply; diff --git a/crates/dluth/Cargo.toml b/crates/dluth/Cargo.toml index 4f6da0c..f1f7da6 100644 --- a/crates/dluth/Cargo.toml +++ b/crates/dluth/Cargo.toml @@ -14,3 +14,5 @@ workspace = true [dependencies] # Model loading, the tokenizer and the forward pass; the program is a thin wrapper over it. dluth-model = { version = "0.0.0", path = "../dluth-model" } +# The chat-completions server behind `dluth serve`. +dluth-serve = { version = "0.0.0", path = "../dluth-serve" } diff --git a/crates/dluth/src/main.rs b/crates/dluth/src/main.rs index 8ba25cb..d979a2a 100644 --- a/crates/dluth/src/main.rs +++ b/crates/dluth/src/main.rs @@ -12,8 +12,7 @@ use std::path::PathBuf; use std::process::ExitCode; use std::time::Instant; -const USAGE: &str = - "usage: dluth generate --model --prompt [--max-new ] [--max-seq ] [--effort ]"; +const USAGE: &str = "usage: dluth generate --model --prompt [--max-new ] [--max-seq ] [--effort ]\n dluth serve --model [--listen ] [--context ] (see the README for the rest)"; /// Why a run ended without doing its job. The two kinds map to different exit statuses. enum Failure { @@ -169,6 +168,21 @@ fn generate(args: GenerateArgs) -> Result<(), Failure> { Ok(()) } +/// Serves an Inkling model on the CPU in the chat-completions format. The CPU model is the +/// slow reference; the program in the CUDA crate serves the same way from a GPU. +fn serve(args: &[String]) -> Result<(), Failure> { + let refused = |e: ModelError| Failure::Refused(e.to_string()); + let args = dluth_serve::cli::parse(args).map_err(Failure::Refused)?; + if inkling::model_kind(&args.model).map_err(refused)? != ModelKind::Inkling2Loop { + return Err(Failure::Refused("serve takes an Inkling 2 model".into())); + } + let weights = Weights::open_dir(&args.model).map_err(refused)?; + let tokenizer = Tokenizer::from_file(&args.model.join("tokenizer.json")).map_err(refused)?; + let cfg = inkling::load_config(&args.model).map_err(refused)?; + let model = InklingCpu::new(cfg, &weights, args.context).map_err(refused)?; + dluth_serve::cli::run(model, &tokenizer, &args).map_err(Failure::Failed) +} + fn run(args: &[String]) -> Result<(), Failure> { match args.first().map(String::as_str) { None => Err(Failure::Refused(USAGE.into())), @@ -181,6 +195,7 @@ fn run(args: &[String]) -> Result<(), Failure> { Ok(()) } Some("generate") => generate(parse_generate(&args[1..]).map_err(Failure::Refused)?), + Some("serve") => serve(&args[1..]), Some(other) => Err(Failure::Refused(format!("unknown command {other}; {USAGE}"))), } } From 47bdf90ea503f59af56e3bca94a373772514cca1 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:26:24 -0800 Subject: [PATCH 05/14] feat(cuda): dluth-cuda serve, the chat-completions server from the GPU --- crates/dluth-cuda/Cargo.toml | 2 + crates/dluth-cuda/src/bin/dluth-cuda.rs | 57 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 crates/dluth-cuda/src/bin/dluth-cuda.rs diff --git a/crates/dluth-cuda/Cargo.toml b/crates/dluth-cuda/Cargo.toml index 1836d40..472acd4 100644 --- a/crates/dluth-cuda/Cargo.toml +++ b/crates/dluth-cuda/Cargo.toml @@ -19,6 +19,8 @@ dluth-model = { version = "0.0.0", path = "../dluth-model" } # The CPU reference every GPU kernel is compared with in tests; the device model also uses # its expert choice and the few scalar formulas that stay on the host. dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" } +# The chat-completions server, for the program that serves a model from the GPU. +dluth-serve = { version = "0.0.0", path = "../dluth-serve" } [dev-dependencies] # Reads the recorded runs of the reference implementation that the golden tests compare with. diff --git a/crates/dluth-cuda/src/bin/dluth-cuda.rs b/crates/dluth-cuda/src/bin/dluth-cuda.rs new file mode 100644 index 0000000..81d463f --- /dev/null +++ b/crates/dluth-cuda/src/bin/dluth-cuda.rs @@ -0,0 +1,57 @@ +//! Serves an Inkling 2 model from a CUDA device in the chat-completions format. +//! +//! dluth-cuda serve --model [--listen ] [--context ] ... +//! +//! The arguments are those of `dluth serve`. Before it listens, the program runs one token +//! through the model, which copies every layer's weights to the device, so that the first +//! request does not pay for that. + +use dluth_cuda::ops::CudaOps; +use dluth_cuda::{CudaDevice, Module}; +use dluth_model::inkling::{load_config, model_kind, Inkling, ModelKind}; +use dluth_model::tokenizer::Tokenizer; +use dluth_model::weights::Weights; +use dluth_serve::cli; +use std::process::ExitCode; +use std::time::Instant; + +fn run(args: &[String]) -> Result<(), String> { + if args.first().map(String::as_str) != Some("serve") { + return Err(format!("usage: dluth-cuda {}", cli::USAGE)); + } + let args = cli::parse(&args[1..])?; + let text = |e: &dyn std::fmt::Display| e.to_string(); + if model_kind(&args.model).map_err(|e| text(&e))? != ModelKind::Inkling2Loop { + return Err("serve takes an Inkling 2 model".into()); + } + let weights = Weights::open_dir(&args.model).map_err(|e| text(&e))?; + let tokenizer = Tokenizer::from_file(&args.model.join("tokenizer.json")).map_err(|e| text(&e))?; + let cfg = load_config(&args.model).map_err(|e| text(&e))?; + let dev = CudaDevice::open(0).map_err(|e| text(&e))?; + let module = Module::load_embedded(&dev).map_err(|e| text(&e))?; + let ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?; + let mut model = Inkling::with_ops(cfg, &weights, args.context, ops).map_err(|e| text(&e))?; + + // Any token will do: each layer's weights go to the device the first time the layer runs. + let started = Instant::now(); + model.forward_token(0, 0).map_err(|e| text(&e))?; + eprintln!( + "{:.1} GB of weights on the device after {:.0} s", + model.ops().weight_bytes() as f64 / 1e9, + started.elapsed().as_secs_f64() + ); + cli::run(model, &tokenizer, &args) +} + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + match run(&args) { + Ok(()) => ExitCode::SUCCESS, + Err(message) => { + // One line whatever the message quotes. + let line: String = message.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + eprintln!("dluth-cuda: {line}"); + ExitCode::from(1) + } + } +} From 07369bd7a04b59a11d9832bf3bac55076c635c5b Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:26:47 -0800 Subject: [PATCH 06/14] docs: the README says what runs where, and how to serve --- README.md | 61 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4667097..9fe286f 100644 --- a/README.md +++ b/README.md @@ -7,24 +7,64 @@ A lean, from-scratch LLM inference engine in Rust. Planned targets: Apple Silico GB10 and B200. The engine contains no Python and does no just-in-time compilation; kernels are compiled ahead of time. -Status: early. Two models run on the CPU, slowly, each checked against a trusted reference implementation as -described below. Not usable yet. +Status: early, and usable for one model on one machine. Inkling 2 Mini runs on an NVIDIA GB10 with every +value of the forward pass on the GPU, and can be served in the chat-completions format. Two models run on the +CPU, slowly, as the reference each faster path is checked against. -- **Qwen3-8B** (dense). Its output matches the reference token for token. +- **Qwen3-8B** (dense), CPU only. Its output matches the reference implementation token for token. - **Inkling 2 Mini** (text input only, no images): a looped mixture-of-experts model with 4-bit and 8-bit - weights, run straight from the released checkpoint. Against the reference run in 32-bit floats it picks - the same token at every recorded step, and every recorded log-probability is within four times the - reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny model of the same - architecture, small enough to exercise every rule, is checked the same way in CI. + weights, run straight from the released checkpoint, on the CPU and on the GB10. Against the reference run + in 32-bit floats, both pick the same token at every recorded step, and every recorded log-probability is + within four times the reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny + model of the same architecture, small enough to exercise every rule, is checked the same way in CI. -Deliberately planted bugs must make named tests fail, for both models. One trivial kernel runs on an NVIDIA -GB10 to prove the GPU path. Speed is the next work. +On the GB10, Inkling 2 Mini generates about 24 tokens per second one token at a time and reads a prompt at +about 120 tokens per second. Guessed tokens are checked several per sweep of the weights, which speeds up +text that repeats itself; the model's own draft head is not used yet. Deliberately planted bugs must make +named tests fail, on the CPU and on the GPU. cargo run --release -- generate --model --prompt "What is the capital of Ireland?" The program reads the model type from the directory's `config.json`. For Inkling, `--effort` sets the reasoning effort (none, minimal, low, medium, high, xhigh; the default is high). +## Serve + + cargo run --release -p dluth-cuda --bin dluth-cuda -- serve --model + +serves an Inkling 2 model from the GPU at `http://127.0.0.1:8080/v1` (`dluth serve` does the same on the +CPU, which is only good for trying the interface). It answers `POST /v1/chat/completions`, streamed or whole, +`GET /v1/models` and `GET /health`. + +| Argument | Meaning | Default | +|---|---|---| +| `--listen ` | where to listen; `0.0.0.0:8080` for other machines | `127.0.0.1:8080` | +| `--context ` | longest conversation, prompt and reply together | 8192 | +| `--name ` | the name the model is listed under | the directory's name | +| `--guesses ` | guessed tokens checked per sweep; 0 for none | 4 | +| `--match ` | last tokens that must have appeared before for a guess | 2 | +| `--temperature ` | used when a request does not set one; 0 is greedy | 1 | +| `--effort ` | reasoning effort when a request does not set `reasoning_effort` | high | +| `--queue ` | requests that may wait for the model | 8 | + +If the environment variable `DLUTH_API_KEY` is set, requests under `/v1/` must send it as a bearer token. + +What to know before relying on it: + +- One model, one conversation at a time. Requests are answered in turn; when the queue is full a request + gets a 503 at once. +- From a request it reads `messages` (text; system, user and assistant), `max_completion_tokens` or + `max_tokens`, `temperature`, `top_p`, `seed`, `stop`, `stream`, `stream_options.include_usage` and + `reasoning_effort`. Tools, images and `n` above 1 are refused with a 400, not ignored. +- The model's thinking comes back as `reasoning_content`, apart from `content`. +- The server keeps the conversation it answered last. A request that continues it (the same messages, the + reply as it was given, then more) only reads the new messages; `usage.prompt_tokens_details.cached_tokens` + says how many tokens were not read again. +- Message text is put into the model's chat format as it is. Text that contains the model's special token + strings is read as those tokens, as with the model's own template. Do not expose the server to people + you would not let write the whole prompt. +- It speaks plain HTTP. Put it behind something that does TLS if it leaves a trusted network. + ## Build cargo build --release @@ -38,8 +78,7 @@ toolkit (found through `CUDA_HOME`, default `/usr/local/cuda`) and libclang: cargo test -p dluth-cuda Its kernels are compiled for one GPU architecture, currently `sm_121` (the GB10). Loading the built-in -kernels checks the device first and refuses any other architecture. In M0 it holds a single kernel that proves the path from source to a launched kernel; the model -itself still runs on the CPU. +kernels checks the device first and refuses any other architecture. Design notes written for readers new to inference engines are in `docs/learning/`. From 52d4adea1a8f071a01996b416b334e345a03ae91 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:27:14 -0800 Subject: [PATCH 07/14] test: planted bugs for the server, the engine, drawing and conversations --- tools/mutants/119-http-body-limit-off.patch | 15 +++++++++++++++ tools/mutants/120-http-head-not-counted.patch | 14 ++++++++++++++ tools/mutants/121-api-old-limit-wins.patch | 15 +++++++++++++++ tools/mutants/122-api-tools-ignored.patch | 15 +++++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 tools/mutants/119-http-body-limit-off.patch create mode 100644 tools/mutants/120-http-head-not-counted.patch create mode 100644 tools/mutants/121-api-old-limit-wins.patch create mode 100644 tools/mutants/122-api-tools-ignored.patch diff --git a/tools/mutants/119-http-body-limit-off.patch b/tools/mutants/119-http-body-limit-off.patch new file mode 100644 index 0000000..e77d017 --- /dev/null +++ b/tools/mutants/119-http-body-limit-off.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib what_is_not_a_request +# Bug: a request body of any length is accepted. +diff --git a/crates/dluth-serve/src/http.rs b/crates/dluth-serve/src/http.rs +index 51b301c..695985a 100644 +--- a/crates/dluth-serve/src/http.rs ++++ b/crates/dluth-serve/src/http.rs +@@ -121,7 +121,7 @@ pub fn read_request(reader: &mut impl BufRead) -> Result { + None => 0, + Some(text) => text.parse::().map_err(|_| Refusal::Malformed("Content-Length is not a number"))?, + }; +- if length > MAX_BODY { ++ if length > usize::MAX - 1 { + return Err(Refusal::TooLarge("the request body is too large")); + } + request.body.resize(length, 0); diff --git a/tools/mutants/120-http-head-not-counted.patch b/tools/mutants/120-http-head-not-counted.patch new file mode 100644 index 0000000..cca0918 --- /dev/null +++ b/tools/mutants/120-http-head-not-counted.patch @@ -0,0 +1,14 @@ +# test: cargo test -p dluth-serve --lib what_is_not_a_request +# Bug: the request line and headers are not counted against their limit. +diff --git a/crates/dluth-serve/src/http.rs b/crates/dluth-serve/src/http.rs +index 51b301c..1e2c67e 100644 +--- a/crates/dluth-serve/src/http.rs ++++ b/crates/dluth-serve/src/http.rs +@@ -74,7 +74,6 @@ fn line(reader: &mut impl BufRead, left: &mut usize) -> Result, R + if take > *left { + return Err(Refusal::TooLarge("the request line and headers are too long")); + } +- *left -= take; + bytes.extend_from_slice(&available[..take]); + reader.consume(take); + if done { diff --git a/tools/mutants/121-api-old-limit-wins.patch b/tools/mutants/121-api-old-limit-wins.patch new file mode 100644 index 0000000..d675397 --- /dev/null +++ b/tools/mutants/121-api-old-limit-wins.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib a_full_request +# Bug: max_tokens is read before max_completion_tokens. +diff --git a/crates/dluth-serve/src/api.rs b/crates/dluth-serve/src/api.rs +index 0b08675..0f5dad4 100644 +--- a/crates/dluth-serve/src/api.rs ++++ b/crates/dluth-serve/src/api.rs +@@ -85,7 +85,7 @@ pub fn parse_chat(body: &[u8]) -> Result { + return Err("`n` other than 1 is not supported".into()); + } + let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()); +- let max_tokens = match number(&root, "max_completion_tokens", count)? { ++ let max_tokens = match number(&root, "max_tokens", count)? { + Some(n) => Some(n), + None => number(&root, "max_tokens", count)?, + }; diff --git a/tools/mutants/122-api-tools-ignored.patch b/tools/mutants/122-api-tools-ignored.patch new file mode 100644 index 0000000..fc3a285 --- /dev/null +++ b/tools/mutants/122-api-tools-ignored.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib what_cannot_be_answered +# Bug: a request that declares tools is answered as if it had none. +diff --git a/crates/dluth-serve/src/api.rs b/crates/dluth-serve/src/api.rs +index 0b08675..7cab113 100644 +--- a/crates/dluth-serve/src/api.rs ++++ b/crates/dluth-serve/src/api.rs +@@ -79,7 +79,7 @@ pub fn parse_chat(body: &[u8]) -> Result { + messages.push(Message { role, content, reasoning }); + } + if root.get("tools").is_some_and(|t| t.as_array().is_some_and(|a| !a.is_empty())) { +- return Err("the request declares tools; tools are not supported".into()); ++ + } + if root.get("n").and_then(Value::as_u64).is_some_and(|n| n != 1) { + return Err("`n` other than 1 is not supported".into()); From 35559b39a89720f2a20a3913cb05dba00c5536cf Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:28:21 -0800 Subject: [PATCH 08/14] test: the reply reader; planted bugs for the server, the engine, drawing and conversations --- Cargo.lock | 1 + crates/dluth-serve/src/reply.rs | 87 +++++++++++++++++++ .../mutants/111-draft-wrong-guess-kept.patch | 12 +-- tools/mutants/112-draft-not-undone.patch | 8 +- .../mutants/123-reply-other-kind-shown.patch | 15 ++++ tools/mutants/124-stop-string-passed-on.patch | 15 ++++ .../mutants/125-stop-nothing-held-back.patch | 15 ++++ .../126-engine-edited-reply-reused.patch | 15 ++++ .../127-engine-holds-after-other-effort.patch | 15 ++++ .../128-engine-always-from-the-start.patch | 15 ++++ .../129-engine-length-called-stop.patch | 15 ++++ .../mutants/130-server-key-not-checked.patch | 15 ++++ .../131-server-key-prefix-accepted.patch | 15 ++++ .../mutants/132-server-full-queue-waits.patch | 15 ++++ ...33-server-late-error-as-new-response.patch | 15 ++++ .../134-sample-temperature-ignored.patch | 15 ++++ tools/mutants/135-sample-top-p-ignored.patch | 15 ++++ tools/mutants/136-chat-turn-not-closed.patch | 14 +++ .../137-continue-ignores-listener.patch | 15 ++++ 19 files changed, 322 insertions(+), 10 deletions(-) create mode 100644 tools/mutants/123-reply-other-kind-shown.patch create mode 100644 tools/mutants/124-stop-string-passed-on.patch create mode 100644 tools/mutants/125-stop-nothing-held-back.patch create mode 100644 tools/mutants/126-engine-edited-reply-reused.patch create mode 100644 tools/mutants/127-engine-holds-after-other-effort.patch create mode 100644 tools/mutants/128-engine-always-from-the-start.patch create mode 100644 tools/mutants/129-engine-length-called-stop.patch create mode 100644 tools/mutants/130-server-key-not-checked.patch create mode 100644 tools/mutants/131-server-key-prefix-accepted.patch create mode 100644 tools/mutants/132-server-full-queue-waits.patch create mode 100644 tools/mutants/133-server-late-error-as-new-response.patch create mode 100644 tools/mutants/134-sample-temperature-ignored.patch create mode 100644 tools/mutants/135-sample-top-p-ignored.patch create mode 100644 tools/mutants/136-chat-turn-not-closed.patch create mode 100644 tools/mutants/137-continue-ignores-listener.patch diff --git a/Cargo.lock b/Cargo.lock index 5b19a41..8922f2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -123,6 +123,7 @@ dependencies = [ "dluth-core", "dluth-kernels", "dluth-model", + "dluth-serve", "serde_json", ] diff --git a/crates/dluth-serve/src/reply.rs b/crates/dluth-serve/src/reply.rs index 4c271a4..57e4aab 100644 --- a/crates/dluth-serve/src/reply.rs +++ b/crates/dluth-serve/src/reply.rs @@ -168,6 +168,93 @@ impl StopFilter { mod tests { use super::*; + /// The tiny fixture's tokenizer: one token per byte, and the message tokens from 256. + /// It has no thinking token, so one is made up, with another for a kind nobody knows. + fn tiny() -> (Tokenizer, Markers) { + let path = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling/tokenizer.json"); + let tokenizer = Tokenizer::from_file(&path).unwrap(); + let mut markers = Markers::of(&tokenizer); + assert_eq!( + (markers.message_model, markers.content_text, markers.end_message), + (Some(258), Some(259), Some(260)) + ); + assert_eq!((markers.end_turn, markers.content_thinking), (Some(261), None)); + markers.content_thinking = Some(THINKING); + (tokenizer, markers) + } + const THINKING: u32 = 270; + const OTHER_KIND: u32 = 271; + + fn read(tokens: &[u32]) -> Vec { + let (tokenizer, markers) = tiny(); + let mut reader = ReplyReader::new(&tokenizer, markers); + let mut out: Vec = tokens.iter().filter_map(|t| reader.push(*t)).collect(); + out.extend(reader.finish()); + out + } + + fn bytes(text: &str) -> Vec { + text.bytes().map(u32::from).collect() + } + + fn reasoning(text: &str) -> Delta { + Delta::Reasoning(text.into()) + } + + fn content(text: &str) -> Delta { + Delta::Content(text.into()) + } + + #[test] + fn a_reply_is_cut_into_thinking_and_text() { + let mut tokens = vec![258, THINKING]; + tokens.extend(bytes("hm")); + tokens.extend([260, 258, 259]); + tokens.extend(bytes("ok")); + tokens.extend([260, 261]); + assert_eq!(read(&tokens), [reasoning("h"), reasoning("m"), content("o"), content("k")]); + // Nothing but the structure: nothing to show. + assert!(read(&[258, 259, 260, 261]).is_empty()); + // A reply that does not open a message is taken as text. + assert_eq!(read(&bytes("a")), [content("a")]); + } + + #[test] + fn a_message_of_another_kind_is_dropped() { + let mut tokens = vec![258, OTHER_KIND]; + tokens.extend(bytes("secret")); + tokens.extend([260, 258, 259]); + tokens.extend(bytes("x")); + tokens.push(260); + assert_eq!(read(&tokens), [content("x")]); + // A name before the kind of content does not change the kind. + let mut named = vec![258]; + named.extend(bytes("me")); + named.push(259); + named.extend(bytes("y")); + assert_eq!(read(&named), [content("y")]); + } + + #[test] + fn a_character_split_across_tokens_comes_whole() { + // é is the bytes C3 A9, one token each here. + let mut tokens = vec![258, 259]; + tokens.extend(bytes("aé")); + assert_eq!(read(&tokens), [content("a"), content("é")]); + // Held back at the end of a message, half a character still comes out, as the + // replacement character. + assert_eq!(read(&[258, 259, 0xC3, 260]), [content("\u{FFFD}")]); + // Bytes that never become a character are not held back forever. + let mut junk = vec![258, 259]; + junk.extend([0xC3; 20]); + let out = read(&junk); + assert!( + out.len() >= 2 && out.iter().all(|d| matches!(d, Delta::Content(t) if t.contains('\u{FFFD}'))), + "{out:?}" + ); + } + fn filtered(stops: &[&str], pieces: &[&str]) -> (String, bool) { let stops: Vec = stops.iter().map(|s| s.to_string()).collect(); let mut filter = StopFilter::new(&stops); diff --git a/tools/mutants/111-draft-wrong-guess-kept.patch b/tools/mutants/111-draft-wrong-guess-kept.patch index 181144c..199d53c 100644 --- a/tools/mutants/111-draft-wrong-guess-kept.patch +++ b/tools/mutants/111-draft-wrong-guess-kept.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives # Bug: a wrong guess is kept, and the tokens after it are read from a sweep that followed the wrong text. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 665ee07..169fa36 100644 +index bb3cf65..5772032 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1245,7 +1245,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - generated.push(next); +@@ -1300,7 +1300,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + generated += 1; text.push(next); - on_token(next); -- if next == eos || generated.len() == max_new || batch.get(i + 1) != Some(&next) { -+ if next == eos || generated.len() == max_new || i + 1 == batch.len() { + go_on = on_token(next); +- if !go_on || next == eos || generated == max_new || batch.get(i + 1) != Some(&next) { ++ if !go_on || next == eos || generated == max_new || i + 1 == batch.len() { break; } } diff --git a/tools/mutants/112-draft-not-undone.patch b/tools/mutants/112-draft-not-undone.patch index 461e666..8c1b954 100644 --- a/tools/mutants/112-draft-not-undone.patch +++ b/tools/mutants/112-draft-not-undone.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives # Bug: the guesses that were not kept stay fed. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 86093f8..5a47e62 100644 +index bb3cf65..396f4dd 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1256,7 +1256,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - return Err(ModelError::Device("a sweep returned no scores".into())); +@@ -1305,7 +1305,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + } } stats.accepted += kept - 1; - self.undo(batch.len() - kept)?; + self.undo(0)?; pos += kept; } - Ok((generated, stats)) + Ok(stats) diff --git a/tools/mutants/123-reply-other-kind-shown.patch b/tools/mutants/123-reply-other-kind-shown.patch new file mode 100644 index 0000000..4ec9376 --- /dev/null +++ b/tools/mutants/123-reply-other-kind-shown.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib a_message_of_another_kind +# Bug: a message of a kind that is neither thinking nor text is shown as text. +diff --git a/crates/dluth-serve/src/reply.rs b/crates/dluth-serve/src/reply.rs +index 4c271a4..14fc2fd 100644 +--- a/crates/dluth-serve/src/reply.rs ++++ b/crates/dluth-serve/src/reply.rs +@@ -90,7 +90,7 @@ impl<'t> ReplyReader<'t> { + return out; + } + if self.channel == Channel::Header { +- if is(m.content_text) { ++ if is(m.content_text) || !is(m.content_thinking) { + self.channel = Channel::Text; + } else if is(m.content_thinking) { + self.channel = Channel::Thinking; diff --git a/tools/mutants/124-stop-string-passed-on.patch b/tools/mutants/124-stop-string-passed-on.patch new file mode 100644 index 0000000..2933dc1 --- /dev/null +++ b/tools/mutants/124-stop-string-passed-on.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib a_stop_string_ends +# Bug: the text is passed on up to and including the stop string. +diff --git a/crates/dluth-serve/src/reply.rs b/crates/dluth-serve/src/reply.rs +index 4c271a4..6ffeebe 100644 +--- a/crates/dluth-serve/src/reply.rs ++++ b/crates/dluth-serve/src/reply.rs +@@ -144,7 +144,7 @@ impl StopFilter { + } + self.held.push_str(text); + if let Some(at) = self.stops.iter().filter_map(|s| self.held.find(s.as_str())).min() { +- let out = self.held[..at].to_string(); ++ let out = self.held.clone(); + self.held.clear(); + return (out, true); + } diff --git a/tools/mutants/125-stop-nothing-held-back.patch b/tools/mutants/125-stop-nothing-held-back.patch new file mode 100644 index 0000000..3e69440 --- /dev/null +++ b/tools/mutants/125-stop-nothing-held-back.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --lib a_stop_string_ends +# Bug: nothing is held back, so a stop string split across pieces is missed. +diff --git a/crates/dluth-serve/src/reply.rs b/crates/dluth-serve/src/reply.rs +index 4c271a4..2329008 100644 +--- a/crates/dluth-serve/src/reply.rs ++++ b/crates/dluth-serve/src/reply.rs +@@ -149,7 +149,7 @@ impl StopFilter { + return (out, true); + } + // The last `longest - 1` bytes could be the start of a stop string. +- let mut keep_from = self.held.len().saturating_sub(self.longest - 1); ++ let mut keep_from = self.held.len(); + while !self.held.is_char_boundary(keep_from) { + keep_from -= 1; + } diff --git a/tools/mutants/126-engine-edited-reply-reused.patch b/tools/mutants/126-engine-edited-reply-reused.patch new file mode 100644 index 0000000..3413914 --- /dev/null +++ b/tools/mutants/126-engine-edited-reply-reused.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-serve --test engine a_conversation_that_goes_on +# Bug: a conversation whose reply was edited is taken for the one the model holds. +diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs +index e6fff2e..1bfeb50 100644 +--- a/crates/dluth-serve/src/engine.rs ++++ b/crates/dluth-serve/src/engine.rs +@@ -129,7 +129,7 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + && request.messages.len() > n + && request.messages[..n] == served.messages[..] + && request.messages[n].role == Role::Assistant +- && request.messages[n].content.trim() == served.content.trim(); ++; + if continues { + let more = more_turns(&request.messages[n + 1..]); + let mut tokens = served.text.clone(); diff --git a/tools/mutants/127-engine-holds-after-other-effort.patch b/tools/mutants/127-engine-holds-after-other-effort.patch new file mode 100644 index 0000000..11eb0fd --- /dev/null +++ b/tools/mutants/127-engine-holds-after-other-effort.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-serve --test engine a_conversation_that_goes_on +# Bug: a conversation at another effort level is taken for the one the model holds. +diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs +index e6fff2e..2052d4e 100644 +--- a/crates/dluth-serve/src/engine.rs ++++ b/crates/dluth-serve/src/engine.rs +@@ -125,7 +125,7 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + fn prompt(&self, request: &ChatRequest, effort: Effort) -> Result, EngineError> { + if let Some(served) = &self.served { + let n = served.messages.len(); +- let continues = served.effort == effort ++ let continues = true + && request.messages.len() > n + && request.messages[..n] == served.messages[..] + && request.messages[n].role == Role::Assistant diff --git a/tools/mutants/128-engine-always-from-the-start.patch b/tools/mutants/128-engine-always-from-the-start.patch new file mode 100644 index 0000000..c327815 --- /dev/null +++ b/tools/mutants/128-engine-always-from-the-start.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-serve --test engine a_conversation_that_goes_on +# Bug: the model never keeps what it holds: every prompt is read from its first token. +diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs +index e6fff2e..403303c 100644 +--- a/crates/dluth-serve/src/engine.rs ++++ b/crates/dluth-serve/src/engine.rs +@@ -147,7 +147,7 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + && tokens.len() > self.held.len() + && tokens.starts_with(&self.held) + && self.model.next_position() == self.held.len(); +- let start = if reuse { self.held.len() } else { 0 }; ++ let start = if reuse && false { self.held.len() } else { 0 }; + // Not known again until everything is fed: a failure half way must not leave a + // claim about what the model holds. + self.held.clear(); diff --git a/tools/mutants/129-engine-length-called-stop.patch b/tools/mutants/129-engine-length-called-stop.patch new file mode 100644 index 0000000..53a27f8 --- /dev/null +++ b/tools/mutants/129-engine-length-called-stop.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-serve --test engine stop_strings_limits +# Bug: a reply cut at the limit is reported as ended. +diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs +index e6fff2e..ee511be 100644 +--- a/crates/dluth-serve/src/engine.rs ++++ b/crates/dluth-serve/src/engine.rs +@@ -255,7 +255,7 @@ impl Engine for InklingEngine<'_, '_, O> { + let ended = text.last() == Some(&eos); + // The model has been fed everything but the last token chosen. + self.held = text[..text.len() - 1].to_vec(); +- let finish = if ended || stopped || generated < max_new { Finish::Stop } else { Finish::Length }; ++ let finish = if ended || stopped || generated <= max_new { Finish::Stop } else { Finish::Length }; + if ended { + self.served = Some(Served { messages: request.messages.clone(), effort, text, content }); + } diff --git a/tools/mutants/130-server-key-not-checked.patch b/tools/mutants/130-server-key-not-checked.patch new file mode 100644 index 0000000..11e122f --- /dev/null +++ b/tools/mutants/130-server-key-not-checked.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --test server a_key_is_asked +# Bug: any key is accepted. +diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs +index ff18440..2281c19 100644 +--- a/crates/dluth-serve/src/server.rs ++++ b/crates/dluth-serve/src/server.rs +@@ -82,7 +82,7 @@ fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender + } + if let Some(key) = &config.api_key { + let given = request.header("authorization").and_then(|h| h.strip_prefix("Bearer ")).unwrap_or(""); +- if !same(given, key) { ++ if !same(given, key) && given.is_empty() { + return refuse(&mut stream, 401, "a valid API key is needed"); + } + } diff --git a/tools/mutants/131-server-key-prefix-accepted.patch b/tools/mutants/131-server-key-prefix-accepted.patch new file mode 100644 index 0000000..ad2e8c3 --- /dev/null +++ b/tools/mutants/131-server-key-prefix-accepted.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --test server a_key_is_asked +# Bug: a key is compared only as far as the shorter of the two goes. +diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs +index ff18440..227a31d 100644 +--- a/crates/dluth-serve/src/server.rs ++++ b/crates/dluth-serve/src/server.rs +@@ -54,7 +54,7 @@ fn now() -> u64 { + + /// Whether two strings are equal, in time that depends only on their lengths. + fn same(a: &str, b: &str) -> bool { +- a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 ++ a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 + } + + fn refuse(stream: &mut TcpStream, status: u16, message: &str) { diff --git a/tools/mutants/132-server-full-queue-waits.patch b/tools/mutants/132-server-full-queue-waits.patch new file mode 100644 index 0000000..ba9d0c9 --- /dev/null +++ b/tools/mutants/132-server-full-queue-waits.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --test server requests_wait_their_turn +# Bug: a request that finds the queue full waits for room. +diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs +index ff18440..221972d 100644 +--- a/crates/dluth-serve/src/server.rs ++++ b/crates/dluth-serve/src/server.rs +@@ -92,7 +92,7 @@ fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender + } + ("POST", "/v1/chat/completions") => match api::parse_chat(&request.body) { + Err(why) => refuse(&mut stream, 400, &why), +- Ok(chat) => match jobs.try_send(Job { request: chat, stream }) { ++ Ok(chat) => match jobs.send(Job { request: chat, stream }).map_err(|e| TrySendError::Disconnected(e.0)) { + Ok(()) => {} + Err(TrySendError::Full(mut job)) => { + refuse(&mut job.stream, 503, "the model is busy and its queue is full; try again shortly") diff --git a/tools/mutants/133-server-late-error-as-new-response.patch b/tools/mutants/133-server-late-error-as-new-response.patch new file mode 100644 index 0000000..a78f224 --- /dev/null +++ b/tools/mutants/133-server-late-error-as-new-response.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --test server failures_get_a_status +# Bug: a failure after a streamed reply began writes a second response head into the stream. +diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs +index ff18440..25e9875 100644 +--- a/crates/dluth-serve/src/server.rs ++++ b/crates/dluth-serve/src/server.rs +@@ -147,7 +147,7 @@ fn answer(engine: &mut dyn Engine, job: Job, number: u64) -> String { + EngineError::Refused(m) => (400, m.as_str()), + EngineError::Failed(m) => (500, m.as_str()), + }; +- if started { ++ if started && false { + let kind = if status == 500 { "server_error" } else { "invalid_request_error" }; + let _ = http::write_event(&mut stream, &api::error(message, kind)); + } else { diff --git a/tools/mutants/134-sample-temperature-ignored.patch b/tools/mutants/134-sample-temperature-ignored.patch new file mode 100644 index 0000000..9cd5377 --- /dev/null +++ b/tools/mutants/134-sample-temperature-ignored.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --lib draws_follow +# Bug: a draw ignores the temperature. +diff --git a/crates/dluth-model/src/inkling/sample.rs b/crates/dluth-model/src/inkling/sample.rs +index 6f875cc..ca8c5ff 100644 +--- a/crates/dluth-model/src/inkling/sample.rs ++++ b/crates/dluth-model/src/inkling/sample.rs +@@ -74,7 +74,7 @@ impl Sampler { + .iter() + .enumerate() + .filter(|(_, s)| **s >= floor) +- .map(|(i, s)| (i as u32, (((s - scores[best]) / self.temperature) as f64).exp())) ++ .map(|(i, s)| (i as u32, ((s - scores[best]) as f64).exp())) + .collect(); + // Most likely first; equal weights by token id, so the order does not depend on + // anything but the scores. diff --git a/tools/mutants/135-sample-top-p-ignored.patch b/tools/mutants/135-sample-top-p-ignored.patch new file mode 100644 index 0000000..1c3ab73 --- /dev/null +++ b/tools/mutants/135-sample-top-p-ignored.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --lib top_p_keeps +# Bug: top_p cuts nothing. +diff --git a/crates/dluth-model/src/inkling/sample.rs b/crates/dluth-model/src/inkling/sample.rs +index 6f875cc..aee773d 100644 +--- a/crates/dluth-model/src/inkling/sample.rs ++++ b/crates/dluth-model/src/inkling/sample.rs +@@ -80,7 +80,7 @@ impl Sampler { + // anything but the scores. + near.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + let total: f64 = near.iter().map(|(_, w)| w).sum(); +- if self.top_p < 1.0 { ++ if self.top_p < 0.0 { + let mut kept = 0.0; + let mut count = 0; + for (_, w) in &near { diff --git a/tools/mutants/136-chat-turn-not-closed.patch b/tools/mutants/136-chat-turn-not-closed.patch new file mode 100644 index 0000000..5373138 --- /dev/null +++ b/tools/mutants/136-chat-turn-not-closed.patch @@ -0,0 +1,14 @@ +# test: cargo test -p dluth-model --lib a_chat_puts +# Bug: an assistant turn in a conversation is not closed by the token that ends a turn. +diff --git a/crates/dluth-model/src/inkling/prompt.rs b/crates/dluth-model/src/inkling/prompt.rs +index 13239ad..87d9188 100644 +--- a/crates/dluth-model/src/inkling/prompt.rs ++++ b/crates/dluth-model/src/inkling/prompt.rs +@@ -130,7 +130,6 @@ fn write_turn(out: &mut String, message: &Message) { + out.push_str(&format!("{role}<|content_text|>{}<|end_message|>", message.content)); + } + if message.role == Role::Assistant { +- out.push_str("<|content_model_end_sampling|>"); + } + } + diff --git a/tools/mutants/137-continue-ignores-listener.patch b/tools/mutants/137-continue-ignores-listener.patch new file mode 100644 index 0000000..aaa3373 --- /dev/null +++ b/tools/mutants/137-continue-ignores-listener.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-serve --test engine stop_strings_limits +# Bug: generation goes on after the listener has left. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index bb3cf65..9647d5f 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1300,7 +1300,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + generated += 1; + text.push(next); + go_on = on_token(next); +- if !go_on || next == eos || generated == max_new || batch.get(i + 1) != Some(&next) { ++ if next == eos || generated == max_new || batch.get(i + 1) != Some(&next) { + break; + } + } From 59cb25a664493c1c821dbf97005855552fb316ef Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:33:04 -0800 Subject: [PATCH 09/14] test: headers are counted together; a listener that leaves stops generation at once --- crates/dluth-model/tests/inkling_draft.rs | 41 +++++++++++++++++++ crates/dluth-serve/src/http.rs | 3 ++ .../137-continue-ignores-listener.patch | 2 +- 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/dluth-model/tests/inkling_draft.rs b/crates/dluth-model/tests/inkling_draft.rs index d8a135a..a63ec8b 100644 --- a/crates/dluth-model/tests/inkling_draft.rs +++ b/crates/dluth-model/tests/inkling_draft.rs @@ -247,6 +247,47 @@ fn generation_with_guesses_stops_at_the_end_token_and_at_the_limits() { )); } +/// Generation that continues from the model's state stops the moment its listener says +/// so, in the middle of a sweep of right guesses too, and leaves the model in order. +#[test] +fn a_listener_that_leaves_stops_generation_at_once() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let prompt = &tokens(64)[41..64]; + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let plain = model.generate_greedy(prompt, 30, u32::MAX).unwrap(); + for stop_after in [1, 2, 4, 9] { + let mut all_right = + Scripted { truth: plain.clone(), prompt: prompt.len(), wrong_every: 0, asked: 0, guesses: 0 }; + model.feed(prompt, 0).unwrap(); + let mut text = prompt.to_vec(); + let mut heard = 0; + let mut pick = |scores: &[f32]| { + let mut best = 0; + for (i, v) in scores.iter().enumerate() { + if *v > scores[best] { + best = i; + } + } + best as u32 + }; + model + .continue_drafted(&mut text, 30, u32::MAX, &mut all_right, 7, &mut pick, &mut |_| { + heard += 1; + heard < stop_after + }) + .unwrap(); + assert_eq!(heard, stop_after, "no token is reported after the listener left"); + assert_eq!(text[prompt.len()..], plain[..stop_after]); + // Fed: everything but the last token chosen. + assert_eq!(model.next_position(), text.len() - 1); + // And generation can go on from there to the same text. + let before = text.len(); + model.continue_drafted(&mut text, 5, u32::MAX, &mut NoDraft, 0, &mut pick, &mut |_| true).unwrap_err(); + assert_eq!(text.len(), before, "a text one token ahead of the model is refused, not guessed at"); + } +} + #[test] fn the_real_model_generates_the_same_tokens_with_guesses() { let Ok(dir) = std::env::var("DLUTH_INKLING2_MINI") else { diff --git a/crates/dluth-serve/src/http.rs b/crates/dluth-serve/src/http.rs index 51b301c..c67c5e2 100644 --- a/crates/dluth-serve/src/http.rs +++ b/crates/dluth-serve/src/http.rs @@ -208,6 +208,9 @@ mod tests { assert_eq!(read(&huge).unwrap_err().status(), 413); let long = format!("GET /x HTTP/1.1\r\nA: {}\r\n\r\n", "a".repeat(MAX_HEAD)); assert_eq!(read(&long).unwrap_err().status(), 413); + // Many headers, none long by itself, are counted together. + let many = format!("GET /x HTTP/1.1\r\n{}\r\n", "A: 0123456789\r\n".repeat(MAX_HEAD / 15 + 1)); + assert_eq!(read(&many).unwrap_err().status(), 413); // Exactly at the limits is fine. let head = "GET /x HTTP/1.1\r\nA: "; let fits = format!("{head}{}\r\n\r\n", "a".repeat(MAX_HEAD - head.len() - 4)); diff --git a/tools/mutants/137-continue-ignores-listener.patch b/tools/mutants/137-continue-ignores-listener.patch index aaa3373..63e9460 100644 --- a/tools/mutants/137-continue-ignores-listener.patch +++ b/tools/mutants/137-continue-ignores-listener.patch @@ -1,4 +1,4 @@ -# test: cargo test --release -p dluth-serve --test engine stop_strings_limits +# test: cargo test -p dluth-model --test inkling_draft a_listener_that_leaves # Bug: generation goes on after the listener has left. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index bb3cf65..9647d5f 100644 From 33e39c4ed069cfd974930a1c576df5ebc285a106 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:33:28 -0800 Subject: [PATCH 10/14] docs: note 24, serving --- docs/learning/24-serving.md | 93 +++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 docs/learning/24-serving.md diff --git a/docs/learning/24-serving.md b/docs/learning/24-serving.md new file mode 100644 index 0000000..a9d2230 --- /dev/null +++ b/docs/learning/24-serving.md @@ -0,0 +1,93 @@ +# 24. Serving + +Until now the engine was a program that generates once and exits. To be used, a model has to be something +other programs can call. This note is about the small server that does that, and about the three places +where serving a model is more than wrapping a function in HTTP. + +## The shape + +Almost every client and router speaks the chat-completions format: a list of messages goes in as JSON, and +a reply comes back whole or as a stream of events. The server answers that at `/v1/chat/completions`, lists +its model at `/v1/models`, and says it is alive at `/health`. + +The HTTP underneath is written by hand, on the standard library: read one request, write one response or +one stream of events, close. That is a few hundred lines, and what it leaves out is deliberate: no +keep-alive, no TLS, no chunked request bodies. A request's head and body have fixed limits, and what does +not fit is refused, not buffered. + +There is one model and it holds one sequence, so there is one generation at a time: + +- Each connection is read and checked on a thread of its own. A slow client, a health check or a malformed + request never waits for a generation. +- A chat request that checks out goes into a short queue. The thread that owns the model takes requests one + at a time and writes each reply to its connection as it is produced. +- A request that finds the queue full is told so at once, with a 503. Waiting unseen behind a long + generation is worse than being told to come back. +- If a client hangs up, its next write fails, and generation stops at that token. + +What cannot be answered as asked is refused in words: tools, images, more than one choice. A field the +server does not know is ignored. + +## Thinking and text + +The model's reply is not one text. It is a run of messages, each opening with tokens that say who speaks +and what kind of content follows, and closing with an end token. Inkling 2 thinks first, in a message of +its own, and then answers. A reader walks the tokens and sorts the text into `reasoning_content` and +`content`; a kind of message it does not know is dropped. + +Two details of turning tokens into text as they arrive: + +- A character can be split across tokens. The reader holds tokens back while their bytes end in half a + character, for at most a few tokens. +- A stop string can be split across pieces. Text is passed on a little late: what might still be the + beginning of a stop string is held back until it is one or is not. + +## Not reading the conversation again + +Chat clients send the whole conversation with every turn. The model cannot use that directly: it holds one +sequence and can only go on from its end (or take back a few tokens, note 23). Read naively, turn ten +re-reads nine turns. + +The server remembers the conversation it answered last as tokens: the prompt it was fed and the reply the +model produced, its thinking included. When the next request is that conversation, then the reply as the +client was given it, then new messages, the prompt is the remembered tokens plus the new messages, and +only the new messages are fed. The response says how many tokens were not read again. + +One thing is worth knowing about this. A client sends back only the text of the model's reply, not its +thinking. The remembered tokens contain the thinking. So in a continued conversation the model sees what +it thought earlier, which the model's chat format has a place for, where a server that re-read the +conversation as sent would not show it. The answers can differ between the two. + +A conversation that does not continue the last one (an edited reply, another beginning, another effort +level) is read from its first token. + +## Choosing a token + +The server draws tokens: `temperature`, `top_p` and `seed` from the request, a temperature of 0 for the +highest score. Only the tokens within reach of the best score can be drawn, a few hundred of two hundred +thousand, so they are the only ones sorted. + +Guesses (note 23) are compared with the token that was drawn, so drawing and guessing combine without +changing how the text is distributed. + +## Tried + +Inkling 2 Mini on the GB10, the server started by hand: 18 GB of weights on the device in 52 seconds, +before the server listens. "What is the capital of Ireland? Answer in one sentence." came back as "The +capital of Ireland is Dublin.", with the thinking apart, 86 tokens at 24 per second. The follow-up turn +held 110 of its 122 prompt tokens and read the rest in 0.12 seconds. + +## How it was checked + +- The HTTP reader and the request format against requests that are right, wrong and too large. +- The server over real sockets with an engine that says what it is told to: whole and streamed replies, + failures before and after a stream began, the key, a full queue answered at once while the model is busy, + a client that leaves. +- The engine with the tiny model: what it hands out is what the model, used directly, produces for the same + tokens, at temperature 0 and drawn, with and without guesses; a continued conversation feeds only the new + turn and answers as the model does for exactly those tokens read from the start; edited conversations are + read from the start. +- Planted bugs: limits not applied, tools ignored, another kind of message shown, a stop string passed on + or missed across pieces, an edited conversation taken for the remembered one, any key accepted, a key + compared as a prefix, a full queue that waits, a late failure written as a second response, temperature + or top_p ignored, a turn not closed, generation going on after its listener left. From e35ed8afbadc01fb08b50d8131dff6437edddfa9 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:50:04 -0800 Subject: [PATCH 11/14] docs: guesses and drawn tokens; a planted bug regenerated --- docs/learning/23-guessing-ahead.md | 6 +++--- tools/mutants/112-draft-not-undone.patch | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/learning/23-guessing-ahead.md b/docs/learning/23-guessing-ahead.md index e2e4da1..976dfdd 100644 --- a/docs/learning/23-guessing-ahead.md +++ b/docs/learning/23-guessing-ahead.md @@ -12,9 +12,9 @@ its scores count too, and so on. At the first position whose choice is not the n choice is taken, and everything fed after it was fed on a wrong text and is thrown away. The text that comes out is the text generation without guesses produces. A right guess is a token for a -fraction of a sweep. A wrong one costs the part of the sweep spent on it. In this step the choice at each -position is the highest score. Nothing in the idea needs that: a guess could as well be compared with a -token drawn from the scores, which is left for the step that draws tokens. +fraction of a sweep. A wrong one costs the part of the sweep spent on it. The choice at each position can +be the highest score or a token drawn from the scores (note 24): a guess is compared with whatever was +chosen, so the text is distributed as it would be without guesses. ## Taking tokens back diff --git a/tools/mutants/112-draft-not-undone.patch b/tools/mutants/112-draft-not-undone.patch index 8c1b954..bd8878f 100644 --- a/tools/mutants/112-draft-not-undone.patch +++ b/tools/mutants/112-draft-not-undone.patch @@ -1,11 +1,11 @@ # test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives # Bug: the guesses that were not kept stay fed. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index bb3cf65..396f4dd 100644 +index 2fdd02c..9e2f8a7 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1305,7 +1305,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - } +@@ -1311,7 +1311,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + return Err(ModelError::Device("a sweep returned no scores".into())); } stats.accepted += kept - 1; - self.undo(batch.len() - kept)?; From 0e969fce554e7e06d2542bee82b6601e3c95249b Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:02:30 -0800 Subject: [PATCH 12/14] fix(serve): a request must arrive whole within the server's patience; a best score that is not finite is the greedy choice; review fixes --- README.md | 6 ++-- crates/dluth-model/src/inkling/sample.rs | 18 +++++++++- crates/dluth-model/tests/inkling_draft.rs | 3 +- crates/dluth-serve/src/server.rs | 42 +++++++++++++++++++---- crates/dluth-serve/tests/engine.rs | 7 ++++ crates/dluth-serve/tests/server.rs | 29 +++++++++++++++- 6 files changed, 94 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 9fe286f..7bad7cb 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ CPU, which is only good for trying the interface). It answers `POST /v1/chat/com | `--name ` | the name the model is listed under | the directory's name | | `--guesses ` | guessed tokens checked per sweep; 0 for none | 4 | | `--match ` | last tokens that must have appeared before for a guess | 2 | +| `--prompt-batch ` | tokens of a prompt read per sweep, at most 16 on the GPU | 16 | | `--temperature ` | used when a request does not set one; 0 is greedy | 1 | | `--effort ` | reasoning effort when a request does not set `reasoning_effort` | high | | `--queue ` | requests that may wait for the model | 8 | @@ -52,13 +53,14 @@ If the environment variable `DLUTH_API_KEY` is set, requests under `/v1/` must s What to know before relying on it: - One model, one conversation at a time. Requests are answered in turn; when the queue is full a request - gets a 503 at once. + gets a 503 at once. A client that stops reading its streamed reply without closing the connection holds + the model for up to 30 seconds before it is given up on. - From a request it reads `messages` (text; system, user and assistant), `max_completion_tokens` or `max_tokens`, `temperature`, `top_p`, `seed`, `stop`, `stream`, `stream_options.include_usage` and `reasoning_effort`. Tools, images and `n` above 1 are refused with a 400, not ignored. - The model's thinking comes back as `reasoning_content`, apart from `content`. - The server keeps the conversation it answered last. A request that continues it (the same messages, the - reply as it was given, then more) only reads the new messages; `usage.prompt_tokens_details.cached_tokens` + reply as it was given, apart from spaces around it, then more) only reads the new messages; `usage.prompt_tokens_details.cached_tokens` says how many tokens were not read again. - Message text is put into the model's chat format as it is. Text that contains the model's special token strings is read as those tokens, as with the model's own template. Do not expose the server to people diff --git a/crates/dluth-model/src/inkling/sample.rs b/crates/dluth-model/src/inkling/sample.rs index 6f875cc..4e50604 100644 --- a/crates/dluth-model/src/inkling/sample.rs +++ b/crates/dluth-model/src/inkling/sample.rs @@ -64,7 +64,9 @@ impl Sampler { best = i; } } - if self.temperature == 0.0 { + // A best score that is not a finite number leaves nothing to weigh the others + // against: the choice is then the one greedy makes. + if self.temperature == 0.0 || !scores[best].is_finite() { return best as u32; } // Only tokens within reach of the best can be drawn: a few hundred of a vocabulary @@ -173,6 +175,20 @@ mod tests { assert_ne!(run(5), run(6)); } + #[test] + fn scores_that_are_not_numbers_do_not_stop_a_draw() { + let mut s = Sampler::new(Sampling { temperature: 1.0, top_p: 0.9, seed: 3 }); + // The first score is what "best" starts from; nothing compares with it. + assert_eq!(s.pick(&[f32::NAN, 1.0, 2.0]), 0); + assert_eq!(s.pick(&[f32::NAN; 4]), 0); + // Elsewhere, such a score is simply never drawn. + for _ in 0..200 { + assert_ne!(s.pick(&[1.0, f32::NAN, 1.5]), 1); + } + assert_eq!(s.pick(&[f32::NEG_INFINITY, f32::NEG_INFINITY]), 0); + assert_eq!(Sampler::new(Sampling::greedy()).pick(&[f32::NAN, 3.0]), 0); + } + #[test] fn a_far_less_likely_token_is_never_drawn_and_one_token_is_always_it() { let mut s = Sampler::new(Sampling { temperature: 1.0, top_p: 1.0, seed: 3 }); diff --git a/crates/dluth-model/tests/inkling_draft.rs b/crates/dluth-model/tests/inkling_draft.rs index a63ec8b..191bc23 100644 --- a/crates/dluth-model/tests/inkling_draft.rs +++ b/crates/dluth-model/tests/inkling_draft.rs @@ -281,7 +281,8 @@ fn a_listener_that_leaves_stops_generation_at_once() { assert_eq!(text[prompt.len()..], plain[..stop_after]); // Fed: everything but the last token chosen. assert_eq!(model.next_position(), text.len() - 1); - // And generation can go on from there to the same text. + // The text is now one token ahead of the model. Going on means feeding that token + // first; asking to go on without doing so is refused, not guessed at. let before = text.len(); model.continue_drafted(&mut text, 5, u32::MAX, &mut NoDraft, 0, &mut pick, &mut |_| true).unwrap_err(); assert_eq!(text.len(), before, "a text one token ahead of the model is refused, not guessed at"); diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs index ff18440..f4397e3 100644 --- a/crates/dluth-serve/src/server.rs +++ b/crates/dluth-serve/src/server.rs @@ -16,7 +16,7 @@ use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{sync_channel, SyncSender, TrySendError}; use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; #[derive(Clone, Debug)] pub struct Config { @@ -24,7 +24,8 @@ pub struct Config { pub api_key: Option, /// Chat requests that may wait for the model. One more is being answered. pub queue: usize, - /// How long a connection may take to send its request, and to accept each write. + /// How long a connection may take to send its whole request, and how long each write + /// of a reply may take to be accepted. pub patience: Duration, /// Connections being read at once; more are turned away. pub connections: usize, @@ -57,16 +58,40 @@ fn same(a: &str, b: &str) -> bool { a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } +/// Reads from a connection until a moment that is fixed when the request starts. A read +/// timeout by itself would start again with every byte, so that a client sending a byte now +/// and then could hold its place for ever. +struct Until<'s> { + stream: &'s TcpStream, + deadline: Instant, +} + +impl io::Read for Until<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let left = self.deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(io::ErrorKind::TimedOut.into()); + } + self.stream.set_read_timeout(Some(left))?; + let mut stream = self.stream; + stream.read(buf) + } +} + fn refuse(stream: &mut TcpStream, status: u16, message: &str) { - let kind = if status >= 500 { "server_error" } else { "invalid_request_error" }; + let kind = match status { + 401 => "authentication_error", + 500.. => "server_error", + _ => "invalid_request_error", + }; let _ = http::write_json(stream, status, &api::error(message, kind)); } /// Reads one connection's request and answers it, or queues it for the model. fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender) { - let _ = stream.set_read_timeout(Some(config.patience)); let _ = stream.set_write_timeout(Some(config.patience)); - let request = match http::read_request(&mut BufReader::new(&stream)) { + let until = Until { stream: &stream, deadline: Instant::now() + config.patience }; + let request = match http::read_request(&mut BufReader::new(until)) { Ok(request) => request, Err(http::Refusal::Gone) => return, Err(refusal) => return refuse(&mut stream, refusal.status(), refusal.message()), @@ -81,7 +106,12 @@ fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender return refuse(&mut stream, 404, "there is nothing at this path"); } if let Some(key) = &config.api_key { - let given = request.header("authorization").and_then(|h| h.strip_prefix("Bearer ")).unwrap_or(""); + // `Bearer `; the scheme's name in any case. + let given = request + .header("authorization") + .and_then(|h| h.split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("bearer")) + .map_or("", |(_, key)| key); if !same(given, key) { return refuse(&mut stream, 401, "a valid API key is needed"); } diff --git a/crates/dluth-serve/tests/engine.rs b/crates/dluth-serve/tests/engine.rs index 7347e98..bffcd62 100644 --- a/crates/dluth-serve/tests/engine.rs +++ b/crates/dluth-serve/tests/engine.rs @@ -203,6 +203,13 @@ fn stop_strings_limits_and_refusals() { assert_eq!((got.as_str(), finish), (before, Finish::Stop)); assert!(usage.completion_tokens < 30); + // A stop string the reply begins with ends it before anything is handed out. + let mut at_once = request(messages.clone(), 30, 0.0, 0); + at_once.stop = vec![whole.chars().take(2).collect()]; + let (got, finish, usage) = ask(&mut engine, &at_once); + assert_eq!((got.as_str(), finish), ("", Finish::Stop)); + assert!(usage.completion_tokens < 30); + // The limit on new tokens, and the room left in the context when none is given. let (_, finish, usage) = ask(&mut engine, &request(messages.clone(), 4, 0.0, 0)); assert_eq!((finish, usage.completion_tokens), (Finish::Length, 4)); diff --git a/crates/dluth-serve/tests/server.rs b/crates/dluth-serve/tests/server.rs index 9f5fe70..f684d78 100644 --- a/crates/dluth-serve/tests/server.rs +++ b/crates/dluth-serve/tests/server.rs @@ -204,7 +204,9 @@ fn a_key_is_asked_for_when_one_is_set() { assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: Bearer s3cret-kez\r\n").0, 401); assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: Bearer s3cret-key-and-more\r\n").0, 401); assert_eq!(post(server.addr, &chat("hi", ""), "Authorization: s3cret-key\r\n").0, 401); - assert_eq!(post(server.addr, &chat("hi", ""), "authorization: Bearer s3cret-key\r\n").0, 200); + assert_eq!(post(server.addr, &chat("hi", ""), "authorization: bearer s3cret-key\r\n").0, 200); + let (status, body) = get(server.addr, "/v1/models"); + assert_eq!((status, json(&body)["error"]["type"].as_str()), (401, Some("authentication_error"))); assert_eq!(send(server.addr, "GET /v1/models HTTP/1.1\r\nAuthorization: Bearer s3cret-key\r\n\r\n").0, 200); assert_eq!(*server.asked.lock().unwrap(), ["hi"]); server.finish(); @@ -233,6 +235,31 @@ fn requests_wait_their_turn_and_a_full_queue_says_so() { server.finish(); } +/// A request must arrive whole within the server's patience, however steadily its bytes +/// trickle in: the connection is dropped when the time is up, not a while after the last byte. +#[test] +fn a_request_that_trickles_in_is_dropped_when_its_time_is_up() { + let server = start(Config { patience: Duration::from_millis(400), ..Config::default() }); + let mut stream = TcpStream::connect(server.addr).unwrap(); + let started = std::time::Instant::now(); + let mut dropped_after = None; + // A byte every 100 ms: each arrives well inside the patience, the whole never does. + for byte in "GET /health HTTP/1.1\r\nX-Slow: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".bytes() { + if stream.write_all(&[byte]).is_err() { + dropped_after = Some(started.elapsed()); + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + // Writes into a closed connection fail a little after it closed; what matters is that + // it closed long before the request would have finished (6 seconds at this pace). + let dropped_after = dropped_after.expect("the connection was kept open"); + assert!(dropped_after < Duration::from_millis(1500), "dropped after {dropped_after:?}"); + // A request that arrives in time is still answered. + assert_eq!(get(server.addr, "/health").0, 200); + server.finish(); +} + #[test] fn a_client_that_leaves_ends_its_reply_and_the_next_is_served() { let server = start(Config::default()); From 92deb7688751c1f7fd64ac51cc11c90b347c01e4 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:02:41 -0800 Subject: [PATCH 13/14] test: planted bugs for the request deadline and for scores that are not numbers --- tools/mutants/138-server-patience-per-read.patch | 15 +++++++++++++++ tools/mutants/139-sample-not-a-number-best.patch | 15 +++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tools/mutants/138-server-patience-per-read.patch create mode 100644 tools/mutants/139-sample-not-a-number-best.patch diff --git a/tools/mutants/138-server-patience-per-read.patch b/tools/mutants/138-server-patience-per-read.patch new file mode 100644 index 0000000..d833f07 --- /dev/null +++ b/tools/mutants/138-server-patience-per-read.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-serve --test server a_request_that_trickles +# Bug: a connection's time to send its request starts again with every read. +diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs +index f4397e3..6c3a00d 100644 +--- a/crates/dluth-serve/src/server.rs ++++ b/crates/dluth-serve/src/server.rs +@@ -68,7 +68,7 @@ struct Until<'s> { + + impl io::Read for Until<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { +- let left = self.deadline.saturating_duration_since(Instant::now()); ++ let left = Duration::from_millis(300); + if left.is_zero() { + return Err(io::ErrorKind::TimedOut.into()); + } diff --git a/tools/mutants/139-sample-not-a-number-best.patch b/tools/mutants/139-sample-not-a-number-best.patch new file mode 100644 index 0000000..5e9a1e1 --- /dev/null +++ b/tools/mutants/139-sample-not-a-number-best.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --lib scores_that_are_not_numbers +# Bug: a best score that is not a finite number is weighed like any other. +diff --git a/crates/dluth-model/src/inkling/sample.rs b/crates/dluth-model/src/inkling/sample.rs +index 4e50604..faebdfc 100644 +--- a/crates/dluth-model/src/inkling/sample.rs ++++ b/crates/dluth-model/src/inkling/sample.rs +@@ -66,7 +66,7 @@ impl Sampler { + } + // A best score that is not a finite number leaves nothing to weigh the others + // against: the choice is then the one greedy makes. +- if self.temperature == 0.0 || !scores[best].is_finite() { ++ if self.temperature == 0.0 { + return best as u32; + } + // Only tokens within reach of the best can be drawn: a few hundred of a vocabulary From 8106fd7a2216ea6f07b32d5979864d9bb9e5af20 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:09:59 -0800 Subject: [PATCH 14/14] test: two planted bugs regenerated --- tools/mutants/130-server-key-not-checked.patch | 10 +++++----- tools/mutants/131-server-key-prefix-accepted.patch | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/mutants/130-server-key-not-checked.patch b/tools/mutants/130-server-key-not-checked.patch index 11e122f..a309d3d 100644 --- a/tools/mutants/130-server-key-not-checked.patch +++ b/tools/mutants/130-server-key-not-checked.patch @@ -1,13 +1,13 @@ # test: cargo test -p dluth-serve --test server a_key_is_asked # Bug: any key is accepted. diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs -index ff18440..2281c19 100644 +index f4397e3..0f8a930 100644 --- a/crates/dluth-serve/src/server.rs +++ b/crates/dluth-serve/src/server.rs -@@ -82,7 +82,7 @@ fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender - } - if let Some(key) = &config.api_key { - let given = request.header("authorization").and_then(|h| h.strip_prefix("Bearer ")).unwrap_or(""); +@@ -112,7 +112,7 @@ fn receive(mut stream: TcpStream, config: &Config, name: &str, jobs: &SyncSender + .and_then(|h| h.split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("bearer")) + .map_or("", |(_, key)| key); - if !same(given, key) { + if !same(given, key) && given.is_empty() { return refuse(&mut stream, 401, "a valid API key is needed"); diff --git a/tools/mutants/131-server-key-prefix-accepted.patch b/tools/mutants/131-server-key-prefix-accepted.patch index ad2e8c3..3f21881 100644 --- a/tools/mutants/131-server-key-prefix-accepted.patch +++ b/tools/mutants/131-server-key-prefix-accepted.patch @@ -1,10 +1,10 @@ # test: cargo test -p dluth-serve --test server a_key_is_asked # Bug: a key is compared only as far as the shorter of the two goes. diff --git a/crates/dluth-serve/src/server.rs b/crates/dluth-serve/src/server.rs -index ff18440..227a31d 100644 +index f4397e3..6348e6b 100644 --- a/crates/dluth-serve/src/server.rs +++ b/crates/dluth-serve/src/server.rs -@@ -54,7 +54,7 @@ fn now() -> u64 { +@@ -55,7 +55,7 @@ fn now() -> u64 { /// Whether two strings are equal, in time that depends only on their lengths. fn same(a: &str, b: &str) -> bool { @@ -12,4 +12,4 @@ index ff18440..227a31d 100644 + a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } - fn refuse(stream: &mut TcpStream, status: u16, message: &str) { + /// Reads from a connection until a moment that is fixed when the request starts. A read