Files
leleka/control-plane/tests/backend_worker_http.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 b3274c1130
Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Failing after 8s
Desktop foundation / core (ubuntu-latest) (push) Failing after 11s
Rust port / port-oracles (push) Failing after 11s
Rust port / port-linux-tests (push) Failing after 14s
Rust port / port-fast (push) Failing after 9s
Linux / verify (push) Failing after 17s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Merge claude/port-gpu-bringup (CUDA runtime port, upstream sync) into main
Brings the Rust/CUDA port of the Strata mode17 serve path together with the
CPU/iGPU/NPU gpt-oss runtime that main gained meanwhile.

Control plane: the Qwen tokenizer is the implementation behind the Qwen35
variant of codec::TextCodec (qwen(), encode_prompt() widen the trait; QwenCodec
derefs to the tokenizer), so control-token marks, images, chat template, the
runtime backend and vision keep their behavior, while the gpt-oss/Harmony path
and the worker pool keep main's. Config carries the union of fields; extra_workers
is rejected together with runtime, lazy_load, idle_unload_s and vision; the
gpt-oss family refuses top_k/min_p/penalties (its GEN line has no such keys).
leleka-kar-codec takes f16_bits_to_f32 from leleka-quant-core (identical code).
Workspace members and default-members are the union of both sides.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:32:33 +01:00

1833 lines
70 KiB
Rust

