diff --git a/control-plane/tests/common/mod.rs b/control-plane/tests/common/mod.rs new file mode 100644 index 00000000..e39e3445 --- /dev/null +++ b/control-plane/tests/common/mod.rs @@ -0,0 +1,73 @@ +//! Shared by the HTTP integration tests: a byte-level tokenizer with the template's special tokens. +#![allow(dead_code)] + +use std::{ + fs, + path::{Path, PathBuf}, + sync::Arc, +}; + +use serde_json::{Map, json}; +use strata_control::tokenizer::Tokenizer; + +pub const SPECIALS: [&str; 7] = [ + "<|im_start|>", + "<|im_end|>", + "", + "", + "<|vision_start|>", + "<|image_pad|>", + "<|vision_end|>", +]; +pub const PAD: u32 = 256 + 5; +pub const START: u32 = 256 + 4; +pub const END: u32 = 256 + 6; + +pub fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("strata-vision-http-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +pub fn tokenizer(dir: &Path) -> Arc { + let root = dir.join("tokenizer"); + fs::create_dir(&root).unwrap(); + let mut vocabulary = Map::new(); + for (id, ch) in strata_control::tokenizer::byte_alphabet() + .0 + .iter() + .enumerate() + { + vocabulary.insert(ch.to_string(), json!(id)); + } + for (offset, token) in SPECIALS.iter().enumerate() { + vocabulary.insert((*token).into(), json!(256 + offset)); + } + let total = 256 + SPECIALS.len(); + fs::write( + root.join("vocab.json"), + serde_json::to_vec(&vocabulary).unwrap(), + ) + .unwrap(); + fs::write(root.join("merges.txt"), "").unwrap(); + let mut types = vec![1u8; total]; + types[256..].fill(3); + fs::write( + root.join("token_type.json"), + serde_json::to_vec(&types).unwrap(), + ) + .unwrap(); + fs::write( + root.join("tokenizer.json"), + serde_json::to_vec(&json!({ + "model": "gpt2", "pre": "qwen35", "vocab_size": total, "n_merges": 0, + "pre_pattern": leleka_tokenizer::QWEN35_PATTERN, + "special_ids": {"tokenizer.ggml.eos_token_id": 257} + })) + .unwrap(), + ) + .unwrap(); + Arc::new(Tokenizer::from_assets(&root).unwrap()) +} diff --git a/control-plane/tests/fixtures/scripted_engine.rs b/control-plane/tests/fixtures/scripted_engine.rs new file mode 100644 index 00000000..2943f1a1 --- /dev/null +++ b/control-plane/tests/fixtures/scripted_engine.rs @@ -0,0 +1,76 @@ +// A scripted stand-in for `strata --serve`, compiled by tests/reasoning_budget_live.rs (std only). +// +// scripted_engine --serve DIR STOP_IDS +// +// DIR/script holds one line of comma-separated token ids per GEN/GENI the worker will send, in order. For each +// request the engine prints `T id` for the first max_new ids of the next line, ends early after a stop id (finish +// stop) or when it reads STOP (finish cancel), and logs "max_new ids" to DIR/requests. A STOP that arrives while no +// request runs is ignored, as the real engine does. +use std::io::{BufRead, Write}; +use std::sync::mpsc; + +fn main() { + let args: Vec = std::env::args().collect(); + let dir = std::path::PathBuf::from(&args[2]); + let stops: Vec = args[3].split(',').filter_map(|s| s.parse().ok()).collect(); + let script: Vec = std::fs::read_to_string(dir.join("script")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect(); + let (sender, lines) = mpsc::channel::(); + std::thread::spawn(move || { + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + if sender.send(line).is_err() { + break; + } + } + }); + let out = std::io::stdout(); + let mut out = out.lock(); + writeln!(out, "READY 1000000 stop").unwrap(); + out.flush().unwrap(); + let mut call = 0; + while let Ok(line) = lines.recv() { + if line == "QUIT" { + return; + } + if !line.starts_with("GEN") { + continue; // a late STOP + } + let fields: Vec<&str> = line.split(' ').collect(); + let max_new: usize = fields[1].parse().unwrap(); + let prompt = fields.last().unwrap(); + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("requests")) + .unwrap(); + writeln!(log, "{max_new} {prompt}").unwrap(); + let stream: Vec = script + .get(call) + .map(|l| l.split(',').filter_map(|s| s.parse().ok()).collect()) + .unwrap_or_default(); + call += 1; + let (mut sent, mut finish) = (0usize, "length"); + for id in stream.iter().take(max_new) { + if let Ok(next) = lines.try_recv() { + if next == "STOP" { + finish = "cancel"; + break; + } + } + writeln!(out, "T {id}").unwrap(); + out.flush().unwrap(); + sent += 1; + if stops.contains(id) { + finish = "stop"; + break; + } + } + let prompt_tokens = prompt.split(',').filter(|s| !s.is_empty()).count(); + writeln!(out, "DONE {sent} {prompt_tokens} 1.0 1.0 {finish}").unwrap(); + out.flush().unwrap(); + } +} diff --git a/control-plane/tests/reasoning_budget_live.rs b/control-plane/tests/reasoning_budget_live.rs new file mode 100644 index 00000000..9f650cfd --- /dev/null +++ b/control-plane/tests/reasoning_budget_live.rs @@ -0,0 +1,370 @@ +//! The reasoning-budget wrap-up on the LIVE worker path against the Python server's `Service.run` (#123). +//! +//! `tests/fixtures/offline/reasoning_budget_oracle.json` holds 400 generations of the unmodified `Service.run` over +//! a scripted engine. Here the same scripts are played by a scripted engine process (`fixtures/scripted_engine.rs`, +//! compiled with `rustc` at test time) behind the real worker supervisor, with the `ReasoningPlan` the Responses +//! path builds, and compared on what the Python run recorded: every request the engine received (prompt tail and +//! `max_new`), the finish reason, the completion tokens and the text the client was sent. +//! +//! Not replayed here: the 34 cases that cancel before the first token (the live path cancels by dropping the +//! client, which `worker::tests` and `scripts/smoke-worker-cancel.py` cover) and the cases with an empty prompt +//! (the engine protocol refuses `GEN` without prompt tokens). The pure port in `reasoning_budget.rs` replays all +//! 400 (`reasoning_budget_oracle.rs`). + +use std::{ + collections::HashSet, + path::{Path, PathBuf}, + process::Command, + sync::{Arc, OnceLock}, + time::Duration, +}; + +mod common; + +use serde::Deserialize; +use serde_json::Value; +use strata_control::{ + reasoning_budget::{Utf8Stream, reasoning_budget}, + wire::{Event, Finish, Generate, ReasoningPlan}, + worker::{ + GenerationCommand, GenerationResult, WorkerConfig, WorkerState, WorkerStatus, + run_with_requests, + }, +}; +use tokio::sync::{RwLock, mpsc, oneshot, watch}; + +#[derive(Deserialize)] +struct Expect { + calls: Vec<(Vec, usize)>, + finish: String, + completion_tokens: usize, + text: String, +} + +#[derive(Deserialize)] +struct RunCase { + prompt: Vec, + thinking: bool, + sampling: Value, + default: Value, + max_new: usize, + cancel: bool, + streams: Vec>, + expect: Expect, +} + +#[derive(Deserialize)] +struct Golden { + vocab: Vec, + wrap_up_ids: Vec, + stop_ids: Vec, + run: Vec, +} + +fn decode_hex(hex: &str) -> Vec { + (0..hex.len() / 2) + .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()) + .collect() +} + +fn engine() -> &'static Path { + static ENGINE: OnceLock = OnceLock::new(); + ENGINE.get_or_init(|| { + let dir = + std::env::temp_dir().join(format!("strata-scripted-engine-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("scripted_engine"); + let source = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/scripted_engine.rs"); + let status = Command::new(std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into())) + .args(["--edition", "2021", "-O", "-o"]) + .arg(&out) + .arg(source) + .status() + .expect("rustc"); + assert!(status.success()); + out + }) +} + +async fn play(case: &RunCase, golden: &Golden, index: usize) -> (Vec, Vec) { + let dir = + std::env::temp_dir().join(format!("strata-budget-live-{}-{index}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script: String = case + .streams + .iter() + .map(|stream| { + stream + .iter() + .map(u32::to_string) + .collect::>() + .join(",") + + "\n" + }) + .collect(); + std::fs::write(dir.join("script"), script).unwrap(); + let stops = golden + .stop_ids + .iter() + .map(u32::to_string) + .collect::>() + .join(","); + let config = WorkerConfig { + executable: engine().as_os_str().to_owned(), + args: vec![dir.to_string_lossy().into_owned(), stops], + startup_timeout: Duration::from_secs(20), + ..Default::default() + }; + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop, stop_rx) = watch::channel(false); + let (requests, requests_rx) = mpsc::channel(1); + let worker = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + requests_rx, + )); + while status.read().await.state != WorkerState::Ready { + tokio::time::sleep(Duration::from_millis(2)).await; + } + let pieces: Vec> = golden.vocab.iter().map(|hex| decode_hex(hex)).collect(); + let budget = if case.thinking { + reasoning_budget(Some(&case.sampling), &case.default).unwrap() + } else { + None + }; + let reasoning = budget.map(|budget| ReasoningPlan { + budget, + wrap_up: golden.wrap_up_ids.clone(), + stop_ids: golden.stop_ids.clone(), + token_bytes: Arc::new(move |id| pieces[id as usize].clone()), + }); + let (result, received) = oneshot::channel(); + requests + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: case.prompt.clone(), + max_new: case.max_new as u32, + reasoning, + ..Default::default() + }, + result: GenerationResult::Buffered(result), + }) + .await + .map_err(|_| "worker gone") + .unwrap(); + let events = tokio::time::timeout(Duration::from_secs(20), received) + .await + .expect("the request finishes") + .unwrap() + .expect("the request succeeds"); + stop.send(true).unwrap(); + let _ = tokio::time::timeout(Duration::from_secs(10), worker).await; + let log = std::fs::read_to_string(dir.join("requests")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect(); + let _ = std::fs::remove_dir_all(dir); + (events, log) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_live_worker_matches_python_service_run() { + let golden: Golden = serde_json::from_str(include_str!( + "fixtures/offline/reasoning_budget_oracle.json" + )) + .unwrap(); + let pieces: Vec> = golden.vocab.iter().map(|hex| decode_hex(hex)).collect(); + let stops: HashSet = golden.stop_ids.iter().copied().collect(); + let (mut played, mut wrapped) = (0, 0); + for (index, case) in golden.run.iter().enumerate() { + if case.cancel || case.prompt.is_empty() { + continue; + } + played += 1; + let (events, log) = play(case, &golden, index).await; + // what the engine was asked + let calls: Vec<(Vec, usize)> = log + .iter() + .map(|line| { + let (max_new, ids) = line.split_once(' ').unwrap(); + ( + ids.split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.parse().unwrap()) + .collect(), + max_new.parse().unwrap(), + ) + }) + .collect(); + assert_eq!(calls, case.expect.calls, "case {index}: engine calls"); + wrapped += usize::from(calls.len() > 1); + // what the client received + let Some(Event::Done(done)) = events.last() else { + panic!("case {index}: no DONE") + }; + let finish = match done.finish { + Finish::Length => "length", + Finish::Stop => "stop", + Finish::Cancel => "cancel", + }; + assert_eq!(finish, case.expect.finish, "case {index}: finish"); + assert_eq!( + done.generated as usize, case.expect.completion_tokens, + "case {index}: completion tokens" + ); + let mut stream = Utf8Stream::default(); + let mut text = String::new(); + let mut delivered = 0; + for event in &events { + if let Event::Token(id) = event { + delivered += 1; + if !stops.contains(id) { + text.push_str(&stream.push(&pieces[*id as usize])); + } + } + } + assert_eq!( + delivered, case.expect.completion_tokens, + "case {index}: delivered tokens" + ); + assert_eq!(text, case.expect.text, "case {index}: text"); + } + assert!(played >= 250, "played {played}"); + assert!( + wrapped >= 30, + "the golden should exercise the wrap-up often, saw {wrapped}" + ); +} + +/// The whole HTTP path with a budget: `/v1/responses` (streamed and not) over the real tokenizer, template, router +/// and worker, with the scripted engine. The model "thinks" `abcde`; the budget of 3 stops it after `abc`, the +/// wrap-up closes the thinking, and the second pass answers `Yes`. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_budget_applies_on_the_responses_http_path() { + mod_common::run().await; +} + +mod mod_common { + use super::*; + use crate::common::{scratch, tokenizer}; + use serde_json::json; + use strata_control::app::{AppState, router}; + + pub async fn run() { + let dir = scratch("budget-http"); + let tokenizer = tokenizer(&dir); + let wrap_up = tokenizer + .encode(leleka_serving_policy::reasoning::WRAP_UP, true) + .unwrap(); + let ids = |text: &str| { + text.bytes() + .map(|b| b.to_string()) + .collect::>() + .join(",") + }; + // pass 1: abcde (stopped after c); pass 2: Yes then <|im_end|> + std::fs::write( + dir.join("script"), + format!("{0}\n{1},257\n{0}\n{1},257\n", ids("abcde"), ids("Yes")), + ) + .unwrap(); + let config = WorkerConfig { + executable: engine().as_os_str().to_owned(), + args: vec![dir.to_string_lossy().into_owned(), "257".into()], + startup_timeout: Duration::from_secs(20), + ..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 worker = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + requests_rx, + )); + let state = AppState { + model: Some("strata-test".into()), + worker: status.clone(), + generation: Some(requests), + tokenizer: Some(tokenizer), + ..Default::default() + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let _ = axum::serve(listener, router(state)).await; + }); + while status.read().await.state != WorkerState::Ready { + tokio::time::sleep(Duration::from_millis(5)).await; + } + let client = reqwest::Client::new(); + for stream in [false, true] { + let _ = std::fs::remove_file(dir.join("requests")); + let body = json!({"model": "strata-test", "input": "hi", "store": false, "max_output_tokens": 200, + "reasoning_budget_tokens": 3, "stream": stream}); + let response = client + .post(format!("{base}/v1/responses")) + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = response.text().await.unwrap(); + let completed: Value = if stream { + let frame = text + .split("\n\n") + .find(|frame| frame.starts_with("event: response.completed")) + .unwrap_or_else(|| panic!("no completed event in {text}")); + let data = frame.split_once("data: ").unwrap().1; + serde_json::from_str::(data).unwrap()["response"].clone() + } else { + serde_json::from_str(&text).unwrap() + }; + let output = completed["output"].as_array().unwrap(); + let reasoning = &output[0]; + assert_eq!(reasoning["type"], "reasoning", "{completed}"); + let thought = reasoning["content"][0]["text"].as_str().unwrap(); + assert_eq!( + thought, + format!( + "abc{}", + leleka_serving_policy::reasoning::WRAP_UP.trim_end_matches("\n\n") + ) + ); + assert_eq!(output[1]["content"][0]["text"], "Yes"); + let usage = &completed["usage"]; + assert_eq!(usage["output_tokens"], 3 + wrap_up.len() + 4, "{completed}"); + // the engine saw two requests: the prompt, then prompt + abc + wrap-up with the remaining budget + let log = std::fs::read_to_string(dir.join("requests")).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 2, "{log}"); + let first: Vec<&str> = lines[0].split(' ').collect(); + let second: Vec<&str> = lines[1].split(' ').collect(); + assert_eq!(first[0], "200"); + assert_eq!(second[0], (200 - 3 - wrap_up.len()).to_string()); + let tail = format!( + "{},{}", + ids("abc"), + wrap_up + .iter() + .map(u32::to_string) + .collect::>() + .join(",") + ); + assert!(second[1].ends_with(&tail), "{}", second[1]); + assert!(second[1].starts_with(first[1])); + } + server.abort(); + stop.send(true).unwrap(); + let _ = tokio::time::timeout(Duration::from_secs(10), worker).await; + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/control-plane/tests/vision_http.rs b/control-plane/tests/vision_http.rs index f34ca6aa..75efd42b 100644 --- a/control-plane/tests/vision_http.rs +++ b/control-plane/tests/vision_http.rs @@ -12,76 +12,16 @@ use std::{ }; use leleka_serving_policy::vision as policy; -use serde_json::{Map, Value, json}; +use serde_json::{Value, json}; use strata_control::{ app::{AppState, router}, - tokenizer::Tokenizer, vision::{Vision, VisionConfig}, worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised}, }; use tokio::sync::{RwLock, mpsc, watch}; -const SPECIALS: [&str; 7] = [ - "<|im_start|>", - "<|im_end|>", - "", - "", - "<|vision_start|>", - "<|image_pad|>", - "<|vision_end|>", -]; -const PAD: u32 = 256 + 5; -const START: u32 = 256 + 4; -const END: u32 = 256 + 6; - -fn scratch(name: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("strata-vision-http-{}-{name}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir -} - -fn tokenizer(dir: &Path) -> Arc { - let root = dir.join("tokenizer"); - fs::create_dir(&root).unwrap(); - let mut vocabulary = Map::new(); - for (id, ch) in strata_control::tokenizer::byte_alphabet() - .0 - .iter() - .enumerate() - { - vocabulary.insert(ch.to_string(), json!(id)); - } - for (offset, token) in SPECIALS.iter().enumerate() { - vocabulary.insert((*token).into(), json!(256 + offset)); - } - let total = 256 + SPECIALS.len(); - fs::write( - root.join("vocab.json"), - serde_json::to_vec(&vocabulary).unwrap(), - ) - .unwrap(); - fs::write(root.join("merges.txt"), "").unwrap(); - let mut types = vec![1u8; total]; - types[256..].fill(3); - fs::write( - root.join("token_type.json"), - serde_json::to_vec(&types).unwrap(), - ) - .unwrap(); - fs::write( - root.join("tokenizer.json"), - serde_json::to_vec(&json!({ - "model": "gpt2", "pre": "qwen35", "vocab_size": total, "n_merges": 0, - "pre_pattern": leleka_tokenizer::QWEN35_PATTERN, - "special_ids": {"tokenizer.ggml.eos_token_id": 257} - })) - .unwrap(), - ) - .unwrap(); - Arc::new(Tokenizer::from_assets(&root).unwrap()) -} +mod common; +use common::{END, PAD, SPECIALS, START, scratch, tokenizer}; fn png(tag: u8) -> Vec { let mut data = b"\x89PNG\r\n\x1a\n".to_vec(); diff --git a/docs/offline-port.md b/docs/offline-port.md index 7c67f2f1..444ab7ec 100644 --- a/docs/offline-port.md +++ b/docs/offline-port.md @@ -57,11 +57,7 @@ scope. They remain Python-only until the Q2_0/AVX-512 path is brought into scope ## Open items -- **The reasoning budget is not wired into the live worker.** `reasoning_budget.rs` is a tested port of the loop - (clean-point rule, wrap-up text, continuation prompt, room check). The Responses path buffers a whole generation and - the request schema does not carry `reasoning_budget_tokens` yet; wiring needs a streaming adapter over - `GenerationResult::Streaming` that can stop the engine, then resubmit `prompt + segment + wrap-up`. It needs a real - engine to validate. +- The reasoning budget is wired into the live worker (`worker.rs` `generate`, `BudgetTracker`); see `docs/port-remaining.md` item 2 for the live-path differential. - The reference-parity checks use synthetic fixtures. No real IQ3_S shard, tokenizer or chat transcript was run here (no model downloads). - Thirteen worker tests in `strata-control` and four in `leleka-model-format` fail on macOS on the base branch too diff --git a/docs/port-remaining.md b/docs/port-remaining.md index b11d2f62..8c72881b 100644 --- a/docs/port-remaining.md +++ b/docs/port-remaining.md @@ -44,3 +44,23 @@ Deliberate divergences: server can read as an image (the bytes only reach the encoder), so run the server behind an API key. 6. The Chat adapter is stricter than Python's: image parts only in user messages, unknown part keys rejected. An image beside a `tool_result` in a Messages user turn is kept (Python drops it). + +## 2. Reasoning budget on the live path + +The budget was already wired when this item started (`wire::ReasoningPlan` built by `responses.rs::reasoning_plan`, +executed in `worker.rs::generate`: count thinking tokens with `serving_policy::reasoning::BudgetTracker`, send `STOP` +at a clean point, discard the tokens until that pass's `DONE`, deliver the wrap-up tokens, re-submit `prompt + segment ++ wrap-up` with `max_new - generated`, report one combined `DONE`); `docs/offline-port.md` still called it open. +What was missing was evidence on that path, because `reasoning_budget_oracle.rs` replays the pure port +(`reasoning_budget::run`), not the worker: + +* `control-plane/tests/reasoning_budget_live.rs::the_live_worker_matches_python_service_run` plays the 288 non-cancel, + non-empty-prompt cases of the real-`Service.run` golden through the real worker supervisor and a scripted engine + process (`tests/fixtures/scripted_engine.rs`, compiled with `rustc` at test time; it honours `STOP` between tokens) + and compares every engine request (prompt, `max_new`), the finish reason, the completion tokens and the delivered + text with Python. A mutation of the budget comparison fails it at case 2. +* `the_budget_applies_on_the_responses_http_path` runs `/v1/responses` (buffered and streamed) through the real router, + tokenizer and template: reasoning, wrap-up text, answer, `output_tokens`, and the second engine request. + +Not applicable: the Chat and Messages adapters pin thinking off (`reasoning: none`), so `reasoning_budget_tokens` +has no effect there; the Python server accepts it in every dialect because it thinks by default.