Files
leleka/control-plane/tests/vision_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

603 lines
22 KiB
Rust

#![cfg(unix)]
//! Pictures over HTTP in the three dialects (Chat Completions, Messages, Responses): the request is parsed, the
//! template writes `<|vision_start|><|image_pad|><|vision_end|>` per picture, the resident encoder (a stand-in for
//! `strata-vision`) is asked for the rows, every pad becomes one pad per row and the engine receives `GENI` with the
//! embeddings file. The engine is the mock in `tests/fixtures/mock_engine.sh` (mode `images`).
use std::{
fs,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use leleka_serving_policy::vision as policy;
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
vision::{Vision, VisionConfig},
worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised},
};
use tokio::sync::{RwLock, mpsc, watch};
mod common;
use common::{END, PAD, SPECIALS, START, scratch, tokenizer};
fn png(tag: u8) -> Vec<u8> {
let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
data.push(tag);
data
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
for i in 0..4 {
out.push(if i <= chunk.len() {
ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char
} else {
'='
});
}
}
out
}
fn data_url(tag: u8) -> String {
format!("data:image/png;base64,{}", base64(&png(tag)))
}
fn fake_encoder(dir: &Path, mode: &str) -> VisionConfig {
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let wrapper = dir.join("strata-vision.sh");
fs::write(
&wrapper,
format!(
"#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n",
fixtures.join("fake_vision.sh").display(),
dir.display()
),
)
.unwrap();
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
serde_json::from_value(
json!({"exe": wrapper, "mmproj": "/m/mmproj.gguf", "model": "/m/model.gguf"}),
)
.unwrap()
}
struct Harness {
base: String,
dir: PathBuf,
state: AppState,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
client: reqwest::Client,
}
impl Harness {
async fn start(name: &str, encoder: Option<&str>) -> Self {
let dir = scratch(name);
let tokenizer = tokenizer(&dir);
let vision = match encoder {
Some(mode) => Some(Vision::start(fake_encoder(&dir, mode)).await.unwrap()),
None => None,
};
let engine = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh");
let config = WorkerConfig {
executable: engine.into_os_string(),
args: vec![
"images".into(),
dir.to_string_lossy().into_owned(),
"x".into(),
],
startup_timeout: Duration::from_secs(10),
vision: vision.clone(),
..Default::default()
};
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(4);
let (control, control_rx) = mpsc::channel(4);
let worker = tokio::spawn(run_supervised(
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let state = AppState {
model: Some("strata-test".into()),
worker: status,
generation: Some(requests),
control: Some(control),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
vision,
..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;
});
tokio::time::timeout(Duration::from_secs(10), async {
while state.worker.read().await.state != WorkerState::Ready {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker ready");
Self {
base,
dir,
state,
stop,
worker,
server,
client: reqwest::Client::new(),
}
}
async fn post(&self, path: &str, body: Value) -> (u16, Value) {
let response = self
.client
.post(format!("{}{path}", self.base))
.header("content-type", "application/json")
.header("anthropic-version", "2023-06-01")
.body(body.to_string())
.send()
.await
.unwrap();
let status = response.status().as_u16();
(
status,
serde_json::from_str(&response.text().await.unwrap()).unwrap_or(Value::Null),
)
}
async fn get(&self, path: &str) -> Value {
serde_json::from_str(
&self
.client
.get(format!("{}{path}", self.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap(),
)
.unwrap()
}
fn lines(&self, file: &str) -> Vec<String> {
fs::read_to_string(self.dir.join(file))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
/// The engine lines of this run: what the mock logged for each GEN / GENI.
fn engine_lines(&self) -> Vec<String> {
self.lines("requests")
}
async fn finish(self) {
self.server.abort();
self.stop.send(true).unwrap();
let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await;
if let Some(vision) = &self.state.vision {
vision.close().await;
}
let _ = fs::remove_dir_all(self.dir);
}
}
/// `(max_new, embeddings path, ids)` of a `GENI` line.
fn geni_line(line: &str) -> (u32, String, Vec<u32>) {
let fields: Vec<&str> = line.split(' ').collect();
assert_eq!(fields[0], "GENI", "{line}");
let ids = fields
.last()
.unwrap()
.split(',')
.map(|n| n.parse().unwrap())
.collect();
(
fields[1].parse().unwrap(),
fields[fields.len() - 2].to_owned(),
ids,
)
}
/// Every maximal run of pads, with the token before and after it.
fn pad_runs(ids: &[u32]) -> Vec<(u32, usize, u32)> {
let mut runs = Vec::new();
let mut at = 0;
while at < ids.len() {
if ids[at] == PAD {
let from = at;
while at < ids.len() && ids[at] == PAD {
at += 1;
}
runs.push((ids[from - 1], at - from, ids[at]));
} else {
at += 1;
}
}
runs
}
async fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
for _ in 0..200 {
if ready() {
return;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("timed out waiting for {what}");
}
#[tokio::test]
async fn chat_messages_and_responses_pictures_reach_the_engine_as_geni() {
let h = Harness::start("dialects", Some("ok")).await;
// Chat Completions: image_url as an object with detail, and as a bare string
let (status, body) = h
.post(
"/v1/chat/completions",
json!({"model": "strata-test", "max_tokens": 20, "messages": [{"role": "user", "content": [
{"type": "text", "text": "what is this?"},
{"type": "image_url", "image_url": {"url": data_url(1), "detail": "high"}},
{"type": "image_url", "image_url": data_url(2)},
]}]}),
)
.await;
assert_eq!(status, 200, "{body}");
assert_eq!(body["choices"][0]["message"]["content"], "Hi");
// Messages: base64 source
let (status, body) = h
.post(
"/v1/messages",
json!({"model": "strata-test", "max_tokens": 20, "messages": [{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": base64(&png(3))}},
{"type": "text", "text": "and this?"},
]}]}),
)
.await;
assert_eq!(status, 200, "{body}");
assert_eq!(body["content"][0]["text"], "Hi");
// Responses: input_image
let (status, body) = h
.post(
"/v1/responses",
json!({"model": "strata-test", "max_output_tokens": 20, "store": false, "reasoning": {"effort": "none"},
"input": [{"role": "user", "content": [
{"type": "input_text", "text": "look"},
{"type": "input_image", "image_url": data_url(1)}]}]}),
)
.await;
assert_eq!(status, 200, "{body}");
assert_eq!(body["output"][0]["content"][0]["text"], "Hi");
let lines = h.engine_lines();
let sent: Vec<&String> = lines.iter().filter(|l| l.starts_with("GENI")).collect();
assert_eq!(sent.len(), 3, "{lines:?}");
// Chat: two pictures, six rows each, in prompt order, text before them
let (max_new, path, ids) = geni_line(sent[0]);
assert!(
max_new > 0 && path.contains("/req-") && path.ends_with(".sve"),
"{}",
sent[0]
);
assert_eq!(pad_runs(&ids), vec![(START, 6, END), (START, 6, END)]);
let text = String::from_utf8_lossy(
&ids.iter()
.filter(|id| **id < 256)
.map(|id| *id as u8)
.collect::<Vec<_>>(),
)
.into_owned();
assert!(text.contains("what is this?"), "{text}");
// Messages: the picture comes first in the user turn
let (_, _, ids) = geni_line(sent[1]);
assert_eq!(pad_runs(&ids), vec![(START, 6, END)]);
let at = ids.iter().position(|id| *id == START).unwrap();
let after = String::from_utf8_lossy(
&ids[at + 8..]
.iter()
.take_while(|id| **id < 256)
.map(|id| *id as u8)
.collect::<Vec<_>>(),
)
.into_owned();
assert!(after.starts_with("and this?"), "{after}");
// Responses
let (_, _, ids) = geni_line(sent[2]);
assert_eq!(pad_runs(&ids), vec![(START, 6, END)]);
// the engine saw a non-empty embeddings file for each (the mock checks at request time)
assert_eq!(
lines.iter().filter(|l| *l == "embeddings-present").count(),
3,
"{lines:?}"
);
// the encoder ran for three distinct pictures only (picture 1 was sent twice)
assert_eq!(h.lines("enc.log").len(), 3);
// the per-request files go with their requests
let vision_dir = h.state.vision.as_ref().unwrap().dir().to_path_buf();
wait_for("req files removed", || {
fs::read_dir(&vision_dir)
.unwrap()
.all(|e| !e.unwrap().file_name().to_string_lossy().starts_with("req-"))
})
.await;
// the combined file of the first request held two SVE1 records
let (status, _) = h.post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": "plain"}]})).await;
assert_eq!(status, 200);
assert!(
h.engine_lines().last().unwrap().starts_with("GEN "),
"text requests stay GEN"
);
// streaming Chat with a picture
let response = h
.client
.post(format!("{}/v1/chat/completions", h.base))
.header("content-type", "application/json")
.body(json!({"model": "strata-test", "max_tokens": 20, "stream": true, "messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": data_url(1)}}]}]}).to_string())
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
let text = response.text().await.unwrap();
assert!(text.contains("\"Hi\"") || text.contains("H"), "{text}");
assert!(
h.engine_lines()
.iter()
.filter(|l| l.starts_with("GENI"))
.count()
== 4
);
h.finish().await;
}
#[tokio::test]
async fn pictures_need_the_encoder_and_a_readable_image() {
// without the encoder: the Python server's words, in each dialect
let h = Harness::start("noenc", None).await;
let message = "this server was started without the vision encoder (run setup again and choose 'vision'), so it cannot read images";
for (path, body) in [
(
"/v1/chat/completions",
json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]}),
),
(
"/v1/messages",
json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": "http://x/y.png"}}]}]}),
),
(
"/v1/responses",
json!({"model": "strata-test", "store": false, "input": [{"role": "user", "content": [{"type": "input_image", "image_url": data_url(1)}]}]}),
),
] {
let (status, body) = h.post(path, body).await;
assert_eq!(status, 400, "{path} {body}");
let text = body.to_string();
assert!(text.contains(message), "{path} {text}");
}
assert!(h.engine_lines().is_empty());
assert_eq!(h.get("/props").await["modalities"]["vision"], false);
assert_eq!(h.get("/v1/status").await["vision"]["enabled"], false);
assert_eq!(h.get("/api/health").await["images"], false);
h.finish().await;
// an encoder that cannot read the picture
let h = Harness::start("bad-image", Some("err")).await;
let (status, body) = h
.post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]}))
.await;
assert_eq!(status, 400, "{body}");
assert!(
body.to_string()
.contains("the image could not be read: cannot read the image"),
"{body}"
);
// unsupported formats and unreadable sources
for (url, want) in [
(
"data:image/webp;base64,UklGRg==",
"this image format is not supported",
),
(
"no/such/file.png",
"an image must be a data: URL, an http(s) URL or a local file path",
),
(
"",
"an image must be a data: URL, an http(s) URL or a local file path",
),
] {
let (status, body) = h
.post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}}]}]}))
.await;
assert_eq!(status, 400, "{body}");
assert!(body.to_string().contains(want), "{body}");
}
assert!(h.engine_lines().is_empty());
h.finish().await;
}
#[tokio::test]
async fn token_counters_do_not_start_the_encoder_and_count_one_pad_per_picture() {
let h = Harness::start("count", Some("ok")).await;
let count = |n: usize| {
h.post(
"/v1/messages/count_tokens",
json!({"model": "strata-test", "messages": [{"role": "user", "content": (0..n)
.map(|i| json!({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": base64(&png(i as u8))}}))
.collect::<Vec<_>>()}]}),
)
};
let (status, one) = count(1).await;
assert_eq!(status, 200, "{one}");
let (_, three) = count(3).await;
// three pictures add two more `<|vision_start|><|image_pad|><|vision_end|>` triples: 6 tokens
assert_eq!(
three["input_tokens"].as_u64().unwrap() - one["input_tokens"].as_u64().unwrap(),
6
);
assert!(h.lines("enc.log").is_empty(), "counting never encodes");
let (status, body) = h
.post(
"/v1/responses/input_tokens",
json!({"model": "strata-test", "input": [{"role": "user", "content": [{"type": "input_image", "image_url": data_url(1)}]}]}),
)
.await;
assert_eq!(status, 200, "{body}");
assert!(h.lines("enc.log").is_empty());
h.finish().await;
}
#[tokio::test]
async fn unload_stops_the_encoder_and_the_next_request_starts_it_before_the_engine() {
let h = Harness::start("lifecycle", Some("ok")).await;
assert_eq!(h.get("/props").await["modalities"]["vision"], true);
assert_eq!(h.get("/v1/status").await["vision"]["available"], true);
assert_eq!(h.get("/api/health").await["images"], true);
assert_eq!(
h.get("/v1/models").await["data"][0]["architecture"]["input_modalities"],
json!(["text", "image"])
);
let vision = h.state.vision.clone().unwrap();
let body = json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]});
assert_eq!(h.post("/v1/chat/completions", body.clone()).await.0, 200);
assert!(vision.alive().await);
let (status, answer) = h.post("/unload", json!({})).await;
assert_eq!(status, 200, "{answer}");
assert!(
!vision.alive().await,
"unloading the model unloads the encoder"
);
// the cached picture needs no encoder, but the request restarts both
assert_eq!(h.post("/v1/chat/completions", body).await.0, 200);
assert!(vision.alive().await);
assert_eq!(h.lines("starts.log").len(), 2);
assert_eq!(h.lines("boots").len(), 2);
h.finish().await;
}
#[test]
fn the_expansion_matches_the_engine_side_position_table() {
// The rows the encoder wrote line up with the pads the server sent: one SVE1 record of 6 rows per picture.
let mut record = Vec::new();
for v in [policy::SVE1_MAGIC, 6, 3, 2, 4] {
record.extend_from_slice(&v.to_le_bytes());
}
record.extend(std::iter::repeat_n(0u8, 6 * 4 * 4));
let embeddings = policy::parse_embeddings(&record, 4).unwrap();
let ids: Vec<i64> = [1, PAD, PAD, PAD, PAD, PAD, PAD, 9]
.iter()
.map(|v| i64::from(*v))
.collect();
let positions = policy::build_positions(&ids, 16, &embeddings, 4, i64::from(PAD)).unwrap();
assert_eq!(positions.images.len(), 1);
}
/// The ids of a request as the template wrote them: bytes as bytes, specials by name, and a run of the rows one
/// picture got collapsed back to the single `<|image_pad|>` of the template.
fn prompt_of(ids: &[u32], rows: usize) -> String {
let mut bytes = Vec::new();
let mut at = 0;
while at < ids.len() {
let id = ids[at];
if id == PAD {
assert!(
ids[at..].len() >= rows && ids[at..at + rows].iter().all(|i| *i == PAD),
"a full run of {rows} rows"
);
at += rows;
} else {
at += 1;
}
match id {
0..=255 => bytes.push(id as u8),
_ => bytes.extend(SPECIALS[id as usize - 256].bytes()),
}
}
String::from_utf8(bytes).unwrap()
}
/// The pictures' tag bytes (the last byte of each fake PNG) in the order the golden lists their sources.
fn tags_of(sources: &Value) -> Vec<String> {
sources
.as_array()
.unwrap()
.iter()
.map(|source| {
let payload = source.as_str().unwrap().split_once(',').unwrap().1;
format!(
"tag={}",
policy::b64decode(payload).unwrap().last().unwrap()
)
})
.collect()
}
/// Every Chat and Messages request of `fixtures/golden/vision_dialects.json` (recorded from the Python handlers
/// `openai_to_messages` / `anthropic_to_messages` and the chat template) reaches the engine as the same prompt, with
/// the same pictures in the same order.
#[tokio::test]
async fn pictures_render_and_order_like_the_python_handlers() {
let golden: Value =
serde_json::from_str(include_str!("fixtures/golden/vision_dialects.json")).unwrap();
let cases = golden["cases"].as_array().unwrap();
assert!(cases.len() >= 14);
let h = Harness::start("golden", Some("ok")).await;
let (mut sent, mut encoded) = (0, 0);
for (index, case) in cases.iter().enumerate() {
let mut body = case["request"].clone();
body["model"] = json!("strata-test");
body["max_tokens"] = json!(20);
let path = match case["dialect"].as_str().unwrap() {
"chat" => "/v1/chat/completions",
_ => "/v1/messages",
};
let (status, answer) = h.post(path, body).await;
assert_eq!(status, 200, "case {index}: {answer}");
let lines = h.engine_lines();
let geni: Vec<&String> = lines.iter().filter(|l| l.starts_with("GENI")).collect();
assert_eq!(geni.len(), sent + 1, "case {index}");
sent += 1;
let (_, _, ids) = geni_line(geni[sent - 1]);
assert_eq!(
prompt_of(&ids, 6),
case["prompt"].as_str().unwrap(),
"case {index}"
);
let want = tags_of(&case["images"]);
let log = h.lines("enc.log");
let got: Vec<String> = log[encoded..]
.iter()
.map(|l| l.rsplit(' ').next().unwrap().to_owned())
.collect();
encoded = log.len();
assert_eq!(got, want, "case {index}: pictures in prompt order");
}
h.finish().await;
}