strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)

From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
This commit is contained in:
adm committed 2026-11-24 05:28:56 +01:00
commit 597ac432e1
30 files changed
+7541

No files matched your search

+340
View File
@@ -0,0 +1,340 @@
//! End-to-end tests of the OpenAI surface: HTTP request -> engine (mock) ->
//! HTTP response, non-stream and stream, driven through a trivial formatter so
//! the whole API layer is exercised without the real tokenizer.
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode};
use tower::ServiceExt; // for `oneshot`
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
use strata_ctl::api::service::ChatService;
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
use strata_ctl::engine::Engine;
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
/// A formatter with no dialect: the prompt is the last message's bytes; each
/// token id < 256 decodes to that byte as a char, always as "content".
struct ByteFormatter;
impl Formatter for ByteFormatter {
fn model_name(&self) -> &str {
"test-model"
}
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let text = req
.messages
.iter()
.rev()
.find_map(|m| m.text())
.unwrap_or("")
.to_string();
Ok(Prompt {
ids: text.bytes().map(u32::from).collect(),
max_new: req.max_new(64),
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
struct ByteDecoder;
impl Decoder for ByteDecoder {
fn push(&mut self, id: u32) -> Vec<Piece> {
if id < 256 {
vec![Piece::Content(char::from(id as u8).to_string())]
} else {
Vec::new()
}
}
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
Vec::new()
}
}
/// Drives the mock's long, STOP-interruptible generation (ids contain 888888).
struct LongFormatter;
impl Formatter for LongFormatter {
fn model_name(&self) -> &str {
"test-model"
}
fn build_prompt(&self, _req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
Ok(Prompt {
ids: vec![888888],
max_new: 100000,
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
async fn build_app() -> axum::Router {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
strata_ctl::api::router(svc)
}
async fn post_json(app: &axum::Router, body: serde_json::Value) -> (StatusCode, String) {
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(body.to_string()))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
#[tokio::test]
async fn models_lists_the_served_model() {
let app = build_app().await;
let resp = app
.oneshot(
Request::builder()
.uri("/v1/models")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["object"], "list");
assert_eq!(json["data"][0]["id"], "test-model");
}
#[tokio::test]
async fn non_stream_completion() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}]
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["object"], "chat.completion");
// the mock's default path emits ids 101..105 -> 'e','f','g','h','i'
assert_eq!(json["choices"][0]["message"]["content"], "efghi");
assert_eq!(json["choices"][0]["message"]["role"], "assistant");
assert_eq!(json["choices"][0]["finish_reason"], "stop");
assert_eq!(json["usage"]["completion_tokens"], 5);
assert_eq!(
json["usage"]["total_tokens"],
json["usage"]["prompt_tokens"].as_u64().unwrap() + 5
);
assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-"));
}
#[tokio::test]
async fn stream_completion_is_sse() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stream": true
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
// every payload line is `data: ...`; the stream ends with `data: [DONE]`
let data_lines: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert!(
data_lines.last().copied() == Some("[DONE]"),
"no [DONE]: {text}"
);
// first chunk announces the role, the last (before [DONE]) the finish reason
let first: serde_json::Value = serde_json::from_str(data_lines[0]).unwrap();
assert_eq!(first["object"], "chat.completion.chunk");
assert_eq!(first["choices"][0]["delta"]["role"], "assistant");
// reassemble content across the middle chunks
let mut content = String::new();
let mut finish = None;
for line in &data_lines[..data_lines.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
content.push_str(c);
}
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
finish = Some(f.to_string());
}
}
assert_eq!(content, "efghi");
assert_eq!(finish.as_deref(), Some("stop"));
}
#[tokio::test]
async fn empty_messages_is_bad_request() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({"model": "test-model", "messages": []}),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["error"]["type"], "invalid_request_error");
}
#[tokio::test]
async fn malformed_json_is_openai_error() {
let app = build_app().await;
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from("{not json"))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert!(json["error"]["message"]
.as_str()
.unwrap()
.contains("invalid JSON"));
}
#[tokio::test]
async fn stream_aborts_on_client_disconnect() {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine.clone(), Arc::new(LongFormatter));
let app = strata_ctl::api::router(svc);
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "go"}],
"stream": true
})
.to_string(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Simulate the client vanishing: drop the SSE body without reading it. The
// receiver is dropped, the disconnect select fires, the engine is aborted.
drop(resp);
// Poll (non-mutating) until the engine is idle: the long generation must
// have been stopped, not left running for the full 100000 tokens. Bounded
// wait so the test is robust under parallel load.
let mut idle = false;
for _ in 0..100 {
if engine.is_idle() {
idle = true;
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
assert!(idle, "engine still busy after client disconnect");
let _ = engine.shutdown().await;
}
#[tokio::test]
async fn stop_sequence_truncates_content() {
let app = build_app().await;
// the mock's default answer is "efghi"; stop "gh" cuts it to "ef"
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stop": ["gh"]
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["choices"][0]["message"]["content"], "ef");
assert_eq!(json["choices"][0]["finish_reason"], "stop");
}
#[tokio::test]
async fn stop_sequence_truncates_stream() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stop": ["gh"],
"stream": true
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let data_lines: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert_eq!(data_lines.last().copied(), Some("[DONE]"));
let mut content = String::new();
let mut finish = None;
for line in &data_lines[..data_lines.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
content.push_str(c);
}
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
finish = Some(f.to_string());
}
}
assert_eq!(content, "ef");
assert_eq!(finish.as_deref(), Some("stop"));
}
+121
View File
@@ -0,0 +1,121 @@
//! End-to-end tests of the supervisor against a scripted mock engine
//! (tests/mock_engine.py), which speaks the protocol exactly as `strata
//! --serve` prints it.
use std::time::Duration;
use strata_ctl::engine::{Engine, EngineError, EngineLine, Sampling};
fn mock() -> (String, Vec<String>) {
let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
(
"python3".into(),
vec![script.into(), "--marker".to_string()],
)
}
async fn start_mock() -> Engine {
let (exe, args) = mock();
Engine::start(&exe, &args[0..1], None, Duration::from_secs(10))
.await
.expect("mock engine starts")
}
#[tokio::test]
async fn start_reads_ready() {
let engine = start_mock().await;
let ready = engine.ready();
assert_eq!(ready.max_context, 8192);
assert!(ready.can_stop);
assert!(ready.can_hold);
assert!(!ready.can_hold_batch);
assert_eq!(
engine.info().await.get("version").map(String::as_str),
Some("0.0.0-mock")
);
engine.shutdown().await.unwrap();
}
#[tokio::test]
async fn generate_streams_and_finishes() {
let engine = start_mock().await;
let mut seen = Vec::new();
let out = engine
.generate(16, &Sampling::default(), &[1, 2, 3, 4], |line| {
if let EngineLine::Prefill { read, total, .. } = line {
seen.push((*read, *total));
}
})
.await
.unwrap();
assert_eq!(out.tokens, vec![101, 102, 103, 104, 105]);
assert_eq!(out.resumed, 1);
assert_eq!(seen, vec![(2, 4)]);
let done = out.done.unwrap();
assert_eq!((done.generated, done.prompt_tokens), (5, 4));
assert_eq!(done.finish, "stop");
assert_eq!(done.extra, ["3", "4", "1"]);
engine.shutdown().await.unwrap();
}
#[tokio::test]
async fn refusal_is_reported_and_trailing_done_swallowed() {
let engine = start_mock().await;
let err = engine
.generate(8, &Sampling::default(), &[1, 999999], |_| {})
.await
.unwrap_err();
assert!(matches!(&err, EngineError::Refused(m) if m.contains("out of range")));
// the mock printed a DONE after the ERR: it must not leak to the next request
let out = engine
.generate(8, &Sampling::default(), &[1, 2], |_| {})
.await
.unwrap();
assert_eq!(out.tokens.len(), 5);
engine.shutdown().await.unwrap();
}
#[tokio::test]
async fn abort_reaches_a_running_request_and_frees_the_wires() {
let exe_mock = mock();
let engine = std::sync::Arc::new(
Engine::start(
&exe_mock.0,
&[exe_mock.1[0].clone()],
None,
Duration::from_secs(10),
)
.await
.unwrap(),
);
let holder = {
let engine = engine.clone();
tokio::spawn(async move {
engine
.generate(1000, &Sampling::default(), &[888888], |_| {})
.await
})
};
// a second request queues behind the first (FIFO, not a refusal)
let waiter = {
let engine = engine.clone();
tokio::spawn(async move {
engine
.generate(8, &Sampling::default(), &[1, 2], |_| {})
.await
})
};
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(engine.abort().await.unwrap(), "a request was running");
let held = holder.await.unwrap();
assert!(
matches!(&held, Err(EngineError::Refused(m)) if m == "aborted"),
"the held request should end aborted: {held:?}"
);
// the queued waiter ran on the same engine and finished normally
let waited = waiter.await.unwrap();
assert_eq!(waited.unwrap().tokens.len(), 5);
// nothing running now: abort is a no-op
assert!(!engine.abort().await.unwrap());
engine.shutdown().await.unwrap();
}
+246
View File
@@ -0,0 +1,246 @@
//! Tests for the Inkling output dialect, driving the public token stream the
//! way `server.py` does (one `feed_token` per engine token) and asserting the
//! reasoning/content framing the launcher-patched reference produces.
use strata_ctl::inkling::dialect::{tag, InklingDialect, Kind, Out};
/// Feed a scripted sequence of tokens; `special` marks channel tokens.
fn run(tokens: &[(&str, bool)], finish: Option<&str>) -> Vec<Out> {
let mut d = InklingDialect::new();
let mut out = Vec::new();
for (piece, is_special) in tokens {
out.extend(d.feed_token(piece, *is_special));
}
out.extend(d.finish(finish));
out
}
fn content_of(outs: &[Out]) -> String {
outs.iter()
.filter(|o| o.kind == Kind::Content)
.map(|o| o.text.as_str())
.collect()
}
fn reasoning_of(outs: &[Out]) -> String {
outs.iter()
.filter(|o| o.kind == Kind::Reasoning)
.map(|o| o.text.as_str())
.collect()
}
#[test]
fn plain_text_answer() {
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_TEXT, true),
("Hello world", false),
(tag::END_MESSAGE, true),
],
None,
);
assert_eq!(content_of(&outs), "Hello world");
assert_eq!(reasoning_of(&outs), "");
}
#[test]
fn thinking_is_streamed_live_then_answers() {
let mut d = InklingDialect::new();
let mut reasoning = Vec::new();
let mut content = Vec::new();
let feed = |d: &mut InklingDialect,
p: &str,
s: bool,
reasoning: &mut Vec<String>,
content: &mut Vec<String>| {
for o in d.feed_token(p, s) {
match o.kind {
Kind::Reasoning => reasoning.push(o.text),
Kind::Content => content.push(o.text),
}
}
};
feed(
&mut d,
tag::MESSAGE_MODEL,
true,
&mut reasoning,
&mut content,
);
feed(
&mut d,
tag::CONTENT_THINKING,
true,
&mut reasoning,
&mut content,
);
feed(&mut d, "Let me ", false, &mut reasoning, &mut content);
feed(&mut d, "think. ", false, &mut reasoning, &mut content);
feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content);
feed(
&mut d,
tag::MESSAGE_MODEL,
true,
&mut reasoning,
&mut content,
);
feed(
&mut d,
tag::CONTENT_TEXT,
true,
&mut reasoning,
&mut content,
);
feed(&mut d, "The answer.", false, &mut reasoning, &mut content);
feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content);
d.finish(None);
// reasoning arrived as discrete live deltas, not one blob at the end
assert_eq!(reasoning, vec!["Let me ", "think. "]);
assert_eq!(content.join(""), "The answer.");
}
#[test]
fn quoted_end_message_stays_in_thinking() {
// #6675: the model literally writes `<|end_message|>` inside its thinking;
// it must not leak to content nor end thinking early.
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_THINKING, true),
("before ", false),
(tag::END_MESSAGE, true), // quoted, not a real channel end
("after", false), // ordinary text proves it was quoted
(tag::ENDOFTEXT, true),
],
None,
);
assert_eq!(content_of(&outs), "");
let r = reasoning_of(&outs);
assert!(r.contains("before "), "{r}");
assert!(
r.contains(tag::END_MESSAGE),
"quoted tag kept in reasoning: {r}"
);
assert!(r.contains("after"), "{r}");
}
#[test]
fn header_overflow_becomes_plain_text() {
// #6620: no `<|content_text|>`; a newline in the "header" means it is text.
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
("Just prose\ncontinued", false),
(tag::END_MESSAGE, true),
],
None,
);
assert_eq!(content_of(&outs), "Just prose\ncontinued");
}
#[test]
fn tool_json_renders_a_frame() {
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
("get_weather", false),
(tag::CONTENT_INVOKE_TOOL_JSON, true),
(r#"{"name":"get_weather","args":{"city":"Rome"}}"#, false),
(tag::END_MESSAGE, true),
],
None,
);
let c = content_of(&outs);
assert!(c.contains(tag::TOOL_CALL_OPEN), "{c}");
assert!(c.contains(tag::TOOL_CALL_CLOSE), "{c}");
// the JSON inside round-trips name + arguments
let json_start = c.find('{').unwrap();
let json_end = c.rfind('}').unwrap();
let v: serde_json::Value = serde_json::from_str(&c[json_start..=json_end]).unwrap();
assert_eq!(v["name"], "get_weather");
assert_eq!(v["arguments"]["city"], "Rome");
}
#[test]
fn tool_json_args_as_json_string_is_parsed() {
// arguments shipped as a JSON *string* must be parsed into an object
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_INVOKE_TOOL_JSON, true),
(r#"{"name":"f","args":"{\"a\":1}"}"#, false),
(tag::END_MESSAGE, true),
],
None,
);
let c = content_of(&outs);
let v: serde_json::Value =
serde_json::from_str(&c[c.find('{').unwrap()..=c.rfind('}').unwrap()]).unwrap();
assert_eq!(v["arguments"]["a"], 1);
}
#[test]
fn truncated_tool_falls_back_to_header_name() {
let mut d = InklingDialect::new();
let mut content = String::new();
for (p, s) in [
(tag::MESSAGE_MODEL, true),
("lookup", false),
(tag::CONTENT_INVOKE_TOOL_JSON, true),
(
"{\"a\":1", // unterminated
false,
),
] {
for o in d.feed_token(p, s) {
if o.kind == Kind::Content {
content.push_str(&o.text);
}
}
}
for o in d.finish(Some("length")) {
if o.kind == Kind::Content {
content.push_str(&o.text);
}
}
assert!(content.contains(tag::TOOL_CALL_OPEN), "{content}");
let v: serde_json::Value =
serde_json::from_str(&content[content.find('{').unwrap()..=content.rfind('}').unwrap()])
.unwrap();
assert_eq!(v["name"], "lookup");
assert_eq!(d.calls, 1);
}
#[test]
fn thinking_only_at_length_surfaces_reasoning() {
// #6682: budget expires mid-thinking with no answer.
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_THINKING, true),
("pondering", false),
],
Some("length"),
);
assert!(content_of(&outs).is_empty());
// the live delta plus the finish-time accumulation both carry it (faithful
// to the reference: patched emit + _finish_typed #6682)
assert!(reasoning_of(&outs).contains("pondering"));
}
#[test]
fn end_sampling_returns_to_idle() {
// after END_SAMPLING a new turn can open; ensure a following MessageModel
// does not double-emit the prior content.
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_TEXT, true),
("first", false),
(tag::END_SAMPLING, true),
],
None,
);
assert_eq!(content_of(&outs), "first");
}
+222
View File
@@ -0,0 +1,222 @@
//! 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::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()),
);
(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);
}
+109
View File
@@ -0,0 +1,109 @@
//! Tests for the Inkling image bridge: path encoding, source extraction across
//! OpenAI/Responses/Anthropic shapes, and materialization (PNG passthrough,
//! WebP->PNG normalization, local path). Host-independent: images are built in
//! memory with the image crate.
use base64::Engine;
use serde_json::json;
use strata_ctl::inkling::images::{encode_path, extract_sources, materialize};
fn png_bytes() -> Vec<u8> {
let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2));
let mut buf = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
}
fn webp_bytes() -> Vec<u8> {
let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2));
let mut buf = Vec::new();
img.write_to(
&mut std::io::Cursor::new(&mut buf),
image::ImageFormat::WebP,
)
.unwrap();
buf
}
fn data_url(mime: &str, bytes: &[u8]) -> String {
format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(bytes)
)
}
#[test]
fn encode_path_only_percent_and_space() {
assert_eq!(encode_path("/mnt/my pic.png"), "/mnt/my%20pic.png");
assert_eq!(encode_path("/a%b.png"), "/a%25b.png");
assert_eq!(encode_path("/a %b.png"), "/a%20%25b.png");
// slashes stay literal (the engine only decodes %20 and %25)
assert_eq!(encode_path("/mnt/x/y.png"), "/mnt/x/y.png");
}
#[test]
fn extract_sources_shapes_and_order() {
let msgs = json!([
{"role": "user", "content": [
{"type": "text", "text": "guarda"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAA"}},
{"type": "image_url", "image_url": "/local/a.png"}
]},
{"role": "user", "content": [
{"type": "input_image", "image_url": "https://x/b.png"},
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "BBB"}}
]}
]);
let srcs = extract_sources(&msgs);
assert_eq!(
srcs,
vec![
"data:image/png;base64,AAA",
"/local/a.png",
"https://x/b.png",
"data:image/jpeg;base64,BBB",
]
);
}
#[test]
fn extract_ignores_text_only() {
let msgs = json!([{"role": "user", "content": "ciao"}]);
assert!(extract_sources(&msgs).is_empty());
}
#[test]
fn materialize_png_passthrough() {
let png = png_bytes();
let paths = materialize(&[data_url("image/png", &png)]).unwrap();
assert_eq!(paths.len(), 1);
assert_eq!(paths[0].extension().unwrap(), "png");
assert_eq!(std::fs::read(&paths[0]).unwrap(), png);
let _ = std::fs::remove_file(&paths[0]);
}
#[test]
fn materialize_webp_normalizes_to_png() {
let webp = webp_bytes();
let paths = materialize(&[data_url("image/webp", &webp)]).unwrap();
assert_eq!(paths.len(), 1);
assert_eq!(paths[0].extension().unwrap(), "png");
let out = std::fs::read(&paths[0]).unwrap();
assert!(
out.starts_with(&[0x89, b'P', b'N', b'G']),
"not converted to PNG"
);
let _ = std::fs::remove_file(&paths[0]);
}
#[test]
fn materialize_local_path() {
let png = png_bytes();
let src = std::env::temp_dir().join(format!("strata-ctl-img-src-{}.png", std::process::id()));
std::fs::write(&src, &png).unwrap();
let paths = materialize(&[src.to_string_lossy().to_string()]).unwrap();
assert_eq!(std::fs::read(&paths[0]).unwrap(), png);
let _ = std::fs::remove_file(&paths[0]);
let _ = std::fs::remove_file(&src);
}
+111
View File
@@ -0,0 +1,111 @@
//! Tests for the Inkling chat-template layer: the custom tojson/raise_exception
//! and generation-strip (deterministic, inline template), prepare_messages /
//! finish_prompt (pure), and an #[ignore] render of the real chat_template.jinja.
use serde_json::json;
use strata_ctl::inkling::dialect::tag;
use strata_ctl::inkling::template::{finish_prompt, prepare_messages, ChatTemplate};
#[test]
fn tojson_compact_and_sorted() {
let t =
ChatTemplate::new("{{ {'b': 1, 'a': 2} | tojson(sort_keys=true, separators=(',', ':')) }}")
.unwrap();
assert_eq!(
t.render(&json!([]), None, None).unwrap(),
"{\"a\":2,\"b\":1}"
);
}
#[test]
fn generation_blocks_are_transparent() {
let t = ChatTemplate::new("A{% generation %}B{% endgeneration %}C").unwrap();
assert_eq!(t.render(&json!([]), None, None).unwrap(), "ABC");
}
#[test]
fn namespace_and_dictsort_work() {
let src = "{%- set s = namespace(x=[]) -%}\
{%- set s.x = s.x + [1, 2] -%}\
{{ s.x | tojson(separators=(',', ':')) }}|\
{%- for k, v in {'b': 1, 'a': 2} | dictsort(case_sensitive=true) -%}\
{{ k }}={{ v }};{%- endfor -%}";
let t = ChatTemplate::new(src).unwrap();
assert_eq!(t.render(&json!([]), None, None).unwrap(), "[1,2]|a=2;b=1;");
}
#[test]
fn raise_exception_fails_render() {
let t = ChatTemplate::new("{{ raise_exception('boom') }}").unwrap();
let err = t.render(&json!([]), None, None).unwrap_err();
assert!(err.to_string().contains("boom"), "{err}");
}
#[test]
fn prepare_messages_parses_string_arguments() {
let mut msgs = json!([
{"role": "assistant", "tool_calls": [
{"id": "c1", "type": "function",
"function": {"name": "f", "arguments": "{\"a\": 1}"}}
]},
{"role": "assistant", "tool_calls": [
{"id": "c2", "function": {"name": "g", "arguments": null}}
]}
]);
prepare_messages(&mut msgs);
assert_eq!(
msgs[0]["tool_calls"][0]["function"]["arguments"],
json!({"a": 1})
);
assert_eq!(msgs[1]["tool_calls"][0]["function"]["arguments"], json!({}));
}
#[test]
fn finish_prompt_only_for_effort_zero() {
// positive effort: untouched (model opens its own thinking)
let p = "<|message_system|><|content_text|>Thinking effort level: 0.2<|end_message|>";
assert_eq!(finish_prompt(p, false, false), p);
// effort zero, no opener yet: append the text opener (no tools)
let z = "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>";
let expect = format!("{z}{}{}", tag::MESSAGE_MODEL, tag::CONTENT_TEXT);
assert_eq!(finish_prompt(z, false, false), expect);
// with tools: the empty-thinking opener
let expect_tools = format!(
"{z}{}{}{}",
tag::MESSAGE_MODEL,
tag::CONTENT_THINKING,
tag::END_MESSAGE
);
assert_eq!(finish_prompt(z, true, false), expect_tools);
// idempotent: already ends with the text opener
assert_eq!(finish_prompt(&expect, false, false), expect);
}
/// Render the REAL template (host file). Run with:
/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored
#[test]
#[ignore = "needs the real Inkling chat_template.jinja"]
fn real_template_renders_a_turn() {
let dir = std::env::var("STRATA_TOK_DIR")
.unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string());
let src = std::fs::read_to_string(format!("{dir}/chat_template.jinja")).unwrap();
let t = ChatTemplate::new(&src).unwrap();
let msgs = json!([{"role": "user", "content": "ciao"}]);
let out = t.render(&msgs, None, Some("low")).unwrap();
assert!(out.contains("Thinking effort level: 0.2"), "{out}");
assert!(
out.contains("<|message_user|><|content_text|>ciao<|end_message|>"),
"{out}"
);
// effort none renders level 0
let out0 = t.render(&msgs, None, Some("none")).unwrap();
assert!(
out0.contains("Thinking effort level: 0<|end_message|>"),
"{out0}"
);
}
+133
View File
@@ -0,0 +1,133 @@
//! Tests for the Inkling tokenizer wrapper.
//!
//! The deterministic tests build a tiny fixture tokenizer with the `tokenizers`
//! crate (no host files), so the suite is green anywhere. A separate `#[ignore]`
//! test exercises the REAL o200k tokenizer when STRATA_TOK_DIR is set; run it
//! with `cargo test -- --ignored`.
use std::collections::HashMap;
use std::sync::Arc;
use tokenizers::models::wordlevel::WordLevel;
use tokenizers::AddedToken;
use tokenizers::Tokenizer;
use strata_ctl::inkling::dialect::Tag;
use strata_ctl::inkling::tokenizer::{Detok, InklingTokenizer};
/// Unique suffix so parallel tests never share a fixture file.
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Build a small WordLevel tokenizer with a few Inkling channel tokens added,
/// save it, and load it through our wrapper. Returns (wrapper, path, ids).
fn fixture() -> (InklingTokenizer, std::path::PathBuf) {
let mut vocab = HashMap::new();
vocab.insert("hello".to_string(), 0u32);
vocab.insert("world".to_string(), 1u32);
vocab.insert("[UNK]".to_string(), 2u32);
let model = WordLevel::builder()
.vocab(vocab.into_iter().collect())
.unk_token("[UNK]".to_string())
.build()
.unwrap();
let mut tok = Tokenizer::new(model);
tok.with_pre_tokenizer(Some(tokenizers::pre_tokenizers::whitespace::Whitespace));
let _ = tok.add_special_tokens([
AddedToken::from("<|message_model|>", true),
AddedToken::from("<|content_text|>", true),
AddedToken::from("<|content_thinking|>", true),
AddedToken::from("<|end_message|>", true),
]);
let path = std::env::temp_dir().join(format!(
"strata-ctl-tok-{}-{}.json",
std::process::id(),
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
tok.save(&path, false).unwrap();
let wrapped = InklingTokenizer::from_file(&path).unwrap();
(wrapped, path)
}
#[test]
fn encode_decode_roundtrip() {
let (t, path) = fixture();
let ids = t.encode("hello world").unwrap();
assert_eq!(ids, vec![0, 1]);
let decoded = t.decode_all(&ids).unwrap();
assert!(
decoded.contains("hello") && decoded.contains("world"),
"{decoded}"
);
let _ = std::fs::remove_file(&path);
}
#[test]
fn channel_tokens_map_to_tags() {
let (t, path) = fixture();
// a channel token encodes to a single id and maps back to its dialect tag
let ids = t.encode("<|content_thinking|>").unwrap();
assert_eq!(ids.len(), 1);
assert!(t.is_special(ids[0]));
assert_eq!(t.channel_tag(ids[0]), Some(Tag::ContentThinking));
let ids = t.encode("<|end_message|>").unwrap();
assert_eq!(t.channel_tag(ids[0]), Some(Tag::EndMessage));
// an ordinary word is not special
assert!(!t.is_special(0));
assert_eq!(t.channel_tag(0), None);
let _ = std::fs::remove_file(&path);
}
#[test]
fn detok_streams_incrementally() {
let (t, path) = fixture();
let mut d = Detok::new(Arc::new(t));
let a = d.push(0);
let b = d.push(1);
let c = d.finish();
// WordLevel decode re-inserts the whitespace between words
assert_eq!(format!("{a}{b}{c}"), "hello world");
let _ = std::fs::remove_file(&path);
}
#[test]
fn detok_emits_special_tokens_immediately() {
let (t, path) = fixture();
let think_id = t.encode("<|content_thinking|>").unwrap()[0];
let mut d = Detok::new(Arc::new(t));
// ordinary word then a channel token: both surface as text pieces
let a = d.push(0);
let b = d.push(think_id);
assert_eq!(a, "hello");
assert!(b.contains("<|content_thinking|>"), "{b}");
let _ = std::fs::remove_file(&path);
}
/// Real-tokenizer check, ignored by default (host files). Run with:
/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored
#[test]
#[ignore = "needs the real Inkling tokenizer dir"]
fn real_tokenizer_channel_ids() {
let dir = std::env::var("STRATA_TOK_DIR")
.unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string());
let t = InklingTokenizer::load_dir(std::path::Path::new(&dir)).expect("load real tokenizer");
// the exact ids observed in tokenizer.hf.json's added_tokens
assert_eq!(t.channel_tag(200001), Some(Tag::MessageModel));
assert_eq!(t.channel_tag(200004), Some(Tag::ContentText));
assert_eq!(t.channel_tag(200006), Some(Tag::EndSampling));
assert_eq!(t.channel_tag(200008), Some(Tag::ContentThinking));
assert_eq!(t.channel_tag(200010), Some(Tag::EndMessage));
assert_eq!(t.channel_tag(200024), Some(Tag::ContentXml));
assert_eq!(t.channel_tag(200049), Some(Tag::ContentInvokeToolJson));
assert_eq!(t.channel_tag(200057), Some(Tag::ContentInvokeToolText));
assert_eq!(t.channel_tag(199999), Some(Tag::EndOfText));
// a channel token in a rendered prompt encodes to its single id
let ids = t
.encode("<|message_model|><|content_text|>ciao<|end_message|>")
.unwrap();
assert_eq!(ids.first().copied(), Some(200001));
assert_eq!(ids.last().copied(), Some(200010));
assert!(t.decode_all(&ids).unwrap().contains("ciao"));
}
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""A scripted stand-in for `strata --serve`, for strata-ctl's integration tests.
Speaks the line protocol exactly as the engine's parser emits it:
READY/INFO at start, then per GEN: optional RESUME, PP lines, T lines, DONE.
Faithful to the real engine's key invariant: **one DONE per request**. A STOP
arriving mid-request ends that request with a single DONE and is not answered
again; a STOP arriving while idle is ignored (no request to abort). Stdin is
read on a background thread so STOP can interrupt a long generation, exactly
as the resident engine's own stdin reader does.
Scenarios, keyed by the prompt ids sent:
* 999999 in ids -> ERR then DONE (a refused id)
* 888888 in ids -> long generation (many tokens), interruptible by STOP
* 777777 in ids -> total silence (the supervisor's watchdog must fire)
* otherwise -> echo five tokens and finish
"""
import queue
import sys
import threading
import time
def out(line: str) -> None:
sys.stdout.write(line + "\n")
sys.stdout.flush()
def reader(cmds: "queue.Queue[str]") -> None:
for raw in sys.stdin:
cmds.put(raw.strip())
cmds.put(None) # EOF
out("INFO version=0.0.0-mock build=test")
out("READY 8192 stop hold")
cmds: "queue.Queue[str | None]" = queue.Queue()
threading.Thread(target=reader, args=(cmds,), daemon=True).start()
while True:
cmd = cmds.get()
if cmd is None or cmd == "QUIT":
break
if cmd == "STOP":
continue # idle STOP: nothing to abort, no reply (as the real engine)
if not cmd.startswith("GEN"):
out("ERR unknown command")
continue
parts = cmd.split()
if len(parts) < 3:
out("ERR GEN: missing ids")
continue
try:
ids = [int(t) for t in parts[-1].split(",")]
except ValueError:
out("ERR GEN: bad id")
continue
keys = " ".join(parts[1:-1])
if "bad_key" in keys:
out("ERR GEN: unknown/unsupported key bad_key")
out("DONE 0 0 0.0 0.0 error")
continue
if 999999 in ids:
out("ERR GEN: id out of range")
out("DONE 0 0 0.0 0.0 error")
continue
if 777777 in ids:
# total silence for this request: swallow commands until a STOP ends it
while True:
nxt = cmds.get()
if nxt is None or nxt == "QUIT":
sys.exit(0)
if nxt == "STOP":
out("DONE 0 0 0.0 0.0 abort")
break
continue
if 888888 in ids:
out("RESUME 3")
out("PP 5 5 1.5 3333.3")
n = 0
stopped = False
while n < 100000:
nxt = cmds.get_nowait() if not cmds.empty() else None
if nxt == "STOP":
stopped = True
break
n += 1
out(f"T {n}")
if n % 50 == 0:
time.sleep(0.001)
out(f"DONE {n} {len(ids)} 1.0 2.0 {'abort' if stopped else 'length'}")
continue
out("RESUME 1")
out("PP 2 4 0.9 2222.2")
for t in (101, 102, 103, 104, 105):
out(f"T {t}")
out("DONE 5 4 12.5 34.0 stop 3 4 1")