Files
strata-ctl/tests/inkling_formatter.rs
T
adm a52bec97d4 Sliding window 30+20 + GEN 0 cache pre-warm (pre-warm-on-change)
Window: MAIN_AREA 30 + BUFFER 20 (same 50 cap) halves rotation frequency. context: shared compose_prefix (byte-exact prefix of compose) + notepad_fingerprint (rendered header body, excludes updated_at). inkling: build_prefix_ids renders without finish_prompt. service: prewarm() sends GEN 0 directly (no PerfMeter/DB). sessions: schedule_prewarm at turn end on pending rotation OR notepad-dirty (ws=0 normalized); session_chat loads only the window subset.

examples/prewarm_bench.rs: joint GEN 0 -> RESUME bench, PASS on HIP (cached==L==385). Verified live all-agent: notepad write -> pre-warm 1468 -> next turn cached_tokens==1468. Tests: prefix property, opener-skip, GEN 0 primitive, notepad fingerprint. Suite 162 passed + 3 ignored.
2026-11-26 19:12:59 +01:00

318 lines
11 KiB
Rust

//! End-to-end test of the assembled InklingFormatter: prompt build (template +
//! encode) and output decode (detok + channel dialect -> API pieces), using a
//! host-independent fixture tokenizer whose decoder concatenates without spaces
//! (like the real ByteLevel decoder), so channel tags match exactly.
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::json;
use tokenizers::decoders::fuse::Fuse;
use tokenizers::models::wordlevel::WordLevel;
use tokenizers::{AddedToken, Tokenizer};
use strata_ctl::api::formatter::{Formatter, Piece};
use strata_ctl::api::types::ChatRequest;
use strata_ctl::engine::Sampling;
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn fixture_tokenizer() -> (Arc<InklingTokenizer>, std::path::PathBuf) {
let mut vocab = HashMap::new();
vocab.insert("think".to_string(), 0u32);
vocab.insert("answer".to_string(), 1u32);
vocab.insert("hello".to_string(), 2u32);
vocab.insert("[UNK]".to_string(), 3u32);
vocab.insert(TOOL_BODY.to_string(), 4u32);
let model = WordLevel::builder()
.vocab(vocab.into_iter().collect())
.unk_token("[UNK]".to_string())
.build()
.unwrap();
let mut tok = Tokenizer::new(model);
// no pre-tokenizer: each whole segment maps to one vocab word (the JSON tool
// body must not be split on punctuation), specials still match via the trie
tok.with_pre_tokenizer(None::<tokenizers::pre_tokenizers::PreTokenizerWrapper>);
// concatenate without separators, mirroring the real ByteLevel decoder
tok.with_decoder(Some(Fuse::new()));
let _ = tok.add_special_tokens([
AddedToken::from("<|message_model|>", true),
AddedToken::from("<|content_thinking|>", true),
AddedToken::from("<|content_text|>", true),
AddedToken::from("<|end_message|>", true),
AddedToken::from("<|content_model_end_sampling|>", true),
AddedToken::from("<|content_invoke_tool_json|>", true),
]);
let path = std::env::temp_dir().join(format!(
"strata-ctl-fmt-{}-{}.json",
std::process::id(),
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
tok.save(&path, false).unwrap();
(Arc::new(InklingTokenizer::from_file(&path).unwrap()), path)
}
const TEMPLATE: &str =
"{%- for m in messages -%}<|content_text|>{{ m.content }}<|end_message|>{%- endfor -%}";
/// A tool-call body as one whitespace-free word (the fixture is WordLevel).
const TOOL_BODY: &str = r#"{"name":"get_weather","args":{"city":"Roma"}}"#;
fn formatter() -> (InklingFormatter, Arc<InklingTokenizer>, std::path::PathBuf) {
let (tok, path) = fixture_tokenizer();
let template = ChatTemplate::new(TEMPLATE).unwrap();
let fmt = InklingFormatter::new(
tok.clone(),
template,
"test-model".into(),
Some("low".into()),
Sampling::default(),
);
(fmt, tok, path)
}
#[test]
fn build_prompt_renders_and_encodes() {
let (fmt, tok, path) = formatter();
let req: ChatRequest = serde_json::from_value(
json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}),
)
.unwrap();
let prompt = fmt.build_prompt(&req).unwrap();
// the rendered prompt is "<|content_text|>hello<|end_message|>"
let text_id = tok.encode("<|content_text|>").unwrap()[0];
let end_id = tok.encode("<|end_message|>").unwrap()[0];
assert!(prompt.ids.contains(&text_id));
assert!(prompt.ids.contains(&2)); // "hello"
assert!(prompt.ids.contains(&end_id));
assert_eq!(prompt.max_new, 2048); // default
let _ = std::fs::remove_file(&path);
}
#[test]
fn decoder_splits_reasoning_and_content() {
let (fmt, tok, path) = formatter();
let mut dec = fmt.decoder();
// a scripted assistant reply: thinking, then the answer
let script = [
"<|message_model|>",
"<|content_thinking|>",
"think",
"<|end_message|>",
"<|message_model|>",
"<|content_text|>",
"answer",
"<|end_message|>",
];
let mut reasoning = String::new();
let mut content = String::new();
for seg in script {
for id in tok.encode(seg).unwrap() {
for p in dec.push(id) {
match p {
Piece::Reasoning(s) => reasoning.push_str(&s),
Piece::Content(s) => content.push_str(&s),
Piece::ToolCall { .. } => {}
}
}
}
}
for p in dec.finish(None) {
match p {
Piece::Reasoning(s) => reasoning.push_str(&s),
Piece::Content(s) => content.push_str(&s),
Piece::ToolCall { .. } => {}
}
}
assert_eq!(reasoning, "think");
assert_eq!(content, "answer");
let _ = std::fs::remove_file(&path);
}
#[test]
fn max_tokens_override_is_honored() {
let (fmt, _tok, path) = formatter();
let req: ChatRequest = serde_json::from_value(json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hello"}],
"max_tokens": 77
}))
.unwrap();
assert_eq!(fmt.build_prompt(&req).unwrap().max_new, 77);
let _ = std::fs::remove_file(&path);
}
#[test]
fn decoder_emits_structured_tool_call() {
let (fmt, tok, path) = formatter();
let mut dec = fmt.decoder();
// assistant opens a JSON tool channel, emits the call body, closes it
let script = [
"<|message_model|>",
"<|content_invoke_tool_json|>",
TOOL_BODY,
"<|end_message|>",
];
let mut calls: Vec<(String, String)> = Vec::new();
let mut content = String::new();
for seg in script {
for id in tok.encode(seg).unwrap() {
for p in dec.push(id) {
match p {
Piece::ToolCall { name, arguments } => calls.push((name, arguments)),
Piece::Content(s) => content.push_str(&s),
Piece::Reasoning(_) => {}
}
}
}
}
for p in dec.finish(None) {
if let Piece::ToolCall { name, arguments } = p {
calls.push((name, arguments));
}
}
assert_eq!(calls.len(), 1, "content was: {content}");
assert_eq!(calls[0].0, "get_weather");
assert_eq!(calls[0].1, r#"{"city":"Roma"}"#);
// the raw frame must NOT leak into content
assert!(content.is_empty(), "frame leaked into content: {content}");
let _ = std::fs::remove_file(&path);
}
#[test]
fn tool_choice_forcing_is_rejected() {
let (fmt, _tok, path) = formatter();
for choice in [
json!("required"),
json!({"type": "function", "function": {"name": "f"}}),
json!("bogus"),
] {
let req: ChatRequest = serde_json::from_value(json!({
"model": "m",
"messages": [{"role": "user", "content": "hello"}],
"tool_choice": choice
}))
.unwrap();
assert!(
fmt.build_prompt(&req).is_err(),
"choice {choice} should be rejected"
);
}
let _ = std::fs::remove_file(&path);
}
#[test]
fn tool_choice_none_and_auto_accepted() {
let (fmt, _tok, path) = formatter();
for choice in [json!("none"), json!("auto")] {
let req: ChatRequest = serde_json::from_value(json!({
"model": "m",
"messages": [{"role": "user", "content": "hello"}],
"tools": [{"type": "function", "function": {"name": "f"}}],
"tool_choice": choice
}))
.unwrap();
assert!(
fmt.build_prompt(&req).is_ok(),
"choice {choice} should be accepted"
);
}
let _ = std::fs::remove_file(&path);
}
#[test]
fn config_sampling_defaults_are_applied_and_overridable() {
let (tok, path) = fixture_tokenizer();
let template = ChatTemplate::new(TEMPLATE).unwrap();
let defaults = Sampling {
temperature: Some(0.7),
top_p: Some(0.9),
min_p: Some(0.05),
repetition_penalty: Some(1.1),
..Default::default()
};
let fmt = InklingFormatter::new(
tok.clone(),
template,
"test-model".into(),
Some("low".into()),
defaults,
);
// request omits every knob -> config defaults apply (not greedy)
let req: ChatRequest = serde_json::from_value(
json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}),
)
.unwrap();
let s = fmt.build_prompt(&req).unwrap().sampling;
assert_eq!(s.temperature, Some(0.7));
assert_eq!(s.top_p, Some(0.9));
assert_eq!(s.min_p, Some(0.05));
assert_eq!(s.repetition_penalty, Some(1.1));
// a per-request knob wins; the others still fall back to the defaults
let req2: ChatRequest = serde_json::from_value(json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hello"}],
"temperature": 0.2,
"top_k": 0
}))
.unwrap();
let s2 = fmt.build_prompt(&req2).unwrap().sampling;
assert_eq!(s2.temperature, Some(0.2));
assert_eq!(s2.top_p, Some(0.9));
assert_eq!(s2.top_k, Some(0)); // carried through; keys() maps 0 -> 64
assert!(s2.keys().contains("top_k=64"));
let _ = std::fs::remove_file(&path);
}
#[test]
fn build_prefix_ids_skips_opener_and_is_token_prefix() {
let (tok, path) = fixture_tokenizer();
// A template emitting the effort-none line, so finish_prompt WOULD append the
// generation opener on build_prompt; build_prefix_ids must skip it.
let tmpl = ChatTemplate::new(
"{%- for m in messages -%}{%- if loop.first -%}<|content_text|>Thinking effort level: 0<|end_message|>{%- endif -%}<|content_text|>{{ m.content }}<|end_message|>{%- endfor -%}",
)
.unwrap();
let fmt = InklingFormatter::new(
tok.clone(),
tmpl,
"m".into(),
Some("none".into()),
Sampling::default(),
);
let prefix_req: ChatRequest = serde_json::from_value(json!({
"model": "m",
"messages": [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "answer"}
]
}))
.unwrap();
let full_req: ChatRequest = serde_json::from_value(json!({
"model": "m",
"messages": [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "answer"},
{"role": "user", "content": "hello"}
]
}))
.unwrap();
let prefix_ids = fmt.build_prefix_ids(&prefix_req).unwrap();
let full_ids = fmt.build_prompt(&full_req).unwrap().ids;
// The pre-warm ids are a byte-exact token prefix of the real turn's ids (the
// message boundary is a special token, so the BPE/WordLevel span never merges
// across it).
assert!(full_ids.len() > prefix_ids.len());
assert_eq!(&full_ids[..prefix_ids.len()], &prefix_ids[..]);
// build_prompt on the SAME prefix appends the opener -> longer than the
// prefix-only build (this is exactly what the pre-warm must NOT include).
let prefix_with_opener = fmt.build_prompt(&prefix_req).unwrap().ids;
assert!(prefix_with_opener.len() > prefix_ids.len());
let _ = std::fs::remove_file(&path);
}