Bug fixes (from review/README.md): - Apply config sampling defaults field-by-field, so an absent temperature no longer means greedy; expose top_k/min_p/repetition_penalty on ChatRequest; top_k=0 is "disabled" (-> 64), not greedy. - Fix cross-request abort race: Engine::request_stop() sets the cancel flag only; the owning generate loop does STOP+drain itself, instead of a spawned abort() that could hit a later request holding the lock. - Initialize tracing-subscriber (RUST_LOG, default info); events were dropped. - TempFilesGuard removes materialized images on every exit path (error/panic/drop); build_prompt runs in spawn_blocking off the async worker; ureq image fetch gets a 15s timeout, a 32MB cap and a basic SSRF guard (literal loopback/private hosts). - Non-blocking shutdown (STOP+QUIT without taking the request lock first) and a bounded drain_to_done that marks the engine dead on timeout. Operational hardening: - Graceful shutdown on SIGTERM as well as SIGINT. - Warn when binding a non-loopback address (no auth, allowed_hosts not enforced). - Configurable startup/silence timeouts (optional config keys, default 600s). Docs: - Add README.md (English): what strata-ctl is, why Rust for stable server use, architecture, usage, honest status, and credits to Strata / Niko1221. 76 tests green + 2 real-file ignored; clippy clean; cargo fmt applied. Deferred (heavy): automatic engine restart after a crash.
271 lines
9.2 KiB
Rust
271 lines
9.2 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);
|
|
}
|