A high-performance inference engine for AI models
Prefill fixes (#832)
Aleksandr Golokozc78181d318de
diff --git a/Cargo.lock b/Cargo.lockindex c2c1a9e77..1dd4c07f8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7591,6 +7591,7 @@ dependencies = ["shoji","sysinfo","tempfile",+ "test-tag","thiserror 2.0.18","tokenizers","tokio",diff --git a/crates/legacy/hanashi/src/chat/hanashi/continuation.rs b/crates/legacy/hanashi/src/chat/hanashi/continuation.rsnew file mode 100644index 000000000..b3869274a--- /dev/null+++ b/crates/legacy/hanashi/src/chat/hanashi/continuation.rs@@ -0,0 +1,140 @@+use shoji::types::{+ basic::TokenId,+ session::chat::{ChatContentBlock, ChatMessage, ChatRole},+};+use token_stream_parser::{Parser as _, reduction::ReductionParserSection, token_stream::TokenStreamParser};++use super::{Error, HanashiEncodingImpl, config::HanashiConfig};++impl HanashiEncodingImpl {+ /// Append a rendered continuation without replacing any sampled prefix token IDs.+ /// Returns None without changing state when the history or message boundary is incompatible.+ pub fn try_append(+ &mut self,+ messages: &[ChatMessage],+ ) -> Result<Option<Vec<TokenId>>, Error> {+ let previous_len = self.state.messages.len();+ if messages.len() <= previous_len+ || !messages.last().is_some_and(|message| matches!(message.role, ChatRole::User {} | ChatRole::Tool {}))+ || !self.state.messages.last().is_some_and(|message| {+ matches!(message.role, ChatRole::Assistant {})+ && !message.content.iter().any(|block| matches!(block, ChatContentBlock::ToolCallCandidate { .. }))+ })+ {+ return Ok(None);+ }++ let Some((group, close)) = Self::completed_boundary(&self.parser) else {+ return Ok(None);+ };++ if !self+ .state+ .tokens+ .last()+ .is_some_and(|token| token.is_special && token.id == close.id && token.value == close.value)+ {+ return Ok(None);+ }++ let boundary = (group.to_string(), close.value.clone());+ let previous = self.fill_default_content(&self.state.messages)?;+ let previous_text = self.render_messages(&previous, false)?;+ let Some(prefix_end) = self.rendered_boundary(&previous_text, &boundary)? else {+ return Ok(None);+ };++ let messages = self.fill_default_content(messages)?;+ let next_text = self.render_messages(&messages, true)?;+ let Some(suffix) = next_text.strip_prefix(&previous_text[..prefix_end]) else {+ return Ok(None);+ };++ let suffix_ids = self.tokenize(suffix)?;+ if suffix_ids.is_empty() {+ return Ok(None);+ }++ // Build the candidate separately: parsing/validation errors must not damage the+ // encoding that still describes the live backend. Replay the exact cached tokens.+ let mut candidate = self.empty_copy()?;+ for message in &messages {+ candidate.validator.validate_next(&message.role)?;+ }+ if messages+ .iter()+ .any(|message| message.content.iter().any(|block| matches!(block, ChatContentBlock::Tools { .. })))+ {+ candidate.parser.set_variable("tools", serde_json::Value::Bool(true));+ }+ candidate.state.messages = messages;+ for token in &self.state.tokens {+ candidate.push_token_to_parser(token, true)?;+ }+ candidate.state.tokens = self.state.tokens.clone();+ candidate.tokenizer_decode_ids = self.tokenizer_decode_ids.clone();+ candidate.tokenizer_decode_prefix = self.tokenizer_decode_prefix.clone();+ candidate.tokenizer_decode_prefix_index = self.tokenizer_decode_prefix_index;+ for id in &suffix_ids {+ let token = candidate.resolve_token(*id, true)?;+ candidate.push_token_to_parser(&token, true)?;+ candidate.state.tokens.push(token);+ }+ candidate.parser.flush_extraction();+ candidate.update_messages_from_parser_state()?;+ *self = candidate;++ Ok(Some(suffix_ids))+ }++ fn empty_copy(&self) -> Result<Self, Error> {+ Self::new(+ HanashiConfig::Custom {+ config: self.config.clone(),+ },+ self.tokenizer.clone(),+ )+ }++ /// Locate the canonical counterpart of the sampled message's closing marker.+ /// Template-owned whitespace after that marker belongs to the new suffix.+ fn rendered_boundary(+ &self,+ text: &str,+ boundary: &(String, String),+ ) -> Result<Option<usize>, Error> {+ let mut rendered = self.empty_copy()?;+ let mut decoded = String::new();+ let mut end = None;+ for id in self.tokenize(text)? {+ let token = rendered.resolve_token(id, true)?;+ decoded.push_str(&token.value);+ rendered.push_token_to_parser(&token, true)?;+ if let Some((group, close)) = Self::completed_boundary(&rendered.parser)+ && group == boundary.0+ && close.value == boundary.1+ && token.is_special+ && token.id == close.id+ && token.value == close.value+ {+ end = Some(decoded.len());+ }+ }+ // A normalizing tokenizer or a template without the corresponding completed+ // message cannot supply a safe byte boundary for splicing.+ Ok(end.filter(|&end| decoded == text && text[end..].chars().all(char::is_whitespace)))+ }++ /// A closed root group, not merely a completed section inside an open message.+ fn completed_boundary(parser: &TokenStreamParser) -> Option<(&str, &token_stream_parser::types::Token)> {+ match parser.reduction().state().sections.last()? {+ ReductionParserSection::Group {+ name,+ close: Some(close),+ finished: true,+ ..+ } => Some((name, close)),+ _ => None,+ }+ }+}diff --git a/crates/legacy/hanashi/src/chat/hanashi/mod.rs b/crates/legacy/hanashi/src/chat/hanashi/mod.rsindex e6c1f4f8c..258674add 100644--- a/crates/legacy/hanashi/src/chat/hanashi/mod.rs+++ b/crates/legacy/hanashi/src/chat/hanashi/mod.rs@@ -1,4 +1,5 @@pub mod config;+mod continuation;mod error;pub mod messages;mod ordering;@@ -100,9 +101,7 @@ impl EncodingTrait for HanashiEncodingImpl {}self.state.messages.extend(messages.clone());- let bos_token = self.config.tokens.bos_token_id.and_then(|token_id| self.resolve_token(token_id, false).ok());- let eos_token = self.config.tokens.eos_token_id.and_then(|token_id| self.resolve_token(token_id, false).ok());- let text = self.renderer.render(&messages, true, bos_token, eos_token, None)?;+ let text = self.render_messages(&messages, true)?;let text_encoding = self.tokenizer.encode(text, false).map_err(|_| Error::UnableToEncodeText)?;tracing::debug!("Encoded tokens: {:?}", text_encoding.get_ids());for token_id in text_encoding.get_ids() {@@ -110,6 +109,7 @@ impl EncodingTrait for HanashiEncodingImpl {self.push_token_to_parser(&token, true)?;self.state.tokens.push(token);}+if self.state.messages.last().is_some_and(|message| message.role != (ChatRole::Tool {})) {// Parse from the generation prompt's open frame. Re-parsing history// can reinterpret literal markup as tool results or merge assistant@@ -136,7 +136,8 @@ impl EncodingTrait for HanashiEncodingImpl {self.validator.validate_next(&ChatRole::Assistant {})?;self.state.messages.push(ChatMessage::assistant());}- // Restore tool context after any parser reset, before extracting the reply.++ // Set tool context after any parser reset, before extraction uses it.let tools_declared = self.state.messages@@ -145,8 +146,10 @@ impl EncodingTrait for HanashiEncodingImpl {if tools_declared {self.parser.set_variable("tools", serde_json::Value::Bool(true));}+self.parser.flush_extraction();self.update_messages_from_parser_state()?;+Ok(())}@@ -174,6 +177,16 @@ impl EncodingTrait for HanashiEncodingImpl {}impl HanashiEncodingImpl {+ fn render_messages(+ &mut self,+ messages: &[ChatMessage],+ add_preamble: bool,+ ) -> Result<String, Error> {+ let bos_token = self.config.tokens.bos_token_id.and_then(|token_id| self.resolve_token(token_id, false).ok());+ let eos_token = self.config.tokens.eos_token_id.and_then(|token_id| self.resolve_token(token_id, false).ok());+ Ok(self.renderer.render(messages, add_preamble, bos_token, eos_token, None)?)+ }+pub fn tokenize(&self,text: &str,diff --git a/crates/legacy/hanashi/src/chat/hanashi/renderer/functions/to_json.rs b/crates/legacy/hanashi/src/chat/hanashi/renderer/functions/to_json.rsindex ca258325e..de137f133 100644--- a/crates/legacy/hanashi/src/chat/hanashi/renderer/functions/to_json.rs+++ b/crates/legacy/hanashi/src/chat/hanashi/renderer/functions/to_json.rs@@ -36,7 +36,7 @@ impl serde_json::ser::Formatter for SpacedJsonFormatter {}}-/// Copied from minijinja::filters::tojson with SpacedJsonFormatter+/// Serialize model prompt JSON with Python-style separators and without HTML escaping.pub fn to_json(value: &minijinja::Value,indent: Option<minijinja::Value>,@@ -69,18 +69,5 @@ pub fn to_json(.map_err(|err| {minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, "cannot serialize to JSON").with_source(err)})- .map(|s| {- // When this filter is used the return value is safe for both HTML and JSON- let mut rv = String::with_capacity(s.len());- for c in s.chars() {- match c {- '<' => rv.push_str("\\u003c"),- '>' => rv.push_str("\\u003e"),- '&' => rv.push_str("\\u0026"),- '\'' => rv.push_str("\\u0027"),- _ => rv.push(c),- }- }- minijinja::Value::from_safe_string(rv)- })+ .map(minijinja::Value::from_safe_string)}diff --git a/crates/legacy/hanashi/src/chat/hanashi/renderer/mod.rs b/crates/legacy/hanashi/src/chat/hanashi/renderer/mod.rsindex ba2903e26..6d2566699 100644--- a/crates/legacy/hanashi/src/chat/hanashi/renderer/mod.rs+++ b/crates/legacy/hanashi/src/chat/hanashi/renderer/mod.rs@@ -150,6 +150,11 @@ fn insert_into_context(#[cfg(test)]mod tests {+ use shoji::types::{+ basic::{ToolCall, Value},+ session::chat::ChatContentBlock,+ };+use super::*;use crate::chat::hanashi::config::HanashiConfig;@@ -268,6 +273,42 @@ mod tests {);}+ #[test]+ fn qwen38_tool_call_json_preserves_cached_text() {+ let renderer = renderer(HanashiConfig::Qwen38);+ let history = vec![system_message_with_effort(ReasoningEffort::Disabled), user_message()];+ let prompt = render(&renderer, history.clone());++ // Generated parameter text, including the nested edit shape from the reprefill log.+ for items in [+ r#"["<"]"#,+ r##"[{"oldText": "#include <stddef.h>", "newText": "<>&'\"\\\n\t\r\u0001", "literal": "\\u003c"}]"##,+ r#"{"nested": ["<>&'"]}"#,+ ] {+ let generated = format!(+ "<tool_call>\n<function=echo>\n<parameter=items>\n{items}\n</parameter>\n</function>\n</tool_call><|im_end|>"+ );+ let cached_text = format!("{prompt}{generated}");+ // Rebuild the assistant message from the structured arguments echoed by the client.+ let mut continuation = history.clone();+ continuation.push(ChatMessage::assistant().with_tool_call(ToolCall {+ identifier: Some("call_1".to_string()),+ name: "echo".to_string(),+ arguments: Value::from(serde_json::json!({+ "items": serde_json::from_str::<serde_json::Value>(items).unwrap()+ })),+ }));+ continuation.push(ChatMessage::tool().with_block(ChatContentBlock::ToolCallResult {+ identifier: Some("call_1".to_string()),+ name: Some("echo".to_string()),+ value: Value::from(serde_json::json!("ok")),+ }));++ let rendered = render(&renderer, continuation);+ assert!(rendered.starts_with(&cached_text), "cached prefix changed for {items}: {rendered}");+ }+ }+#[test]fn qwen38_capabilities_report_levels() {let capabilities = HanashiConfig::Qwen38.capabilities().unwrap();diff --git a/crates/legacy/hanashi/src/chat/mod.rs b/crates/legacy/hanashi/src/chat/mod.rsindex f3abb2a11..ebfc296b3 100644--- a/crates/legacy/hanashi/src/chat/mod.rs+++ b/crates/legacy/hanashi/src/chat/mod.rs@@ -38,6 +38,16 @@ pub enum Encoding {}impl Encoding {+ pub fn try_append(+ &mut self,+ messages: &[ChatMessage],+ ) -> Result<Option<Vec<TokenId>>, Error> {+ match self {+ Self::Hanashi(inner) => inner.try_append(messages).map_err(Into::into),+ Self::Harmony(_) => Ok(None),+ }+ }+pub fn tokenize(&self,text: &str,diff --git a/crates/legacy/hanashi/tests/test_continuation.rs b/crates/legacy/hanashi/tests/test_continuation.rsnew file mode 100644index 000000000..a1fbf611b--- /dev/null+++ b/crates/legacy/hanashi/tests/test_continuation.rs@@ -0,0 +1,270 @@+use std::sync::Arc;++use hanashi::{+ Encoding as _,+ chat::hanashi::{HanashiEncodingImpl, config::HanashiConfig},+};+use shoji::types::{+ basic::{ReasoningEffort, ToolDescription, ToolFunction, ToolNamespace, Value},+ session::chat::{ChatContentBlock, ChatMessage, ChatRole},+};+use tokenizers::{AddedToken, Tokenizer, models::bpe::BPE, pre_tokenizers::byte_level::ByteLevel};++fn encoding(config: HanashiConfig) -> HanashiEncodingImpl {+ let mut config = config.resolve().unwrap();+ let mut alphabet: Vec<_> = ByteLevel::alphabet().into_iter().collect();+ alphabet.sort_unstable();+ let vocabulary: [(String, u32); 256] = alphabet+ .into_iter()+ .enumerate()+ .map(|(index, value)| (value.to_string(), index as u32))+ .collect::<Vec<_>>()+ .try_into()+ .unwrap();+ let model = BPE::builder().vocab_and_merges(vocabulary, Vec::new()).build().unwrap();+ let mut tokenizer = Tokenizer::new(model);+ tokenizer.with_pre_tokenizer(Some(ByteLevel::new(false, false, false)));+ tokenizer.with_decoder(Some(ByteLevel::new(false, false, false)));+ tokenizer.add_tokens(+ &["system", "user", "assistant", "tool", "model", "inspect"].map(|value| AddedToken::from(value, false)),+ );+ let mut markers = config.parsing.framing_config().tokens;+ markers.extend(["<bos>".to_string(), "<eos>".to_string()]);+ tokenizer.add_special_tokens(&markers.into_iter().map(|value| AddedToken::from(value, true)).collect::<Vec<_>>());+ config.tokens.bos_token_id = tokenizer.token_to_id("<bos>");+ config.tokens.eos_token_id = tokenizer.token_to_id("<eos>");+ HanashiEncodingImpl::new(+ HanashiConfig::Custom {+ config,+ },+ Arc::new(tokenizer),+ )+ .unwrap()+}++fn decode(+ encoding: &mut HanashiEncodingImpl,+ text: &str,+) {+ for id in encoding.tokenize(text).unwrap() {+ // Sample a valid alternative tokenization, as an autoregressive model can.+ if encoding.tokenize("inspect").unwrap() == [id] {+ for character in "inspect".chars() {+ let id = encoding.tokenize(&character.to_string()).unwrap()[0];+ encoding.decode(vec![id]).unwrap();+ }+ } else {+ encoding.decode(vec![id]).unwrap();+ }+ }+}++fn tool_call(options: &str) -> String {+ format!("<tool_call>\n<function=inspect>\n<parameter=options>\n{options}\n</parameter>\n</function>\n</tool_call>")+}++fn history() -> Vec<ChatMessage> {+ vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::developer().with_block(ChatContentBlock::Tools {+ namespaces: vec![ToolNamespace {+ name: "functions".to_string(),+ description: None,+ tools: vec![ToolDescription::Function {+ tool_function: ToolFunction {+ name: "inspect".to_string(),+ description: String::new(),+ parameters: Some(Value::from(serde_json::json!({"type": "object"}))),+ return_definition: None,+ },+ }],+ }],+ }),+ ChatMessage::user().with_text("Inspect the repository.".to_string()),+ ]+}++fn add_tool_result(+ encoding: &HanashiEncodingImpl,+ history: &mut Vec<ChatMessage>,+) {+ let mut assistant = encoding.state().messages.last().unwrap().clone();+ let ChatContentBlock::ToolCall {+ value,+ } = assistant.content.last_mut().unwrap()+ else {+ panic!("expected a tool call");+ };+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&value.arguments.json).unwrap(),+ serde_json::json!({"options": {"a": 1, "b": 2}})+ );+ // Nagare assigns an ID after parsing; it is absent from the sampled encoding.+ value.identifier = Some(format!("call-{}", history.len()));+ let identifier = value.identifier.clone();+ history.push(assistant);+ history.push(ChatMessage::tool().with_block(ChatContentBlock::ToolCallResult {+ identifier,+ name: Some("inspect".to_string()),+ value: Value::from(serde_json::json!("done")),+ }));+}++#[test]+fn formatting_and_sampled_token_ids_survive_repeated_tool_continuations() {+ for config in [HanashiConfig::Qwen35, HanashiConfig::Qwen36, HanashiConfig::Qwen38] {+ for options in [r#"{"a":1,"b":2}"#, r#"{"a":1, "b": 2}"#, "{\n \"b\": 2,\n \"a\": 1\n}"] {+ let mut encoding = encoding(config.clone());+ let mut history = history();+ encoding.encode(history.clone()).unwrap();+ for _ in 0..3 {+ decode(&mut encoding, &(tool_call(options) + "<|im_end|>"));+ let sampled = encoding.state().tokens.clone();+ let sampled_text = encoding.state().text();+ assert_ne!(+ sampled.iter().map(|token| token.id).collect::<Vec<_>>(),+ encoding.tokenize(&sampled_text).unwrap()+ );+ add_tool_result(&encoding, &mut history);+ let canonical = canonical_text(config.clone(), history.clone());+ assert!(!canonical.starts_with(&sampled_text));++ let suffix = encoding.try_append(&history).unwrap().expect("must reuse the sampled prefix");++ assert_eq!(&encoding.state().tokens[..sampled.len()], sampled);+ assert_eq!(+ encoding.state().tokens[sampled.len()..].iter().map(|token| token.id).collect::<Vec<_>>(),+ suffix+ );+ assert_eq!(+ &encoding.state().text()[sampled_text.len()..],+ "\n<|im_start|>user\n<tool_response>\ndone\n</tool_response><|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"+ );+ assert!(matches!(encoding.state().messages.last().unwrap().role, ChatRole::Assistant {}));+ }+ }+ }+}++#[test]+fn edited_history_and_render_context_are_rejected_without_mutation() {+ let mut encoding = encoding(HanashiConfig::Qwen38);+ let mut history = history();+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history);+ let original = encoding.state().clone();+ let mut edited = history.clone();+ edited[2] = ChatMessage::user().with_text("Different request.".to_string());+ assert!(encoding.try_append(&edited).unwrap().is_none());+ assert_eq!(*encoding.state(), original);+ let mut edited = history.clone();+ edited[0] = ChatMessage::system().with_reasoning_effort(ReasoningEffort::Default);+ assert!(encoding.try_append(&edited).unwrap().is_none());+ assert_eq!(*encoding.state(), original);+ let mut edited = history.clone();+ let ChatContentBlock::Tools {+ namespaces,+ } = &mut edited[1].content[0]+ else {+ unreachable!()+ };+ let ToolDescription::Function {+ tool_function,+ } = &mut namespaces[0].tools[0];+ tool_function.description = "Changed tool description.".to_string();+ assert!(encoding.try_append(&edited).unwrap().is_none());+ assert_eq!(*encoding.state(), original);+ // A rejected attempt must not poison a later valid continuation.+ assert!(encoding.try_append(&history).unwrap().is_some());+}++#[test]+fn partial_messages_and_unparsed_calls_are_rejected() {+ for tail in [tool_call(r#"{"a":1,"b":2}"#), "<tool_call>broken</tool_call><|im_end|>".to_string()] {+ let mut encoding = encoding(HanashiConfig::Qwen35);+ let mut history = history();+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, &tail);+ history.push(encoding.state().messages.last().unwrap().clone());+ history.push(ChatMessage::user().with_text("Continue.".to_string()));+ let original = encoding.state().clone();+ assert!(encoding.try_append(&history).unwrap().is_none());+ assert_eq!(*encoding.state(), original);+ }+}++#[test]+fn different_message_delimiters_and_bos_are_supported() {+ let mut encoding = encoding(HanashiConfig::Gemma3);+ let mut history = vec![ChatMessage::user().with_text("Hello.".to_string())];+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, " Hello! <end_of_turn>");+ let sampled = encoding.state().tokens.clone();+ history.push(encoding.state().messages.last().unwrap().clone());+ history.push(ChatMessage::user().with_text("Continue.".to_string()));+ let canonical = canonical_text(HanashiConfig::Gemma3, history.clone());+ assert!(!canonical.starts_with(&encoding.state().text()));+ assert!(encoding.try_append(&history).unwrap().is_some());+ assert_eq!(&encoding.state().tokens[..sampled.len()], sampled);+ assert!(encoding.state().text().ends_with("\n<start_of_turn>user\nContinue.<end_of_turn>\n<start_of_turn>model\n"));+}++fn canonical_text(+ config: HanashiConfig,+ history: Vec<ChatMessage>,+) -> String {+ let mut encoding = encoding(config);+ encoding.encode(history).unwrap();+ encoding.state().text()+}++#[test]+fn context_dependent_rewriting_of_previous_reasoning_is_rejected() {+ let mut config = HanashiConfig::Qwen38.resolve().unwrap();+ config.rendering.jinja.template.insert_str(0, "{%- set preserve_thinking = false %}");+ let config = HanashiConfig::Custom {+ config,+ };+ let mut encoding = encoding(config.clone());+ let mut history = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Default),+ ChatMessage::user().with_text("Say hello.".to_string()),+ ];+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, "Some thought.\n</think>\n\nHello.<|im_end|>");+ history.push(encoding.state().messages.last().unwrap().clone());+ history.push(ChatMessage::user().with_text("Another question.".to_string()));+ let original = encoding.state().clone();+ assert!(original.text().contains("Some thought."));+ assert!(!canonical_text(config, history.clone()).contains("Some thought."));+ assert!(encoding.try_append(&history).unwrap().is_none());+ assert_eq!(*encoding.state(), original);+}++#[test]+fn reasoning_mode_change_that_only_affects_suffix_can_reuse_prefix() {+ let mut encoding = encoding(HanashiConfig::Qwen35);+ let mut history = history();+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history);+ history[0] = ChatMessage::system().with_reasoning_effort(ReasoningEffort::Default);+ let sampled = encoding.state().tokens.clone();+ assert!(encoding.try_append(&history).unwrap().is_some());+ assert_eq!(&encoding.state().tokens[..sampled.len()], sampled);+ assert!(encoding.state().text().ends_with("<|im_start|>assistant\n<think>\n"));+}++#[test]+fn unicode_survives_prefix_boundary_detection() {+ let mut encoding = encoding(HanashiConfig::Qwen38);+ let mut history = history();+ history[2] = ChatMessage::user().with_text("Проверь репозиторий 🦀".to_string());+ encoding.encode(history.clone()).unwrap();+ decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history);+ let sampled = encoding.state().tokens.clone();+ assert!(encoding.try_append(&history).unwrap().is_some());+ assert_eq!(&encoding.state().tokens[..sampled.len()], sampled);+}diff --git a/crates/legacy/nagare/src/chat/token.rs b/crates/legacy/nagare/src/chat/token.rsindex 47450d30e..35cbb634b 100644--- a/crates/legacy/nagare/src/chat/token.rs+++ b/crates/legacy/nagare/src/chat/token.rs@@ -131,51 +131,9 @@ impl Session {) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {let time_start = Instant::now();- let curr_all_tokens = self.encoding.state().tokens.clone();- let new_all_tokens = match self.build_input(input) {- Ok(input) => input,- Err(err) => {- return error_stream(ChatSessionError::Backend {- message: err.to_string(),- });- },- };-- // The engine state can only be kept whole or reset, so reuse it whenever the session's- // text is a prefix of the newly rendered text — even if tokenizations differ, as sampled- // replies are not canonically tokenized — and prefill only the raw-tokenized text suffix.- let curr_text = curr_all_tokens.iter().fold(String::new(), |mut text, token| {- text.push_str(&token.value);- text- });- let new_text = self.encoding.state().tokens.iter().fold(String::new(), |mut text, token| {- text.push_str(&token.value);- text- });- let reset = !new_text.starts_with(&curr_text);- let cached_tokens_input = if reset {- 0- } else {- curr_all_tokens.len()- };- self.input_tokens = if reset {- if let Err(err) = self.state_reset().await {- return error_stream(err);- }- tracing::debug!(- "Reprefill: {}",- describe_reprefill(&curr_all_tokens, &self.encoding.state().tokens, &curr_text, &new_text)- );- new_all_tokens- } else {- match self.encoding.tokenize(&new_text[curr_text.len()..]) {- Ok(suffix_tokens) => suffix_tokens.into_iter().map(u64::from).collect(),- Err(err) => {- return error_stream(ChatSessionError::Backend {- message: err.to_string(),- });- },- }+ let cached_tokens_input = match self.prepare_input(input).await {+ Ok(cached_tokens) => cached_tokens,+ Err(error) => return error_stream(error),};let instance = self.instance.as_ref();@@ -251,6 +209,38 @@ impl Session {Ok(())}+ async fn prepare_input(+ &mut self,+ messages: &[ChatMessage],+ ) -> Result<usize, ChatSessionError> {+ let cached = self.encoding.state().tokens.clone();+ if let Some(suffix) = self.encoding.try_append(messages).map_err(|error| ChatSessionError::Backend {+ message: error.to_string(),+ })? {+ self.input_tokens = suffix.into_iter().map(u64::from).collect();+ return Ok(cached.len());+ }++ let rendered_ids = self.build_input(messages)?;+ let cached_ids: Vec<_> = cached.iter().map(|token| u64::from(token.id)).collect();+ // Without an append operation preserving the sampled encoding, the newly+ // built encoding can describe the live backend only if token IDs match.+ if rendered_ids.starts_with(&cached_ids) {+ self.input_tokens = rendered_ids[cached_ids.len()..].to_vec();+ return Ok(cached_ids.len());+ }++ self.state_reset().await?;+ let cached_text: String = cached.iter().map(|token| token.value.as_str()).collect();+ let rendered_text = self.encoding.state().text();+ tracing::warn!(+ "Reprefill: {}",+ describe_reprefill(&cached, &self.encoding.state().tokens, &cached_text, &rendered_text)+ );+ self.input_tokens = rendered_ids;+ Ok(0)+ }+fn build_input(&mut self,all_messages: &[ChatMessage],@@ -372,7 +362,9 @@ fn describe_reprefill() -> String {let text_difference = cached_text.bytes().zip(rendered_text.bytes()).take_while(|(a, b)| a == b).count();let token_difference = cached.iter().zip(rendered).take_while(|(a, b)| a.id == b.id).count();- let reason = if cached_text.starts_with(rendered_text) {+ let reason = if rendered_text.starts_with(cached_text) {+ "rendered token IDs changed"+ } else if cached_text.starts_with(rendered_text) {"rendered prompt is shorter than cached text"} else {"rendered text changed"diff --git a/crates/legacy/uzu/Cargo.toml b/crates/legacy/uzu/Cargo.tomlindex bab0b153b..60e7012df 100644--- a/crates/legacy/uzu/Cargo.toml+++ b/crates/legacy/uzu/Cargo.toml@@ -135,6 +135,7 @@ schemars.workspace = trueserde_json.workspace = truemock-registry.workspace = truerstest.workspace = true+test-tag.workspace = true[[test]]name = "tool"diff --git a/crates/legacy/uzu/tests/tool/calls.rs b/crates/legacy/uzu/tests/tool/calls.rsindex 188ef292e..39c1fa624 100644--- a/crates/legacy/uzu/tests/tool/calls.rs+++ b/crates/legacy/uzu/tests/tool/calls.rs@@ -129,7 +129,12 @@ async fn run_tool_calls_test(let mut messages = Vec::new();if with_system_message {- messages.push(ChatMessage::system().with_text("You are a helpful assistant".to_string()));+ // Make tool use and dependency resolution explicit for small models.+ messages.push(+ ChatMessage::system().with_text(+ "You are a helpful assistant. Use the available tools to answer the user's request. If a tool needs information provided by another tool, call that tool first.".to_string(),+ ),+ );}messages.push(ChatMessage::user().with_text(case.prompt.to_string()));@@ -192,6 +197,7 @@ async fn run_tool_calls_test(}}+#[test_tag::tag(heavy)]#[tokio::test]async fn lfm2_5_350m() {run_tool_calls_test("trymirai/LFM2.5-350M-L", true, false, &TEST_CASES[..1]).await;@@ -203,6 +209,7 @@ async fn muse_glimmer_30b_m() {run_tool_calls_test("trymirai/Muse-Glimmer-30B-M", true, false, TEST_CASES).await;}+#[test_tag::tag(heavy)]#[tokio::test]async fn qwen3_5_0_8b() {run_tool_calls_test("trymirai/Qwen3.5-0.8B-M", true, false, TEST_CASES).await;