//! The whole HTTP API in front of a text-level engine: real axum router, real worker adapter
//! (`backend_worker`), real HTTP/SSE over loopback, and a scripted in-process engine implementing the
//! backend contract (`leleka_backend_api::scripted`). No GPU, no model, no child process.
//!
//! What the engine says is scripted, so none of this is a statement about any model; it checks that the
//! adapter and the API above it keep the protocol intact: ordered events, exactly one terminal event, tool
//! calls and structured output validated, finish reasons, cancellation, and failure completion even when
//! the engine dies. Fixtures are the repository's sanitized ones (`benchmarks/fixtures/responses`).
use std::{sync::Arc, time::Duration};
use leleka_backend_api::{
ErrorCode, FinishReason, InferenceMode, RuntimeConfig, Usage,
scripted::{Script, ScriptedEngine, ScriptedHandle, Step},
};
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, run_backend_worker},
tokenizer::Tokenizer,
worker::{WorkerState, WorkerStatus},
};
use tokio::sync::{RwLock, mpsc, watch};
mod common;
const LIVE_TOOL_EPISODE: &str =
include_str!("../../benchmarks/fixtures/responses/live-tool-episode.json");
const COMMENTARY_PROMPT: &str =
include_str!("../../benchmarks/fixtures/responses/commentary-tool-prompt.json");
/// A tokenizer with a few merges, so that re-tokenizing a piece of text does not give the ids the
/// whole text has (the engine never reports ids; only bytes must survive).
fn merging_tokenizer(dir: &std::path::Path) -> Arc<Tokenizer> {
let root = dir.join("tokenizer");
std::fs::create_dir(&root).unwrap();
let mut vocabulary = serde_json::Map::new();
for (id, ch) in strata_control::tokenizer::byte_alphabet()
.0
.iter()
.enumerate()
{
vocabulary.insert(ch.to_string(), json!(id));
}
let mut next = 256;
for token in common::SPECIALS {
vocabulary.insert(token.into(), json!(next));
next += 1;
}
let merged = ["he", "ll", "hell", "ok", "to", "too", "tool"];
for token in merged {
vocabulary.insert(token.into(), json!(next));
next += 1;
}
std::fs::write(
root.join("vocab.json"),
serde_json::to_vec(&vocabulary).unwrap(),
)
.unwrap();
std::fs::write(
root.join("merges.txt"),
"h e\nl l\nhe ll\no k\nt o\nto o\ntoo l",
)
.unwrap();
let mut types = vec![1u8; next];
for t in types[256..256 + common::SPECIALS.len()].iter_mut() {
*t = 3;
}
std::fs::write(
root.join("token_type.json"),
serde_json::to_vec(&types).unwrap(),
)
.unwrap();
std::fs::write(
root.join("tokenizer.json"),
serde_json::to_vec(&json!({
"model": "gpt2", "pre": "qwen35", "vocab_size": next, "n_merges": 7,
"pre_pattern": leleka_tokenizer::QWEN35_PATTERN,
"special_ids": {"tokenizer.ggml.eos_token_id": 257}
}))
.unwrap(),
)
.unwrap();
Arc::new(Tokenizer::from_assets(&root).unwrap())
}
struct Stack {
base: String,
client: reqwest::Client,
engine: ScriptedHandle,
status: Arc<RwLock<WorkerStatus>>,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
tokenizer: Arc<Tokenizer>,
state: AppState,
}
fn runtime_config() -> RuntimeConfig {
RuntimeConfig {
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
inference_mode: InferenceMode::Native,
gpu_memory_limit_bytes: None,
allow_experimental: false,
}
}
impl Stack {
async fn start(name: &str) -> Self {
Self::start_with(name, |_| {}).await
}
async fn start_with(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig)) -> Self {
Self::start_full(name, tune, false).await
}
/// The same stack with the API request monitor (`api_monitor`) on.
async fn start_monitored(name: &str) -> Self {
Self::start_full(name, |_| {}, true).await
}
async fn start_full(
name: &str,
tune: impl FnOnce(&mut BackendWorkerConfig),
monitor: bool,
) -> Self {
let dir = common::scratch(name);
let tokenizer = merging_tokenizer(&dir);
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
let mut config = BackendWorkerConfig {
tokenizer: tokenizer.clone(),
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(20),
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(20),
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
};
tune(&mut config);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(8);
let (control, control_rx) = mpsc::channel(8);
let worker = tokio::spawn(run_backend_worker(
Box::new(engine),
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let state = AppState {
model: Some("fixture".into()),
worker: status.clone(),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
generation: Some(requests),
control: Some(control),
monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(
monitor,
)),
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state.clone());
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let stack = Self {
base,
client: reqwest::Client::new(),
engine: handle,
status,
stop,
worker,
server,
tokenizer,
state,
};
stack.wait_state(WorkerState::Ready).await;
stack
}
async fn wait_state(&self, wanted: WorkerState) {
tokio::time::timeout(Duration::from_secs(10), async {
while self.status.read().await.state != wanted {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap_or_else(|_| panic!("worker never reached {wanted:?}"));
}
async fn post(&self, path: &str, body: &Value) -> (u16, String) {
let response = self
.client
.post(format!("{}{path}", self.base))
.header("content-type", "application/json")
.body(body.to_string())
.send()
.await
.unwrap();
let status = response.status().as_u16();
(status, response.text().await.unwrap())
}
async fn get(&self, path: &str) -> (u16, String) {
let response = self
.client
.get(format!("{}{path}", self.base))
.send()
.await
.unwrap();
let status = response.status().as_u16();
(status, response.text().await.unwrap())
}
async fn finish(self) {
let _ = self.stop.send(true);
let _ = tokio::time::timeout(Duration::from_secs(10), self.worker).await;
self.server.abort();
}
}
/// The JSON `data:` frames of an SSE body, in order (comments and `[DONE]` skipped).
fn sse_events(body: &str) -> Vec<Value> {
body.split("\n\n")
.filter(|frame| !frame.trim().is_empty() && !frame.starts_with(':'))
.filter_map(|frame| {
let data = frame
.lines()
.filter_map(|line| line.strip_prefix("data:"))
.map(str::trim_start)
.collect::<Vec<_>>()
.join("\n");
(data != "[DONE]").then(|| serde_json::from_str(&data).unwrap())
})
.collect()
}
fn types(events: &[Value]) -> Vec<&str> {
events
.iter()
.map(|event| event["type"].as_str().unwrap())
.collect()
}
/// The protocol invariants every Responses stream must keep.
fn assert_stream_invariants(events: &[Value]) {
assert!(!events.is_empty());
for (index, event) in events.iter().enumerate() {
assert_eq!(event["sequence_number"], json!(index), "{event}");
}
let terminal = [
"response.completed",
"response.failed",
"response.incomplete",
];
let terminals: Vec<_> = types(events)
.into_iter()
.filter(|kind| terminal.contains(kind))
.collect();
assert_eq!(
terminals.len(),
1,
"exactly one terminal event: {terminals:?}"
);
assert!(
terminal.contains(&events.last().unwrap()["type"].as_str().unwrap()),
"the terminal event is last"
);
assert_eq!(events[0]["type"], "response.created");
}
fn usage(input: u64, output: u64, reused: u64) -> Usage {
Usage {
input_tokens: input,
output_tokens: output,
reused_input_tokens: reused,
}
}
fn body(extra: Value) -> Value {
let mut value = json!({"model": "fixture", "input": "hi", "reasoning": {"effort": "none"}});
for (key, item) in extra.as_object().unwrap() {
value[key] = item.clone();
}
value
}
fn text_of(response: &Value) -> String {
response["output"]
.as_array()
.unwrap()
.iter()
.filter(|item| item["type"] == "message")
.flat_map(|item| item["content"].as_array().unwrap().clone())
.filter_map(|part| part["text"].as_str().map(str::to_owned))
.collect()
}
#[tokio::test]
async fn non_streaming_text_carries_the_rendered_prompt_and_engine_usage() {
let stack = Stack::start("bw-nonstream").await;
stack
.engine
.push(Script::stop_with(&["hel", "lo ", "жук"], usage(11, 5, 4)));
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"max_output_tokens": 64, "temperature": 0.5, "seed": 7})),
)
.await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["status"], "completed");
assert_eq!(text_of(&response), "hello жук");
// Usage is the engine's report, not a count of re-tokenized pieces.
assert_eq!(response["usage"]["input_tokens"], 11);
assert_eq!(response["usage"]["output_tokens"], 5);
assert_eq!(
response["usage"]["input_tokens_details"]["cached_tokens"],
4
);
let requests = stack.engine.requests();
assert_eq!(requests.len(), 1);
let sent = &requests[0];
assert_eq!(
sent.prompt,
"<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
);
assert_eq!(sent.max_output_tokens, 64);
assert_eq!(sent.temperature_milli, 500);
assert_eq!(sent.sampling.seed, Some(7));
// The engine never sees the HTTP layer's response ID; its own request identity is a UUID.
assert_eq!(sent.request_id.len(), 36);
assert!(
sent.request_id
.chars()
.all(|c| c == '-' || c.is_ascii_hexdigit())
);
stack.finish().await;
}
#[tokio::test]
async fn the_engine_receives_exactly_the_fixture_prompt() {
let stack = Stack::start("bw-prompt").await;
let fixture: Value = serde_json::from_str(COMMENTARY_PROMPT).unwrap();
stack
.engine
.push(Script::stop_with(&["ok"], usage(1, 1, 0)));
let mut request = fixture["request"].clone();
request["model"] = json!("fixture");
let (status, text) = stack.post("/v1/responses", &request).await;
assert_eq!(status, 200, "{text}");
assert_eq!(
stack.engine.requests()[0].prompt,
fixture["rendered"].as_str().unwrap()
);
stack.finish().await;
}
#[tokio::test]
async fn streaming_text_is_ordered_with_one_terminal_and_the_same_bytes() {
let stack = Stack::start("bw-stream").await;
stack.engine.push(Script::stop_with(
&["hel", "lo ", "ж", "ук"],
usage(9, 4, 0),
));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
let deltas: String = events
.iter()
.filter(|e| e["type"] == "response.output_text.delta")
.map(|e| e["delta"].as_str().unwrap())
.collect();
assert_eq!(deltas, "hello жук");
assert_eq!(
events.last().unwrap()["response"]["usage"]["output_tokens"],
4
);
stack.finish().await;
}
#[tokio::test]
async fn length_finish_is_incomplete_and_tool_calls_reason_is_a_stop() {
let stack = Stack::start("bw-length").await;
stack.engine.push(Script::finishing(
&["cut"],
FinishReason::Length,
usage(5, 1, 0),
));
let (status, text) = stack
.post("/v1/responses", &body(json!({"max_output_tokens": 1})))
.await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["status"], "incomplete");
assert_eq!(
response["incomplete_details"]["reason"],
"max_output_tokens"
);
stack.engine.push(Script::finishing(
&["cut"],
FinishReason::Length,
usage(5, 1, 0),
));
let (_, text) = stack
.post(
"/v1/responses",
&body(json!({"max_output_tokens": 1, "stream": true})),
)
.await;
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
// `tool_calls` from an engine carries no native calls here: tool calls come from the text.
stack.engine.push(Script::finishing(
&["done"],
FinishReason::ToolCalls,
usage(5, 1, 0),
));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
assert_eq!(
serde_json::from_str::<Value>(&text).unwrap()["status"],
"completed"
);
stack.finish().await;
}
#[tokio::test]
async fn a_stop_literal_ends_the_text_cancels_the_engine_and_never_reaches_the_client() {
for (name, pieces) in [
("one", vec!["ok<|im_end|>junk"]),
("split", vec!["ok<|im", "_end", "|>junk"]),
("endoftext", vec!["ok", "<|endoftext|>", "junk"]),
] {
let stack = Stack::start(&format!("bw-stop-{name}")).await;
stack.engine.push(Script::hanging_after(&pieces));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(
events.last().unwrap()["type"],
"response.completed",
"{name}"
);
let deltas: String = events
.iter()
.filter(|e| e["type"] == "response.output_text.delta")
.map(|e| e["delta"].as_str().unwrap())
.collect();
assert_eq!(deltas, "ok", "{name}");
assert!(!text.contains("junk") && !text.contains("<|"), "{name}");
assert_eq!(
stack.engine.cancels().len(),
1,
"{name}: the engine was cancelled"
);
// The slot is free again.
stack
.engine
.push(Script::stop_with(&["next"], usage(1, 1, 0)));
let (status, _) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{name}");
stack.finish().await;
}
}
#[tokio::test]
async fn a_held_back_prefix_that_never_completes_is_delivered_at_the_end() {
let stack = Stack::start("bw-heldback").await;
stack
.engine
.push(Script::stop_with(&["a <|im", "_x"], usage(3, 2, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
assert_eq!(text_of(&serde_json::from_str(&text).unwrap()), "a <|im_x");
stack.finish().await;
}
#[tokio::test]
async fn an_engine_failure_terminal_ends_the_stream_with_response_failed() {
let stack = Stack::start("bw-fail").await;
stack.engine.push(Script::failing_after(
&["par"],
ErrorCode::ResourceExhausted,
"scripted engine failure",
));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
let last = events.last().unwrap();
assert_eq!(last["type"], "response.failed");
assert!(
last["response"]["error"]["message"]
.as_str()
.unwrap()
.contains("scripted engine failure")
);
stack.engine.push(Script::failing_after(
&[],
ErrorCode::Internal,
"scripted engine failure",
));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 502, "{text}");
assert_eq!(
serde_json::from_str::<Value>(&text).unwrap()["error"]["code"],
"generation_failed"
);
// The engine is healthy: the worker stays ready.
assert_eq!(stack.status.read().await.state, WorkerState::Ready);
stack.finish().await;
}
#[tokio::test]
async fn an_engine_that_dies_mid_stream_still_gets_a_terminal_event_and_the_worker_recovers() {
let stack = Stack::start("bw-die").await;
stack.engine.push(Script::dying_after(&["half"]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
// The engine process is gone: not ready, and a request is refused, not hung.
stack.engine.restart_engine();
stack.wait_state(WorkerState::Restarting).await;
let (status, _) = stack.get("/ready").await;
assert_eq!(status, 503);
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 503, "{text}");
// The runtime comes back with the model loaded again: the worker attaches by itself.
stack.engine.reload_engine();
stack.wait_state(WorkerState::Ready).await;
stack
.engine
.push(Script::stop_with(&["back"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
assert_eq!(text_of(&serde_json::from_str(&text).unwrap()), "back");
stack.finish().await;
}
#[tokio::test]
async fn a_dead_engine_fails_a_buffered_request_instead_of_hanging_it() {
let stack = Stack::start("bw-die-buffered").await;
stack.engine.push(Script::dying_after(&["half"]));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 502, "{text}");
assert_eq!(
serde_json::from_str::<Value>(&text).unwrap()["error"]["type"],
"server_error"
);
stack.finish().await;
}
#[tokio::test]
async fn a_client_disconnect_cancels_the_engine_and_frees_it_for_the_next_request() {
let stack = Stack::start("bw-disconnect").await;
stack.engine.push(Script::hanging_after(&["start"]));
let mut response = stack
.client
.post(format!("{}/v1/responses", stack.base))
.header("content-type", "application/json")
.body(body(json!({"stream": true})).to_string())
.send()
.await
.unwrap();
// Read until the first text delta, then walk away.
let mut seen = String::new();
while !seen.contains("response.output_text.delta") {
let chunk = tokio::time::timeout(Duration::from_secs(10), response.chunk())
.await
.unwrap()
.unwrap()
.expect("stream ended early");
seen.push_str(&String::from_utf8_lossy(&chunk));
}
drop(response);
tokio::time::timeout(Duration::from_secs(10), async {
while stack.engine.is_generating() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the engine generation was cancelled");
assert_eq!(stack.engine.cancels().len(), 1);
stack
.engine
.push(Script::stop_with(&["again"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
assert_eq!(metrics["generation"]["cancelled"], 1);
assert_eq!(metrics["generation"]["completed"], 1);
stack.finish().await;
}
#[tokio::test]
async fn the_generation_deadline_cancels_the_engine_and_fails_the_request() {
let stack = Stack::start_with("bw-deadline", |config| {
config.generation_timeout = Some(Duration::from_millis(150));
})
.await;
stack.engine.push(Script::hanging_after(&["slow"]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
let last = events.last().unwrap();
assert_eq!(last["type"], "response.failed");
assert!(
last["response"]["error"]["message"]
.as_str()
.unwrap()
.contains("execution deadline")
);
assert_eq!(stack.engine.cancels().len(), 1);
stack.finish().await;
}
#[tokio::test]
async fn an_engine_that_ignores_cancellation_is_treated_as_lost_after_the_drain_timeout() {
let stack = Stack::start_with("bw-drain", |config| {
config.generation_timeout = Some(Duration::from_millis(100));
config.cancel_drain_timeout = Duration::from_millis(200);
})
.await;
// A wedged engine: it produced a delta and then ignores everything, including cancel.
stack.engine.push(Script::new(vec![
Step::Text("x".into()),
Step::Unresponsive(Duration::from_millis(1500)),
Step::AwaitCancel,
]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(text.contains("execution deadline"), "{text}");
// The engine is treated as lost; once it can serve again the worker attaches again by itself.
stack.wait_state(WorkerState::Ready).await;
tokio::time::sleep(Duration::from_millis(1600)).await;
stack
.engine
.push(Script::stop_with(&["fine"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
stack.finish().await;
}
#[tokio::test]
async fn a_native_tool_call_delta_from_the_engine_is_a_protocol_violation() {
let stack = Stack::start("bw-toolviolation").await;
stack.engine.push(Script::new(vec![
Step::Text("x".into()),
Step::ToolCall {
index: 0,
id: Some("c".into()),
name: Some("lookup".into()),
arguments_delta: "{}".into(),
},
Step::AwaitCancel,
]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200);
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(text.contains("tool-call delta"));
stack.finish().await;
}
fn tool_markup(name: &str, arguments: &Value) -> String {
let mut out = format!("<tool_call>\n<function={name}>\n");
for (key, value) in arguments.as_object().unwrap() {
let rendered = value
.as_str()
.map_or_else(|| value.to_string(), str::to_owned);
out.push_str(&format!("<parameter={key}>\n{rendered}\n</parameter>\n"));
}
out.push_str("</function>\n</tool_call>");
out
}
fn chunks(text: &str, size: usize) -> Vec<String> {
let chars: Vec<char> = text.chars().collect();
chars
.chunks(size)
.map(|part| part.iter().collect())
.collect()
}
fn scripted_text(engine: &ScriptedHandle, text: &str, size: usize) {
let owned = chunks(text, size);
let refs: Vec<&str> = owned.iter().map(String::as_str).collect();
engine.push(Script::stop_with(&refs, usage(10, owned.len() as u64, 0)));
}
/// The sanitized two-step tool episode (`live-tool-episode.json`) replayed through HTTP, JSON and SSE.
#[tokio::test]
async fn function_tool_episode_fixture_round_trips_in_json_and_sse() {
let episode: Value = serde_json::from_str(LIVE_TOOL_EPISODE).unwrap();
let steps = episode["steps"].as_array().unwrap();
for stream in [false, true] {
let stack = Stack::start(&format!("bw-tools-{stream}")).await;
let mut previous: Option<Value> = None;
for step in steps {
let mut request = step["request"].clone();
request["model"] = json!("fixture");
request["stream"] = json!(stream);
let expect = &step["expect"][0];
let output = if expect["type"] == "function_call" {
tool_markup(
expect["name"].as_str().unwrap(),
&expect["arguments"].clone(),
)
} else {
expect["text"].as_str().unwrap().to_owned()
};
if let Some(call) = &previous {
let results: Vec<Value> = step["tool_results"]
.as_array()
.unwrap()
.iter()
.map(|result| {
json!({"type": "function_call_output", "call_id": call["call_id"], "output": result})
})
.collect();
let mut input = vec![
json!({"role": "user", "content": request["input"]}),
call.clone(),
];
input.extend(results);
request["input"] = Value::Array(input);
}
scripted_text(&stack.engine, &output, 7);
let (status, text) = stack.post("/v1/responses", &request).await;
assert_eq!(status, 200, "{text}");
let response = if stream {
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
events.last().unwrap()["response"].clone()
} else {
serde_json::from_str::<Value>(&text).unwrap()
};
if expect["type"] == "function_call" {
let call = response["output"]
.as_array()
.unwrap()
.iter()
.find(|item| item["type"] == "function_call")
.unwrap_or_else(|| panic!("no function_call in {response}"));
assert_eq!(call["name"], expect["name"]);
let arguments: Value =
serde_json::from_str(call["arguments"].as_str().unwrap()).unwrap();
assert_eq!(arguments, expect["arguments"]);
previous = Some(json!({
"type": "function_call", "call_id": call["call_id"],
"name": call["name"], "arguments": call["arguments"]
}));
} else {
assert_eq!(text_of(&response), expect["text"].as_str().unwrap());
}
}
// The second prompt carries the call and its output as the template renders them.
let second = &stack.engine.requests()[1].prompt;
assert!(second.contains("CONFIRMED-731"), "{second}");
assert!(second.contains("<function=lookup>"), "{second}");
stack.finish().await;
}
}
#[tokio::test]
async fn a_custom_tool_call_is_returned_as_custom_tool_call_input() {
let stack = Stack::start("bw-custom").await;
let source = "\n print(\"Привіт\")\n";
let markup = tool_markup("run", &json!({"input": source}));
for stream in [false, true] {
scripted_text(&stack.engine, &markup, 5);
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"stream": stream, "tools": [{"type": "custom", "name": "run", "format": {"type": "text"}}]})),
)
.await;
assert_eq!(status, 200, "{text}");
let response = if stream {
let events = sse_events(&text);
assert_stream_invariants(&events);
let joined: String = events
.iter()
.filter(|e| e["type"] == "response.custom_tool_call_input.delta")
.map(|e| e["delta"].as_str().unwrap())
.collect();
assert_eq!(joined, source);
events.last().unwrap()["response"].clone()
} else {
serde_json::from_str(&text).unwrap()
};
let call = response["output"]
.as_array()
.unwrap()
.last()
.unwrap()
.clone();
assert_eq!(call["type"], "custom_tool_call");
assert_eq!(call["input"], source);
}
stack.finish().await;
}
#[tokio::test]
async fn an_invalid_tool_call_never_becomes_a_successful_function_call() {
let stack = Stack::start("bw-badtool").await;
// The model calls a tool that was not declared.
scripted_text(
&stack.engine,
&tool_markup("undeclared", &json!({"key": "v"})),
9,
);
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"stream": true, "tools": [{"type": "function", "name": "lookup", "parameters": {"type": "object"}}]})),
)
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(
!events
.iter()
.any(|e| e["type"] == "response.function_call_arguments.done")
);
stack.finish().await;
}
#[tokio::test]
async fn text_format_json_schema_accepts_valid_and_fails_invalid_output() {
let stack = Stack::start("bw-schema").await;
let format = json!({"type": "json_schema", "name": "result", "strict": true,
"schema": {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"], "additionalProperties": false}});
for stream in [false, true] {
scripted_text(&stack.engine, "{\"ok\":true}", 4);
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"stream": stream, "text": {"format": format}})),
)
.await;
assert_eq!(status, 200, "{text}");
if stream {
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
} else {
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(text_of(&response), "{\"ok\":true}");
}
scripted_text(&stack.engine, "{\"ok\":\"yes\"}", 4);
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"stream": stream, "text": {"format": format}})),
)
.await;
if stream {
assert_eq!(status, 200);
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(
!events
.iter()
.any(|e| e["type"] == "response.output_text.delta")
);
} else {
assert_eq!(status, 502, "{text}");
}
}
// The schema travels in the prompt (guidance), not as a decoding constraint.
assert!(stack.engine.requests()[0].prompt.contains("\"ok\""));
stack.finish().await;
}
#[tokio::test]
async fn text_the_contract_cannot_carry_is_refused_not_dropped() {
let stack = Stack::start("bw-refuse").await;
// Reasoning budget wrap-up needs token-level continuation.
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"reasoning": {"effort": "high"}, "reasoning_budget_tokens": 5})),
)
.await;
assert_eq!(status, 400, "{text}");
assert!(
text.contains("reasoning_budget_tokens") && text.contains("unsupported_request_field"),
"{text}"
);
// Per-request engine tuning is not part of the contract.
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"strata_tune": {"pcie_frac": 0.5}})),
)
.await;
assert_eq!(status, 400, "{text}");
assert!(text.contains("strata_tune"), "{text}");
// Sampling that is not exact thousandths is refused like the daemon does.
let (status, text) = stack
.post("/v1/responses", &body(json!({"temperature": 0.0005})))
.await;
assert_eq!(status, 400, "{text}");
assert!(text.contains("temperature"), "{text}");
// None of these reached the engine.
assert!(stack.engine.requests().is_empty());
// And the worker is still serving.
stack
.engine
.push(Script::stop_with(&["fine"], usage(1, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
stack.finish().await;
}
#[tokio::test]
async fn a_prompt_that_is_not_the_canonical_encoding_is_refused() {
use strata_control::wire::Generate;
use strata_control::worker::{GenerationCommand, GenerationResult};
// Two merged tokens "he","ll" are the canonical encoding of "hell" as "hell"; this id sequence is not.
let stack = Stack::start("bw-canonical").await;
let he = stack.tokenizer.encode("he", false).unwrap();
let ll = stack.tokenizer.encode("ll", false).unwrap();
assert_eq!(stack.tokenizer.encode("hell", false).unwrap().len(), 1);
let ids: Vec<u32> = he.iter().chain(ll.iter()).copied().collect();
let (sender, receiver) = tokio::sync::oneshot::channel();
// A second worker, fed the way the HTTP layer feeds it.
let (requests, requests_rx) = mpsc::channel(1);
let (_control, control_rx) = mpsc::channel(1);
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let config = BackendWorkerConfig {
tokenizer: stack.tokenizer.clone(),
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(20),
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(20),
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
};
tokio::spawn(run_backend_worker(
Box::new(engine),
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
while status.read().await.state != WorkerState::Ready {
tokio::time::sleep(Duration::from_millis(5)).await;
}
requests
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: ids,
max_new: 8,
..Default::default()
},
result: GenerationResult::Buffered(sender),
})
.await
.unwrap();
let outcome = receiver.await.unwrap();
let message = outcome.expect_err("a non-canonical prompt must not reach the engine");
assert!(message.contains("canonical encoding"), "{message}");
assert!(handle.requests().is_empty());
stack.finish().await;
}
#[tokio::test]
async fn re_tokenized_pieces_keep_bytes_even_when_ids_differ_from_the_whole() {
let stack = Stack::start("bw-merges").await;
stack.engine.push(Script::stop_with(
&["he", "l", "l", "o tool"],
usage(3, 4, 0),
));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(text_of(&response), "hello tool");
// Usage is what the engine counted (4), not what the merges make of the pieces.
assert_eq!(response["usage"]["output_tokens"], 4);
stack.finish().await;
}
#[tokio::test]
async fn chat_completions_stream_and_json_over_the_same_worker() {
let stack = Stack::start("bw-chat").await;
let request = |stream: bool| json!({"model": "fixture", "stream": stream, "messages": [{"role": "user", "content": "hi"}]});
stack
.engine
.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0)));
let (status, text) = stack.post("/v1/chat/completions", &request(false)).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["choices"][0]["message"]["content"], "hello");
assert_eq!(response["choices"][0]["finish_reason"], "stop");
assert_eq!(response["usage"]["completion_tokens"], 2);
stack.engine.push(Script::finishing(
&["cut"],
FinishReason::Length,
usage(7, 1, 0),
));
let (status, text) = stack.post("/v1/chat/completions", &request(true)).await;
assert_eq!(status, 200, "{text}");
assert!(text.trim_end().ends_with("data: [DONE]"), "{text}");
let chunks = sse_events(&text);
let content: String = chunks
.iter()
.filter_map(|c| c["choices"][0]["delta"]["content"].as_str())
.collect();
assert_eq!(content, "cut");
assert_eq!(
chunks
.iter()
.filter_map(|c| c["choices"][0]["finish_reason"].as_str())
.collect::<Vec<_>>(),
vec!["length"]
);
// Tool call through Chat: finish_reason tool_calls, arguments intact.
let markup = tool_markup("lookup", &json!({"key": "value"}));
scripted_text(&stack.engine, &markup, 6);
let (status, text) = stack
.post(
"/v1/chat/completions",
&json!({"model": "fixture", "messages": [{"role": "user", "content": "go"}],
"tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": {"key": {"type": "string"}}}}}]}),
)
.await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
let choice = &response["choices"][0];
assert_eq!(choice["finish_reason"], "tool_calls");
let call = &choice["message"]["tool_calls"][0];
assert_eq!(call["function"]["name"], "lookup");
assert_eq!(
serde_json::from_str::<Value>(call["function"]["arguments"].as_str().unwrap()).unwrap(),
json!({"key": "value"})
);
// An engine death in Chat is an error object plus [DONE], never a success.
stack.engine.push(Script::dying_after(&["x"]));
let (_, text) = stack.post("/v1/chat/completions", &request(true)).await;
assert!(text.contains("\"error\""), "{text}");
assert!(!text.contains("\"finish_reason\":\"stop\""), "{text}");
stack.finish().await;
}
#[tokio::test]
async fn status_metrics_and_unload_reflect_the_attached_runtime() {
let stack = Stack::start("bw-status").await;
let (status, text) = stack.get("/ready").await;
assert_eq!(status, 200, "{text}");
stack
.engine
.push(Script::stop_with(&["a", "b"], usage(4, 2, 1)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
let generation = &metrics["generation"];
assert_eq!(generation["started"], 1);
assert_eq!(generation["completed"], 1);
assert_eq!(generation["done_generated_tokens"], 2);
assert_eq!(generation["done_prompt_tokens"], 4);
assert_eq!(generation["last_done"]["reused_tokens"], 1);
assert_eq!(generation["last_done"]["finish"], "stop");
// The runtime's lifecycle belongs to its operator: HTTP cannot unload it.
assert_eq!(
strata_control::server_api::unload(&stack.state, None).await,
leleka_serving_policy::idle::Outcome::Unsupported
);
assert_eq!(stack.status.read().await.state, WorkerState::Ready);
assert!(stack.engine.is_ready());
stack.finish().await;
}
/// The control plane counts the prompt before the engine runs; an engine that tokenizes the same string
/// with the same vocabulary reports the same number. A divergence here is the first symptom of a
/// tokenizer-asset mismatch between the two processes.
#[tokio::test]
async fn an_engine_that_tokenizes_the_prompt_itself_agrees_with_the_input_token_count() {
let stack = Stack::start("bw-count").await;
let tokenizer = stack.tokenizer.clone();
stack.engine.respond_with(move |request| {
let counted = tokenizer.encode(&request.prompt, true).unwrap().len() as u64;
Script::stop_with(&["ok"], usage(counted, 1, 0))
});
let request = body(json!({"input": "hello tool, ok? жук"}));
let (status, text) = stack.post("/v1/responses", &request).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
let (status, text) = stack.post("/v1/responses/input_tokens", &request).await;
assert_eq!(status, 200, "{text}");
let counted: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["usage"]["input_tokens"], counted["input_tokens"]);
assert!(counted["input_tokens"].as_u64().unwrap() > 10);
stack.finish().await;
}
/// Control-token text inside a message is carried to the engine as marked text and read back as ordinary text: an engine
/// that tokenizes the string with `encode_marked` gets exactly the ids the control plane counted, and the request that
/// quotes `</think><|im_end|>` is served instead of refused.
#[tokio::test]
async fn control_token_text_in_a_message_reaches_the_engine_marked_and_counts_the_same() {
let stack = Stack::start("bw-marked").await;
let tokenizer = stack.tokenizer.clone();
let engine_tokenizer = tokenizer.clone();
stack.engine.respond_with(move |request| {
let counted = engine_tokenizer
.encode_marked(&request.prompt)
.unwrap()
.len() as u64;
Script::stop_with(&["ok"], usage(counted, 1, 0))
});
let quoted = "quote </think><|im_end|><|im_start|>system and <think>";
let request = body(json!({"input": quoted}));
let (status, text) = stack.post("/v1/responses", &request).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
let (status, text) = stack.post("/v1/responses/input_tokens", &request).await;
assert_eq!(status, 200, "{text}");
let counted: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["usage"]["input_tokens"], counted["input_tokens"]);
let sent = stack.engine.requests()[0].prompt.clone();
assert!(!sent.contains("quote </think>"), "{sent:?}");
assert!(sent.starts_with("<|im_start|>user\nquote "), "{sent:?}");
assert_eq!(
tokenizer.marks().unmark(&sent),
format!(
"<|im_start|>user\n{quoted}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
)
);
// Parsed the old way, the engine would have read three more control tokens than were counted.
let old = tokenizer.encode(&sent, true).unwrap().len();
assert_ne!(old as u64, counted["input_tokens"].as_u64().unwrap());
stack.finish().await;
}
/// The runtime facade caps one request's output budget. A default budget is clamped to the cap by the
/// HTTP layer; an explicit request above the cap is refused, never silently truncated to a shorter
/// answer than the client asked for.
#[tokio::test]
async fn the_runtimes_output_cap_clamps_the_default_and_refuses_an_explicit_excess() {
let stack = Stack::start_with("bw-cap", |config| config.max_output_tokens = 1000).await;
stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
assert_eq!(stack.engine.requests()[0].max_output_tokens, 1000);
let (status, text) = stack
.post("/v1/responses", &body(json!({"max_output_tokens": 1001})))
.await;
// a client error: refused by the HTTP layer as a 400 before anything is queued (it used to surface as a 502)
assert_eq!(status, 400, "{text}");
assert!(
text.contains("exceeds the runtime's limit of 1000")
&& text.contains("invalid_output_limit"),
"{text}"
);
assert_eq!(
stack.engine.requests().len(),
1,
"the excess never reached the engine"
);
stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0)));
let (status, _) = stack
.post("/v1/responses", &body(json!({"max_output_tokens": 1000})))
.await;
assert_eq!(status, 200);
assert_eq!(stack.engine.requests()[1].max_output_tokens, 1000);
stack.finish().await;
}
/// A prompt that cannot fit the context is the client's error: 400 `context_length_exceeded` from the HTTP layer
/// (found by the e2e run: it used to be a 502 `generation_failed` after queueing), and a default output budget leaves
/// the engine's 8-token margin so a prompt that just fits is served instead of refused.
#[tokio::test]
async fn a_prompt_that_cannot_fit_the_context_is_a_400_and_the_default_budget_keeps_the_margin() {
let stack = Stack::start_with("bw-context", |config| config.max_context = 600).await;
// explicit budget that does not fit
let (status, text) = stack
.post("/v1/responses", &body(json!({"max_output_tokens": 4000})))
.await;
assert_eq!(status, 400, "{text}");
assert!(text.contains("context_length_exceeded"), "{text}");
// a prompt longer than the context
let long = "word ".repeat(2000);
let (status, text) = stack
.post("/v1/responses", &body(json!({"input": long})))
.await;
assert_eq!(status, 400, "{text}");
assert!(text.contains("context_length_exceeded"), "{text}");
assert!(
stack.engine.requests().is_empty(),
"nothing reached the engine"
);
// a request that fits, with the default budget: prompt + max_new + 8 == context at most
stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
let seen = &stack.engine.requests()[0];
let prompt_tokens = stack.tokenizer.encode(&seen.prompt, true).unwrap().len();
assert!(
prompt_tokens + seen.max_output_tokens as usize + 8 <= 600,
"{} + {} + 8 > 600",
prompt_tokens,
seen.max_output_tokens
);
stack.finish().await;
}
#[tokio::test]
async fn every_sampling_control_reaches_the_engine_as_fixed_point() {
let stack = Stack::start("bw-sampling").await;
stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0)));
let (status, text) = stack
.post(
"/v1/responses",
&body(
json!({"temperature": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.05,
"repetition_penalty": 1.1, "frequency_penalty": -0.5, "presence_penalty": 0.25,
"penalty_last_n": 128, "seed": 99}),
),
)
.await;
assert_eq!(status, 200, "{text}");
let sent = &stack.engine.requests()[0];
assert_eq!(sent.temperature_milli, 700);
let s = &sent.sampling;
assert_eq!(s.top_p_micro, Some(900_000));
assert_eq!(s.top_k, Some(40));
assert_eq!(s.min_p_micro, Some(50_000));
assert_eq!(s.repetition_penalty_micro, Some(1_100_000));
assert_eq!(s.frequency_penalty_micro, Some(-500_000));
assert_eq!(s.presence_penalty_micro, Some(250_000));
assert_eq!(s.penalty_last_n, Some(128));
assert_eq!(s.seed, Some(99));
// An unset control keeps the Original's default: nothing is invented on the way.
stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
let plain = &stack.engine.requests()[1];
assert_eq!(plain.temperature_milli, 0);
assert_eq!(plain.sampling.top_p_micro, None);
assert_eq!(plain.sampling.seed, None);
stack.finish().await;
}
fn shell_tool() -> Value {
json!({"type": "function", "name": "shell", "description": "Run a command", "strict": false,
"parameters": {"type": "object",
"properties": {"command": {"type": "array", "items": {"type": "string"}}},
"required": ["command"]}})
}
/// The request shape of the Codex console (fields and values as it sends them), two turns, stateless
/// replay of the first turn's output items, through the runtime stack. Synthetic prompts and scripted
/// engine output: this checks that the surface is accepted and the protocol holds, not Codex itself.
#[tokio::test]
async fn a_codex_shaped_request_streams_reasoning_and_a_tool_call_and_replays_statelessly() {
let stack = Stack::start("bw-codex").await;
let turn_one = json!({
"model": "fixture",
"instructions": "You are a coding agent.",
"input": [{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "List the files."}]}],
"tools": [shell_tool()],
"tool_choice": "auto",
"parallel_tool_calls": false,
"reasoning": {"effort": "medium", "summary": "auto"},
"store": false,
"stream": true,
"include": ["reasoning.encrypted_content"],
"prompt_cache_key": "019a0000-0000-7000-8000-000000000000",
"text": {"verbosity": "low"},
"service_tier": "priority",
"client_metadata": {"x-codex-installation-id": "synthetic-installation"}
});
let markup = "The user wants a listing.</think>\n\n<tool_call>\n<function=shell>\n<parameter=command>\n[\"ls\",\"-la\"]\n</parameter>\n</function>\n</tool_call>";
scripted_text(&stack.engine, markup, 11);
let (status, text) = stack.post("/v1/responses", &turn_one).await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
let kinds: Vec<&str> = events.iter().map(|e| e["type"].as_str().unwrap()).collect();
assert!(
kinds.contains(&"response.reasoning_text.delta"),
"{kinds:?}"
);
assert!(
kinds.contains(&"response.function_call_arguments.done"),
"{kinds:?}"
);
let response = events.last().unwrap()["response"].clone();
assert_eq!(response["store"], json!(false));
let output = response["output"].as_array().unwrap().clone();
let reasoning = output.iter().find(|i| i["type"] == "reasoning").unwrap();
assert_eq!(reasoning["content"][0]["text"], "The user wants a listing.");
let call = output
.iter()
.find(|i| i["type"] == "function_call")
.unwrap()
.clone();
assert_eq!(call["name"], "shell");
assert_eq!(
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
json!({"command": ["ls", "-la"]})
);
// The prompt the engine saw: the instructions as the system turn, thinking opened for the model.
let prompt = stack.engine.requests()[0].prompt.clone();
assert!(prompt.starts_with("<|im_start|>system\n"), "{prompt}");
assert!(prompt.contains("You are a coding agent."), "{prompt}");
assert!(prompt.contains("List the files."), "{prompt}");
assert!(prompt.ends_with("<think>\n"), "{prompt}");
assert_eq!(stack.engine.requests()[0].max_output_tokens, 4096);
// store:false really stores nothing.
let (status, _) = stack
.get(&format!(
"/v1/responses/{}",
response["id"].as_str().unwrap()
))
.await;
assert_eq!(status, 404);
// Turn two replays the whole transcript, the way a stateless client does.
let mut input = turn_one["input"].as_array().unwrap().clone();
input.extend(output);
input.push(
json!({"type": "function_call_output", "call_id": call["call_id"],
"output": "Cargo.toml\nsrc"}),
);
let mut turn_two = turn_one.clone();
turn_two["input"] = Value::Array(input);
turn_two["reasoning"] = json!({"effort": "medium", "summary": "auto"});
scripted_text(
&stack.engine,
"There are two entries.</think>\n\nCargo.toml and src.",
13,
);
let (status, text) = stack.post("/v1/responses", &turn_two).await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
let final_text = text_of(&events.last().unwrap()["response"]);
assert_eq!(final_text, "Cargo.toml and src.");
let second = &stack.engine.requests()[1].prompt;
assert!(second.contains("Cargo.toml\nsrc"), "{second}");
assert!(second.contains("The user wants a listing."), "{second}");
assert!(second.contains("<function=shell>"), "{second}");
stack.finish().await;
}
#[tokio::test]
async fn codex_tool_choice_and_parallel_calls_are_enforced_on_the_generated_calls() {
let stack = Stack::start("bw-toolchoice").await;
let two_calls = format!(
"{}\n{}",
tool_markup("shell", &json!({"command": ["ls"]})),
tool_markup("shell", &json!({"command": ["pwd"]}))
);
let request = |extra: Value| {
let mut value = body(json!({"tools": [shell_tool()], "stream": true}));
for (key, item) in extra.as_object().unwrap() {
value[key] = item.clone();
}
value
};
// parallel_tool_calls:false + two calls => the response fails instead of publishing both.
scripted_text(&stack.engine, &two_calls, 17);
let (_, text) = stack
.post(
"/v1/responses",
&request(json!({"parallel_tool_calls": false})),
)
.await;
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
// parallel allowed => both calls arrive.
scripted_text(&stack.engine, &two_calls, 17);
let (_, text) = stack
.post(
"/v1/responses",
&request(json!({"parallel_tool_calls": true})),
)
.await;
let events = sse_events(&text);
assert_eq!(events.last().unwrap()["type"], "response.completed");
let calls = events.last().unwrap()["response"]["output"]
.as_array()
.unwrap()
.iter()
.filter(|i| i["type"] == "function_call")
.count();
assert_eq!(calls, 2);
// tool_choice none + a call => failure; required + plain text => failure; forced name mismatch.
scripted_text(
&stack.engine,
&tool_markup("shell", &json!({"command": ["ls"]})),
17,
);
let (_, text) = stack
.post("/v1/responses", &request(json!({"tool_choice": "none"})))
.await;
assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed");
scripted_text(&stack.engine, "just words", 17);
let (_, text) = stack
.post(
"/v1/responses",
&request(json!({"tool_choice": "required"})),
)
.await;
assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed");
scripted_text(
&stack.engine,
&tool_markup("shell", &json!({"command": ["ls"]})),
17,
);
let (_, text) = stack
.post(
"/v1/responses",
&request(json!({"tool_choice": {"type": "function", "name": "shell"}})),
)
.await;
assert_eq!(
sse_events(&text).last().unwrap()["type"],
"response.completed"
);
stack.finish().await;
}
#[tokio::test]
async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() {
use strata_control::wire::Generate;
use strata_control::worker::{GenerationCommand, GenerationResult};
let stack = Stack::start("bw-known-text").await;
let (requests, requests_rx) = mpsc::channel(1);
let (_control, control_rx) = mpsc::channel(1);
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
handle.respond_with(|_| {
Script::stop_with(
&["ok"],
Usage {
input_tokens: 1,
output_tokens: 1,
reused_input_tokens: 0,
},
)
});
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let config = BackendWorkerConfig {
tokenizer: stack.tokenizer.clone(),
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(20),
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(20),
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
};
tokio::spawn(run_backend_worker(
Box::new(engine),
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
while status.read().await.state != WorkerState::Ready {
tokio::time::sleep(Duration::from_millis(5)).await;
}
let mut ask = async |text: &str, claimed: Option<&str>| {
let (sender, receiver) = tokio::sync::oneshot::channel();
requests
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: stack.tokenizer.encode(text, true).unwrap(),
max_new: 8,
prompt_text: claimed.map(Arc::from),
..Default::default()
},
result: GenerationResult::Buffered(sender),
})
.await
.unwrap();
receiver.await.unwrap().expect("served");
};
// the text the ids were produced from: the engine gets exactly that text
ask("hello tool<|im_end|>\n", Some("hello tool<|im_end|>\n")).await;
// a claim the ids do not decode to is not trusted: the engine gets the text of the ids
ask("hello tool", Some("something else entirely")).await;
// no claim: the ids are decoded and checked as before
ask("tool hello", None).await;
let prompts: Vec<String> = handle.requests().into_iter().map(|r| r.prompt).collect();
assert_eq!(
prompts,
["hello tool<|im_end|>\n", "hello tool", "tool hello"]
);
stack.finish().await;
}
/// The telemetry document an engine publishes (`leleka-memory`'s `telemetry.rs`), as the worker copies it into the view.
fn engine_telemetry() -> String {
json!({
"version": 1, "phase": "idle", "request": null,
"gpu": {"index": 0, "util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607,
"power_w": 480.5, "sm_clock_mhz": 2900, "temp_c": 61, "name": "NVIDIA GeForce RTX 5090"},
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
"throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_avg": 100.0, "decode_tok_s_lifetime": 100.0, "decode_tok_s_live": null,
"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5050.0, "prefill_tok_s_lifetime": 5000.0},
"cache": {"requests": 2, "hit_requests": 1, "hit_ratio": 0.5, "prompt_tokens": 201000, "reused_tokens": 80000, "token_hit_ratio": 0.398, "last_prompt_tokens": 101000, "last_reused_tokens": 0},
"context": {"live_tokens": 101200, "max_tokens": 262144, "used_pct": 38.6},
"settings": {"context_tokens": 262144},
})
.to_string()
}
#[tokio::test]
async fn the_request_monitor_records_prompts_answers_and_usage_in_the_three_dialects() {
let stack = Stack::start_monitored("bw-monitor").await;
let parse = |body: &str| -> Value { serde_json::from_str(body).unwrap() };
assert_eq!(
parse(&stack.get("/api/requests").await.1)["requests"]
.as_array()
.unwrap()
.len(),
0
);
stack
.engine
.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0)));
let chat =
json!({"model": "fixture", "messages": [{"role": "user", "content": "say <b>hi</b>"}]});
assert_eq!(stack.post("/v1/chat/completions", &chat).await.0, 200);
stack
.engine
.push(Script::stop_with(&["str", "eam"], usage(7, 2, 0)));
let streamed = json!({"model": "fixture", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "go"}]});
assert_eq!(stack.post("/v1/chat/completions", &streamed).await.0, 200);
stack
.engine
.push(Script::stop_with(&["res", "p"], usage(4, 2, 1)));
assert_eq!(
stack
.post("/v1/responses", &body(json!({"stream": true})))
.await
.0,
200
);
stack
.engine
.push(Script::stop_with(&["whole"], usage(4, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
// a refused request is recorded as an error with its status, not as a success
let (status, _) = stack
.post(
"/v1/responses",
&json!({"model": "fixture", "input": "x", "bogus": 1}),
)
.await;
assert!(status >= 400);
let listed = parse(&stack.get("/api/requests").await.1);
assert_eq!(listed["retention"], 100);
assert_eq!(listed["persistent"], false);
assert_eq!(listed["loaded"], true);
let rows = listed["requests"].as_array().unwrap();
assert_eq!(rows.len(), 5);
// newest first: the refusal, then the buffered Responses, the streamed Responses, the streamed Chat, the buffered Chat
assert_eq!(rows[0]["state"], "error");
assert!(rows[0]["http_status"].as_u64().unwrap() >= 400);
let expected = [
("/v1/responses", "whole"),
("/v1/responses", "resp"),
("/v1/chat/completions", "stream"),
("/v1/chat/completions", "hello"),
];
for (row, (path, output)) in rows[1..].iter().zip(expected) {
assert_eq!(row["path"], path);
assert_eq!(row["state"], "completed", "{row}");
assert_eq!(row["http_status"], 200);
assert!(
row.get("input").is_none() && row.get("output").is_none(),
"summaries carry no payload"
);
assert!(row["wallclock_s"].as_f64().unwrap() >= row["first_token_s"].as_f64().unwrap());
let detail = parse(
&stack
.get(&format!("/api/requests?id={}", row["id"].as_str().unwrap()))
.await
.1,
);
assert_eq!(detail["output"], output, "{detail}");
assert!(
detail["input"]
.as_str()
.unwrap()
.contains("\"model\": \"fixture\"")
);
assert!(detail["usage"].is_object(), "{detail}");
assert_eq!(detail["model"], "fixture");
}
let streamed_chat = parse(
&stack
.get(&format!(
"/api/requests?id={}",
rows[3]["id"].as_str().unwrap()
))
.await
.1,
);
assert_eq!(streamed_chat["stream"], true);
assert!(
streamed_chat.get("response").is_none(),
"a stream has no single response body"
);
let buffered_chat = parse(
&stack
.get(&format!(
"/api/requests?id={}",
rows[4]["id"].as_str().unwrap()
))
.await
.1,
);
assert_eq!(
parse(buffered_chat["response"].as_str().unwrap())["choices"][0]["message"]["content"],
"hello"
);
assert!(
buffered_chat["input"]
.as_str()
.unwrap()
.contains("say <b>hi</b>")
);
assert_eq!(stack.get("/api/requests?id=missing").await.0, 404);
stack.finish().await;
}
#[tokio::test]
async fn the_request_monitor_is_off_by_default_and_keeps_nothing() {
let stack = Stack::start("bw-monitor-off").await;
stack.engine.push(Script::stop_with(&["x"], usage(2, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
let (status, text) = stack.get("/api/requests").await;
assert_eq!(status, 404, "{text}");
assert_eq!(stack.get("/api/requests?id=anything").await.0, 404);
assert!(stack.state.monitor.summaries().is_empty());
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
assert_eq!(metrics["engine"]["api_monitor"], false);
// an engine that publishes no telemetry (yet): empty hardware blocks, no raw document, the rest of the document intact
assert_eq!(metrics["hardware"], json!({}));
assert_eq!(metrics["hardware_static"], json!({}));
assert!(metrics["telemetry"].is_null());
assert_eq!(metrics["requests_kept"], 1);
stack.finish().await;
}
#[tokio::test]
async fn metrics_carry_the_python_monitor_members_and_a_prometheus_view() {
let stack = Stack::start("bw-metrics-monitor").await;
stack.state.memory.set_telemetry(Some(engine_telemetry()));
stack
.engine
.push(Script::stop_with(&["a", "b"], usage(10, 2, 4)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
stack.engine.push(Script::stop_with(&["c"], usage(6, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
// the native members are untouched
assert_eq!(metrics["schema_version"], 1);
assert_eq!(metrics["generation"]["completed"], 2);
// the Python Monitor members
assert_eq!(metrics["engine"]["model"], "fixture");
assert_eq!(metrics["engine"]["max_context"], 262_144);
assert_eq!(metrics["engine"]["images"], false);
assert_eq!(metrics["live"]["state"], "idle");
assert_eq!(metrics["live"]["queued"], 0);
assert_eq!(metrics["requests_kept"], 2);
let requests = metrics["requests"].as_array().unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0]["prompt_tokens"], 6);
assert_eq!(requests[1]["prompt_tokens"], 10);
assert_eq!(requests[1]["reused"], 4);
assert_eq!(requests[1]["output_tokens"], 2);
assert_eq!(requests[1]["finish"], "stop");
assert_eq!(metrics["totals"]["requests"], 2);
assert_eq!(metrics["totals"]["prompt_tokens"], 16);
assert_eq!(metrics["totals"]["reused"], 4);
assert_eq!(metrics["totals"]["output_tokens"], 3);
assert_eq!(metrics["hardware"]["gpu_util"], 91);
assert_eq!(metrics["hardware"]["gpu_mem_used"], 30000u64 * 1_048_576);
assert_eq!(metrics["hardware"]["gpu_temp"], 61);
assert_eq!(metrics["hardware"]["tok_s"], 0.0);
assert_eq!(
metrics["hardware_static"]["gpu_name"],
"NVIDIA GeForce RTX 5090"
);
assert_eq!(metrics["history"]["gpu_util"].as_array().unwrap().len(), 1);
assert!(metrics["time"].as_f64().unwrap() > 1.0e9);
assert_eq!(metrics["telemetry"]["context"]["max_tokens"], 262_144);
// `?requests=all` lists everything kept (here the same two)
let all: Value = serde_json::from_str(&stack.get("/metrics?requests=all").await.1).unwrap();
assert_eq!(all["requests"].as_array().unwrap().len(), 2);
// Prometheus text: by query and by the Accept header a scraper sends
let scrape = |accept: Option<&str>, query: &str| {
let mut request = stack.client.get(format!("{}/metrics{query}", stack.base));
if let Some(accept) = accept {
request = request.header("accept", accept);
}
request
};
for (accept, query) in [
(None, "?format=prometheus"),
(
Some(
"application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1",
),
"",
),
] {
let response = scrape(accept, query).send().await.unwrap();
assert_eq!(response.status(), 200);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("text/plain; version=0.0.4")
);
let text = response.text().await.unwrap();
assert!(
text.contains("leleka_generations_completed_total 2\n"),
"{text}"
);
assert!(
text.contains("leleka_prompt_tokens_total 16\n")
&& text.contains("leleka_prompt_tokens_reused_total 4\n")
);
assert!(text.contains("leleka_generated_tokens_total 3\n"));
assert!(text.contains("leleka_up 1\n"));
assert!(text.contains("leleka_gpu_utilization_percent 91\n"));
assert!(text.contains("leleka_gpu_memory_used_bytes 31457280000\n"));
assert!(text.contains("leleka_gpu_temperature_celsius 61\n"));
assert!(
text.contains("leleka_host_memory_used_bytes 55448698880\n"),
"{text}"
);
assert!(
text.contains("leleka_context_live_tokens 101200\n")
&& text.contains("leleka_context_max_tokens 262144\n")
);
assert!(text.contains("leleka_prefix_cache_token_hit_ratio 0.398\n"));
assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 100\n"));
assert!(text.contains("leleka_engine_phase{phase=\"idle\"} 1\n"));
}
// a JSON client keeps getting JSON
let json_reply = scrape(Some("application/json"), "").send().await.unwrap();
assert_eq!(json_reply.headers()["content-type"], "application/json");
stack.finish().await;
}