diff --git a/Cargo.lock b/Cargo.lock index 930a3709..113f9350 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1079,6 +1079,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "leleka-serving-policy" +version = "0.1.0" +dependencies = [ + "leleka-sampler-ref", + "serde_json", +] + [[package]] name = "leleka-tokenizer" version = "0.1.0" @@ -2079,6 +2087,8 @@ dependencies = [ "jsonschema", "leleka-model-format", "leleka-quant-core", + "leleka-sampler-ref", + "leleka-serving-policy", "leleka-tokenizer", "libc", "regex", @@ -2103,6 +2113,8 @@ dependencies = [ "jsonschema", "leleka-backend-api", "leleka-runtime", + "leleka-sampler-ref", + "leleka-serving-policy", "prost", "protoc-bin-vendored", "regex", diff --git a/Cargo.toml b/Cargo.toml index d80f1f4f..07b45d56 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index e4454078..4b73f910 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -14,6 +14,8 @@ axum = "0.8" futures-core = "0.3" hex = "0.4" leleka-tokenizer = { path = "../crates/tokenizer" } +leleka-sampler-ref = { path = "../crates/sampler-ref" } +leleka-serving-policy = { path = "../crates/serving-policy" } leleka-model-format = { path = "../crates/model-format" } leleka-quant-core = { path = "../crates/quant-core" } http-body = "1" diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 92e9ccb0..1e2e1704 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -27,6 +27,20 @@ pub struct AppState { pub tokenizer: Option>, pub generation: Option>, pub response_history: Arc>, + pub settings: Arc, + /// Other names of the model (`aliases` in the config), answered like the model's own. + pub aliases: Arc>, + /// Browser pages of these origins may call `/v1/*`. + pub cors: Arc, + /// Origins that count as this server's own page for `/settings` and `/v1/load|unload`. + pub trusted_origins: Arc>, + /// Administrative channel to the worker supervisor (load/unload); `None` without a worker. + pub control: Option>, + pub started_at: std::time::SystemTime, + /// Source of the model's chat template, served by `/props`. + pub chat_template: Option>, + /// The MCP servers configured for the operator (`GET /mcp`). + pub mcp: Option>, } impl Default for AppState { @@ -40,6 +54,14 @@ impl Default for AppState { tokenizer: None, generation: None, response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())), + settings: Arc::new(crate::settings::Settings::default()), + aliases: Arc::new(Vec::new()), + cors: Arc::new(Default::default()), + trusted_origins: Arc::new(Vec::new()), + control: None, + started_at: std::time::SystemTime::now(), + chat_template: None, + mcp: None, } } } @@ -66,6 +88,20 @@ pub fn router(state: AppState) -> Router { .route("/ready", get(ready)) .route("/status", get(status)) .route("/metrics", get(metrics)) + .route("/api/health", get(crate::server_api::api_health)) + .route("/props", get(crate::server_api::props)) + .route("/slots", get(crate::server_api::slots)) + .route("/v1/status", get(crate::server_api::v1_status)) + .route("/mcp", get(crate::server_api::mcp_status)) + .route( + "/settings", + get(crate::server_api::settings_get).post(crate::server_api::settings_post), + ) + .route("/load", post(crate::server_api::load_post)) + .route("/unload", post(crate::server_api::unload_post)) + .route("/v1/load", post(crate::server_api::v1_load)) + .route("/v1/unload", post(crate::server_api::v1_unload)) + .route("/models", get(crate::models_api::list)) .route("/v1/models", get(crate::models_api::list)) .route("/v1/models/{id}", get(crate::models_api::retrieve)) .route( @@ -118,11 +154,17 @@ pub fn router(state: AppState) -> Router { ) .route("/admin/drain", post(drain)) .route("/admin/resume", post(resume)) + .fallback(crate::server_api::not_found) .layer(DefaultBodyLimit::max(16 * 1024 * 1024)) .layer(middleware::from_fn_with_state( state.api_key.clone(), crate::auth::authorize, )) + // Outermost: a browser's credential-less preflight is answered before authentication. + .layer(middleware::from_fn_with_state( + state.cors.clone(), + crate::server_api::cors_layer, + )) .with_state(state) } @@ -137,7 +179,10 @@ async fn lifecycle_status(State(state): State) -> Json, stop: Option, logprobs: Option, - frequency_penalty: Option, - presence_penalty: Option, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -151,14 +149,6 @@ impl Request { if self.logprobs == Some(true) { return Err(invalid("logprobs", "log probabilities are not supported")); } - if self.frequency_penalty.is_some_and(|x| x != 0.0) - || self.presence_penalty.is_some_and(|x| x != 0.0) - { - return Err(invalid( - "frequency_penalty", - "nonzero frequency/presence penalties are not supported", - )); - } if !self.stream && self.stream_options.is_some() { return Err(invalid( "stream_options", @@ -389,6 +379,8 @@ pub async fn create( Ok(body) => body, Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()), }; + // Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request. + let (body, extensions) = crate::sampling::split_extensions(body); let request: Request = match serde_json::from_value(body) { Ok(r) => r, Err(e) => { @@ -400,7 +392,7 @@ pub async fn create( ); } }; - let (request, stream, include_usage) = match request.into_responses() { + let (mut request, stream, include_usage) = match request.into_responses() { Ok(r) => r, Err((p, m)) => { return error( @@ -411,6 +403,9 @@ pub async fn create( ); } }; + for (key, value) in extensions { + request[key] = value; + } let response = responses::create(State(state), Ok(Json(request))).await; if stream && response.status().is_success() { return stream_response(response.into_body(), include_usage); diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index f6d9e460..57570739 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -28,6 +28,24 @@ pub struct Config { pub model: Option, pub worker: Option, pub tokenizer_dir: Option, + /// Other names the model answers to (`aliases`). + pub aliases: Vec, + /// Browser pages of these origins may call `/v1/*` (`cors_origins`; `"*"` allowed). + pub cors_origins: Vec, + /// Origins that count as this server's own page (`trusted_origins`; no wildcard). + pub trusted_origins: Vec, + /// The `sampling` block: defaults for what a request leaves out. + pub sampling: leleka_serving_policy::shared::ConfigSampling, + /// `reasoning_budget_tokens`: the default thinking budget (0: none). + pub reasoning_budget_tokens: Option, + /// Where the Chat settings shared with every client are kept between starts. + pub shared_settings_file: Option, + /// Unload the engine after this long without requests (`engine.idle_unload_s`). + pub idle_unload: Option, + /// MCP servers (`mcp_servers`, `mcpServers`, `mcp_config_file`); empty when there are none. + pub mcp_servers: std::collections::BTreeMap>, + /// The `mcp` block: timeouts and caps. + pub mcp_settings: crate::mcp::Settings, } #[derive(Default, Deserialize)] @@ -49,6 +67,17 @@ struct FileConfig { bind: Option, model: Option, engine: Option, + aliases: Option, + cors_origins: Option, + trusted_origins: Option, + sampling: Option, + reasoning_budget_tokens: Option, + shared_settings_file: Option, + mcp_servers: Option, + #[serde(rename = "mcpServers")] + mcp_servers_desktop: Option, + mcp_config_file: Option, + mcp: Option, } #[derive(Deserialize)] @@ -61,6 +90,140 @@ struct FileEngine { generation_timeout_s: Option, max_restarts: Option, tokenizer_dir: Option, + /// Start unloaded; the first request loads the engine. + #[serde(default)] + lazy_load: bool, + /// Unload after this many idle seconds so other programs can use the GPU. + idle_unload_s: Option, + /// Reload only when this much VRAM is free (MiB). + min_free_vram_mib: Option, + /// Command run before every reload and restart (a shell line or an argv list). + before_load: Option, + /// No engine line for this long during a request ends it (the stall watchdog). + stall_timeout_s: Option, + /// A control vector on the residual stream (steering); requests switch it per request. + control_vector: Option, +} + +/// `--control-vector-scaled`, `--cvec-mode`, `--cvec-dir`, `--control-vector-layer-range`. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ControlVector { + files: Vec, + /// `add` (default) or `project`. + mode: Option, + /// `per-layer` (default) or `single:L` (project mode). + dir: Option, + /// First and last steered layer, inclusive. + layer_range: Option<[i32; 2]>, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ControlVectorFile { + path: PathBuf, + scale: f32, +} + +impl ControlVector { + /// The engine arguments for this vector after checking the files (GGUF control vectors with + /// F32 `direction.` tensors of one width), so a typo stops the start, not the load. + fn engine_args(&self) -> Result, String> { + if self.files.is_empty() || self.files.len() > 16 { + return Err("control_vector.files needs 1 to 16 files".into()); + } + let mode = match self.mode.as_deref() { + None => leleka_serving_policy::cvec::Mode::Add, + Some(text) => leleka_serving_policy::cvec::parse_mode(text)?, + }; + let single = match self.dir.as_deref() { + None => -1, + Some(text) => leleka_serving_policy::cvec::parse_dir(text)?, + }; + if single >= 0 && mode != leleka_serving_policy::cvec::Mode::Project { + return Err("control_vector.dir single:L needs mode project".into()); + } + let mut width: Option = None; + let mut list = Vec::new(); + for file in &self.files { + if !file.path.is_absolute() + || file.path.to_str().is_none_or(|p| p.contains([',', '\n'])) + { + return Err("control_vector file paths must be absolute, without commas".into()); + } + if !file.scale.is_finite() { + return Err("control_vector scale must be finite".into()); + } + let metadata = fs::metadata(&file.path) + .map_err(|error| format!("control_vector {}: {error}", file.path.display()))?; + if !metadata.is_file() || metadata.len() > 256 * 1024 * 1024 { + return Err(format!( + "control_vector {} must be a regular file of at most 256 MiB", + file.path.display() + )); + } + let parsed = leleka_serving_policy::cvec::parse_gguf( + &fs::read(&file.path) + .map_err(|error| format!("control_vector {}: {error}", file.path.display()))?, + ) + .map_err(|error| format!("control_vector {}: {error}", file.path.display()))?; + if parsed.architecture.as_deref() != Some("controlvector") { + return Err(format!( + "control_vector {}: not a control vector GGUF (general.architecture is not 'controlvector')", + file.path.display() + )); + } + let mut found = false; + for tensor in parsed + .tensors + .iter() + .filter(|t| t.name.starts_with("direction.")) + { + if tensor.kind != 0 { + return Err(format!( + "control_vector {}: {} must be f32", + file.path.display(), + tensor.name + )); + } + if *width.get_or_insert(tensor.elements) != tensor.elements { + return Err(format!( + "control_vector {}: direction tensors differ in width", + file.path.display() + )); + } + found = true; + } + if !found { + return Err(format!( + "control_vector {}: no direction. tensors", + file.path.display() + )); + } + list.push(format!("{}:{}", file.path.display(), file.scale)); + } + let mut args = vec!["--control-vector-scaled".to_owned(), list.join(",")]; + args.extend([ + "--cvec-mode".to_owned(), + if mode == leleka_serving_policy::cvec::Mode::Project { + "project" + } else { + "add" + } + .to_owned(), + ]); + if let Some(dir) = &self.dir { + args.extend(["--cvec-dir".to_owned(), dir.clone()]); + } + if let Some([first, last]) = self.layer_range { + args.extend([ + "--control-vector-layer-range".to_owned(), + first.to_string(), + last.to_string(), + ]); + } + Ok(args) + } } impl Config { @@ -70,14 +233,12 @@ impl Config { /// An explicit CLI config path takes precedence over STRATA_CONFIG. pub fn load_with_path(path: Option<&Path>) -> Result> { - let file = match path + let config_path = path .map(|p| p.as_os_str().to_owned()) .or_else(|| env::var_os("STRATA_CONFIG")) - { - Some(path) => { - let path = PathBuf::from(path); - serde_json::from_str::(&fs::read_to_string(path)?)? - } + .map(PathBuf::from); + let file = match &config_path { + Some(path) => serde_json::from_str::(&fs::read_to_string(path)?)?, None => FileConfig::default(), }; @@ -157,6 +318,25 @@ impl Config { if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { return Err("generation_timeout_s must be between 1 and 86400".into()); } + let engine_file = file.engine.as_ref(); + let mut args = args; + if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) { + if args + .iter() + .any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-")) + { + return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into()); + } + args.extend(vector.engine_args()?); + } + let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s); + if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("stall_timeout_s must be between 1 and 86400".into()); + } + let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s); + if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) { + return Err("idle_unload_s must be a non-negative number".into()); + } let worker = match executable { Some(executable) if !executable.is_empty() => Some(WorkerConfig { executable, @@ -165,6 +345,12 @@ impl Config { startup_timeout: Duration::from_secs(startup_timeout_s), generation_timeout: generation_timeout_s.map(Duration::from_secs), max_restarts, + lazy: engine_file.is_some_and(|engine| engine.lazy_load), + stall_timeout: stall_timeout_s.map(Duration::from_secs), + before_load: engine_file.and_then(|engine| engine.before_load.clone()), + min_free_vram_mib: engine_file + .and_then(|engine| engine.min_free_vram_mib) + .unwrap_or(0), }), Some(_) => return Err("engine executable cannot be empty".into()), None if !args.is_empty() => return Err("engine args require an executable".into()), @@ -257,7 +443,91 @@ impl Config { "response_history_dir must be an absolute non-root path without '..'".into(), ); } + let aliases = match &file.aliases { + None => Vec::new(), + Some(value) => leleka_serving_policy::shared::normalize_aliases( + value, + model.as_deref().unwrap_or(""), + ) + .map_err(|message| format!("config {message}"))?, + }; + if aliases.iter().any(|alias| { + alias.len() > 180 + || !alias + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + }) { + return Err( + "aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(), + ); + } + let cors_origins = leleka_serving_policy::cors::origins_of( + file.cors_origins + .as_ref() + .unwrap_or(&serde_json::Value::Null), + "cors_origins", + true, + )?; + let trusted_origins = leleka_serving_policy::cors::origins_of( + file.trusted_origins + .as_ref() + .unwrap_or(&serde_json::Value::Null), + "trusted_origins", + false, + )?; + let sampling = leleka_serving_policy::shared::sampling_defaults_from_config( + file.sampling.as_ref().unwrap_or(&serde_json::Value::Null), + )?; + for ignored in &sampling.ignored { + eprintln!("config sampling.{ignored}: unknown key, ignored"); + } + if let Some(value) = &file.reasoning_budget_tokens { + leleka_serving_policy::reasoning::parse_budget(None, Some(value)) + .map_err(|message| format!("config {message}"))?; + } + let shared_settings_file = file.shared_settings_file.clone().or_else(|| { + config_path + .as_deref() + .map(crate::settings::default_shared_path) + }); + let mut mcp_servers = std::collections::BTreeMap::new(); + let null = serde_json::Value::Null; + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers.as_ref().unwrap_or(&null), + "config mcp_servers", + )?); + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers_desktop.as_ref().unwrap_or(&null), + "config mcpServers", + )?); + if let Some(path) = &file.mcp_config_file { + // Claude Desktop's format; a name in both takes this file's entry. + let location = format!("mcp_config_file {}", path.display()); + let text = std::fs::read_to_string(path) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let block = data + .get("mcpServers") + .or_else(|| data.get("mcp_servers")) + .ok_or_else(|| { + format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}") + })?; + mcp_servers.extend(crate::mcp::servers_from(block, &location)?); + } + let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?; Ok(Self { + mcp_servers, + mcp_settings, + aliases, + cors_origins, + trusted_origins, + sampling, + reasoning_budget_tokens: file.reasoning_budget_tokens, + shared_settings_file, + idle_unload: idle_unload_s + .filter(|seconds| *seconds > 0.0) + .map(Duration::from_secs_f64), mtp_pack: file.mtp_pack, response_history_dir, assets: file.assets, @@ -365,3 +635,190 @@ fn optional_env(name: &str) -> Result, env::VarError> { Err(error) => Err(error), } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn temp(name: &str) -> PathBuf { + let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn load(dir: &Path, value: serde_json::Value) -> Result { + let path = dir.join("config.json"); + fs::write(&path, value.to_string()).unwrap(); + Config::load_with_path(Some(&path)).map_err(|e| e.to_string()) + } + + fn control_vector_file( + dir: &Path, + name: &str, + architecture: &str, + kind: u32, + elements: u64, + ) -> PathBuf { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + let key = b"general.architecture"; + bytes.extend_from_slice(&(key.len() as u64).to_le_bytes()); + bytes.extend_from_slice(key); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes()); + bytes.extend_from_slice(architecture.as_bytes()); + let tensor = b"direction.1"; + bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes()); + bytes.extend_from_slice(tensor); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&elements.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + while !bytes.len().is_multiple_of(32) { + bytes.push(0); + } + bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4)); + let path = dir.join(name); + fs::write(&path, bytes).unwrap(); + path + } + + #[test] + fn serving_settings_are_read_and_checked_at_start() { + let dir = temp("serving"); + let config = load( + &dir, + json!({ + "model": "strata-test", + "aliases": ["gpt-local", " strata-test ", "gpt-local"], + "cors_origins": ["https://chat.example.com/", "*"], + "trusted_origins": "https://strata.example.com", + "sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1}, + "reasoning_budget_tokens": 128, + "engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90, + "min_free_vram_mib": 20000, "before_load": "echo hook", + "stall_timeout_s": 120} + }), + ) + .unwrap(); + assert_eq!(config.aliases, vec!["gpt-local"]); + assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]); + assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]); + assert_eq!(config.sampling.sampling.top_k, Some(30)); + assert_eq!(config.sampling.ignored, vec!["nonsense"]); + assert_eq!(config.idle_unload, Some(Duration::from_secs(90))); + assert_eq!( + config.shared_settings_file, + Some(dir.join("config.shared-settings.json")) + ); + let worker = config.worker.unwrap(); + assert!(worker.lazy); + assert_eq!(worker.min_free_vram_mib, 20000); + assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120))); + assert_eq!( + worker.before_load, + Some(crate::worker::BeforeLoad::Shell("echo hook".into())) + ); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn bad_serving_settings_stop_the_start() { + let dir = temp("serving-bad"); + for (name, value) in [ + ("sampling", json!({"sampling": {"top_k": 100}})), + ("cors", json!({"cors_origins": ["https://a.example/path"]})), + ("trusted", json!({"trusted_origins": ["*"]})), + ("aliases", json!({"aliases": [1]})), + ("alias charset", json!({"aliases": ["has space"]})), + ("budget", json!({"reasoning_budget_tokens": "many"})), + ( + "stall", + json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}), + ), + ( + "idle", + json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}), + ), + ] { + assert!(load(&dir, value).is_err(), "{name}"); + } + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_control_vector_becomes_engine_arguments_after_a_preflight() { + let dir = temp("cvec"); + let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8); + let config = load( + &dir, + json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"], + "control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project", + "dir": "single:3", "layer_range": [2, 40]}}}), + ) + .unwrap(); + let args = config.worker.unwrap().args; + assert_eq!(args[..2], ["--max-context", "4096"]); + assert_eq!(args[2], "--control-vector-scaled"); + assert_eq!(args[3], format!("{}:0.5", good.display())); + assert_eq!( + args[4..], + [ + "--cvec-mode", + "project", + "--cvec-dir", + "single:3", + "--control-vector-layer-range", + "2", + "40" + ] + ); + for (name, value) in [ + ( + "wrong arch", + control_vector_file(&dir, "arch.gguf", "llama", 0, 8), + ), + ( + "f16", + control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8), + ), + ] { + let result = load( + &dir, + json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}), + ); + assert!(result.is_err(), "{name}"); + } + for bad in [ + json!({"files": []}), + json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}), + json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}), + json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}), + json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}), + json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}), + ] { + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/e", "control_vector": bad}}) + ) + .is_err(), + "{bad}" + ); + } + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"], + "control_vector": {"files": [{"path": good, "scale": 1.0}]}}}) + ) + .is_err(), + "owned arguments" + ); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/control-plane/src/cuda_memory.rs b/control-plane/src/cuda_memory.rs index bb1bcdc3..4287c7b5 100644 --- a/control-plane/src/cuda_memory.rs +++ b/control-plane/src/cuda_memory.rs @@ -42,6 +42,18 @@ impl Selection { choose(self.policy, devices, Some(std::slice::from_ref(&self.uuid))).map(|_| ()) } } +/// Free VRAM in MiB of the selected GPU, or of the freest visible one; `None` when it cannot be read +/// (then nothing is refused, as in the Original's `free_vram_mib`). +pub async fn free_mib(selection: Option<&Selection>) -> Option { + let devices = inventory().await.ok()?; + match selection { + Some(selection) => devices + .iter() + .find(|d| d.uuid == selection.uuid) + .map(|d| d.free), + None => devices.iter().map(|d| d.free).max(), + } +} struct Device { uuid: String, free: u64, diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index ef8c6e48..6e55a7d1 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -60,3 +60,11 @@ pub mod cuda_memory; pub mod service_switch; pub mod queue; + +pub mod sampling; + +pub mod server_api; + +pub mod settings; + +pub mod mcp; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index d1553d91..e5691c29 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -1,4 +1,4 @@ -use std::{env, io::Read, path::Path, sync::Arc}; +use std::{env, io::Read, path::Path, sync::Arc, time::Duration}; use tokio::sync::{mpsc, watch}; @@ -822,30 +822,74 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result<(), Box__`, called +//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`. +//! +//! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers` +//! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`, +//! `env`, `cwd`; newline-delimited JSON-RPC 2.0 on its stdin/stdout) or an address (`url`, +//! `headers`; Streamable HTTP, answered as JSON or as an event stream). No MCP SDK is needed. +//! +//! A server that does not start is left out with one log line; one that stops later is started +//! again by its next call (a failed start is retried at most every 10 s). Results reach the model +//! as text capped at `max_result_chars`; a failed call becomes a result starting with `error:` so +//! the model can react. +//! +//! Scope in this server: the hub, its configuration, tool listing and `GET /mcp` status. The +//! Original's chat loop that runs these tools *server-side* inside one chat completion +//! (`run_with_mcp`, `strata_mcp: true`) serves its bundled web page; Responses, Chat Completions and +//! Messages here return tool calls to the client, which executes them (the contract validated in +//! `docs/api-contract.md`), so the loop is deliberately not connected and no endpoint executes MCP +//! tools on a client's behalf. + +use std::{ + collections::{BTreeMap, HashMap, VecDeque}, + process::Stdio, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + }, + time::{Duration, Instant}, +}; + +use serde_json::{Map, Value, json}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + process::{Child, ChildStdin, Command}, + sync::{Mutex as AsyncMutex, oneshot, watch}, +}; + +pub const PROTOCOL: &str = "2025-06-18"; + +/// `DEFAULTS` of the Original: the knobs of the optional `mcp` config block. +#[derive(Clone, Debug, PartialEq)] +pub struct Settings { + pub timeout_s: f64, + pub max_result_chars: usize, + pub max_rounds: usize, + pub start_timeout_s: f64, +} + +impl Default for Settings { + fn default() -> Self { + Self { + timeout_s: 60.0, + max_result_chars: 20_000, + max_rounds: 8, + start_timeout_s: 120.0, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum McpError { + /// A server answered with an error, stopped, or could not be reached. + Failed(String), + Timeout(String), + /// The chat was stopped while the call ran. + Cancelled, +} + +impl std::fmt::Display for McpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Failed(m) | Self::Timeout(m) => f.write_str(m), + Self::Cancelled => f.write_str("stopped"), + } + } +} + +fn failed(message: impl Into) -> McpError { + McpError::Failed(message.into()) +} + +pub type Cancel = watch::Receiver; + +/// A response `result`, or the error a JSON-RPC response carried (`_wait` of the Original). +fn response_result(message: &Value) -> Result { + if let Some(error) = message.get("error") { + let (text, code) = match error { + Value::Object(object) => ( + object + .get("message") + .and_then(Value::as_str) + .filter(|t| !t.is_empty()) + .unwrap_or("error") + .to_owned(), + object.get("code").cloned().unwrap_or(Value::Null), + ), + other => (other.to_string(), Value::Null), + }; + let code = if code.is_null() { + "None".to_owned() + } else { + code.to_string() + }; + return Err(failed(format!("{text} (code {code})"))); + } + Ok(message + .get("result") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or_else(|| json!({}))) +} + +type Slot = oneshot::Sender>; + +// ------------------------------------------------------------------------------------------------ stdio + +struct StdioTransport { + name: String, + stdin: Arc>>, + child: AsyncMutex>, + pid: Option, + pending: Arc>>, + next_id: AtomicU64, + stderr: Arc>>, + ended: Arc, +} + +impl StdioTransport { + async fn spawn(name: &str, config: &Map) -> Result { + let command = config + .get("command") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let mut process = Command::new(&command); + process + .args( + config + .get("args") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|a| a.as_str().map_or_else(|| a.to_string(), str::to_owned)), + ) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + for (key, value) in config + .get("env") + .and_then(Value::as_object) + .into_iter() + .flatten() + { + process.env( + key, + value + .as_str() + .map_or_else(|| value.to_string(), str::to_owned), + ); + } + if let Some(dir) = config + .get("cwd") + .and_then(Value::as_str) + .filter(|d| !d.is_empty()) + { + process.current_dir(dir); + } + #[cfg(unix)] + process.process_group(0); // its own group, so closing it ends its children too + let mut child = process + .spawn() + .map_err(|error| failed(format!("could not start {command:?}: {error}")))?; + let stdin = child.stdin.take(); + let stdout = child.stdout.take().expect("piped stdout"); + let stderr = child.stderr.take().expect("piped stderr"); + let pid = child.id(); + let pending: Arc>> = Arc::default(); + let log: Arc>> = Arc::default(); + let ended = Arc::new(std::sync::atomic::AtomicBool::new(false)); + + // The server's stderr is its log; the last lines explain a failure. + let (done_tx, done_rx) = oneshot::channel::<()>(); + { + let log = log.clone(); + let label = name.to_owned(); + tokio::spawn(async move { + let mut lines = BufReader::new(stderr).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let line = line.trim_end().to_owned(); + if line.is_empty() { + continue; + } + if std::env::var_os("STRATA_DEBUG").is_some() { + eprintln!("[mcp {label}] {line}"); + } + let mut log = log.lock().expect("mcp log"); + log.push_back(line); + if log.len() > 40 { + log.pop_front(); + } + } + let _ = done_tx.send(()); + }); + } + let stdin = Arc::new(AsyncMutex::new(stdin)); + let transport = Self { + name: name.to_owned(), + stdin: stdin.clone(), + child: AsyncMutex::new(Some(child)), + pid, + pending: pending.clone(), + next_id: AtomicU64::new(0), + stderr: log.clone(), + ended: ended.clone(), + }; + // Reader: one JSON-RPC message per line; requests from the server get "not supported". + let writer = stdin; + tokio::spawn(async move { + let mut lines = BufReader::new(stdout).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Ok(message) = serde_json::from_str::(line) else { + let mut log = log.lock().expect("mcp log"); + log.push_back(line.to_owned()); // a server that prints to stdout; the spec forbids it + continue; + }; + let batch = match message { + Value::Array(items) => items, + other => vec![other], + }; + for m in batch.into_iter().filter(Value::is_object) { + dispatch(&m, &pending, &writer).await; + } + } + ended.store(true, Ordering::SeqCst); + // Let the stderr reader take the last log line first (the pipe closes with the process). + let _ = tokio::time::timeout(Duration::from_secs(1), done_rx).await; + let tail = log + .lock() + .expect("mcp log") + .back() + .map(|l| format!(": {}", l.chars().take(300).collect::())) + .unwrap_or_default(); + let error = failed(format!("the server stopped{tail}")); + let slots: Vec = pending + .lock() + .expect("mcp pending") + .drain() + .map(|(_, s)| s) + .collect(); + for slot in slots { + let _ = slot.send(Err(error.clone())); + } + }); + Ok(transport) + } + + fn tail(&self) -> String { + self.stderr + .lock() + .expect("mcp log") + .back() + .map(|l| format!(": {}", l.chars().take(300).collect::())) + .unwrap_or_default() + } + + fn alive(&self) -> bool { + !self.ended.load(Ordering::SeqCst) + } + + async fn send(&self, message: &Value) -> Result<(), McpError> { + let mut data = serde_json::to_vec(message).expect("json"); + data.push(b'\n'); + let mut stdin = self.stdin.lock().await; + let Some(pipe) = stdin.as_mut() else { + return Err(failed(format!("the server stopped{}", self.tail()))); + }; + if pipe.write_all(&data).await.is_err() || pipe.flush().await.is_err() { + return Err(failed(format!("the server stopped{}", self.tail()))); + } + Ok(()) + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + mut cancel: Option, + ) -> Result { + if !self.alive() { + return Err(failed(format!("the server is not running{}", self.tail()))); + } + let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1; + let (slot, received) = oneshot::channel(); + self.pending.lock().expect("mcp pending").insert(id, slot); + if let Err(error) = self + .send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})) + .await + { + self.pending.lock().expect("mcp pending").remove(&id); + return Err(error); + } + let outcome = tokio::select! { + answer = received => match answer { + Ok(Ok(message)) => return response_result(&message), + Ok(Err(error)) => return Err(error), + Err(_) => return Err(failed(format!("the server stopped{}", self.tail()))), + }, + () = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))), + () = cancelled(&mut cancel) => McpError::Cancelled, + }; + self.pending.lock().expect("mcp pending").remove(&id); + // Tell the server to stop working on it. + let _ = self + .notify( + "notifications/cancelled", + Some(json!({"requestId": id, "reason": outcome.to_string()})), + ) + .await; + Err(outcome) + } + + async fn notify(&self, method: &str, params: Option) -> Result<(), McpError> { + let mut message = json!({"jsonrpc": "2.0", "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.send(&message).await + } + + /// As the spec says: close its stdin, give it a moment to exit, then end it and what it started. + async fn close(&self) { + self.stdin.lock().await.take(); + let child = self.child.lock().await.take(); + let Some(mut child) = child else { return }; + if tokio::time::timeout(Duration::from_secs(2), child.wait()) + .await + .is_err() + { + if let Some(pid) = self.pid { + let _ = Command::new("kill") + .args(["-TERM", &format!("-{pid}")]) + .stderr(Stdio::null()) + .status() + .await; + if tokio::time::timeout(Duration::from_secs(2), child.wait()) + .await + .is_err() + { + let _ = Command::new("kill") + .args(["-KILL", &format!("-{pid}")]) + .stderr(Stdio::null()) + .status() + .await; + } + } + let _ = child.start_kill(); + let _ = child.wait().await; + } + let _ = &self.name; + } +} + +/// A message from the server: answers go to the waiting call; its own requests get `ping` answered +/// and anything else "method not supported" (this client offers no client features); notifications +/// (log messages, list changes) are not used. +async fn dispatch( + message: &Value, + pending: &Arc>>, + writer: &Arc>>, +) { + if let Some(method) = message.get("method") { + if let Some(id) = message.get("id") { + let reply = if method == "ping" { + json!({"jsonrpc": "2.0", "id": id, "result": {}}) + } else { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, + "message": format!("method not supported: {}", method.as_str().unwrap_or(""))}}) + }; + // Written from its own task: the reader must never wait on a full pipe. + let writer = writer.clone(); + tokio::spawn(async move { + let mut data = serde_json::to_vec(&reply).expect("json"); + data.push(b'\n'); + if let Some(pipe) = writer.lock().await.as_mut() { + let _ = pipe.write_all(&data).await; + let _ = pipe.flush().await; + } + }); + } + return; + } + let slot = message + .get("id") + .and_then(Value::as_u64) + .and_then(|id| pending.lock().expect("mcp pending").remove(&id)); + if let Some(slot) = slot { + let _ = slot.send(Ok(message.clone())); + } // an answer to a call that timed out is simply dropped +} + +async fn cancelled(cancel: &mut Option) { + match cancel { + Some(receiver) => { + if *receiver.borrow() { + return; + } + while receiver.changed().await.is_ok() { + if *receiver.borrow() { + return; + } + } + std::future::pending::<()>().await; + } + None => std::future::pending::<()>().await, + } +} + +/// Python's `f"{x:g}"` for the timeouts in messages. +fn fmt_g(x: f64) -> String { + if x.fract() == 0.0 && x.abs() < 1e15 { + format!("{x:.0}") + } else { + let text = format!("{x:.6}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() + } +} + +// ------------------------------------------------------------------------------------------------ http + +struct Http { + url: String, + headers: Vec<(String, String)>, + client: reqwest::Client, + session: Mutex>, + protocol: Mutex>, + next_id: AtomicU64, + broken: Mutex>, +} + +impl Http { + fn new(config: &Map) -> Self { + let url = config + .get("url") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let headers = config + .get("headers") + .and_then(Value::as_object) + .into_iter() + .flatten() + .map(|(k, v)| { + ( + k.clone(), + v.as_str().map_or_else(|| v.to_string(), str::to_owned), + ) + }) + .collect(); + Self { + url, + headers, + client: reqwest::Client::new(), + session: Mutex::new(None), + protocol: Mutex::new(None), + next_id: AtomicU64::new(0), + broken: Mutex::new(None), + } + } + + fn alive(&self) -> bool { + self.broken.lock().expect("mcp http").is_none() + } + + fn builder(&self, method: reqwest::Method, timeout: Duration) -> reqwest::RequestBuilder { + let mut builder = self + .client + .request(method, &self.url) + .timeout(timeout) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("User-Agent", "strata"); + for (key, value) in &self.headers { + builder = builder.header(key.as_str(), value.as_str()); + } + if let Some(session) = self.session.lock().expect("mcp http").clone() { + builder = builder.header("Mcp-Session-Id", session); + } + if let Some(protocol) = self.protocol.lock().expect("mcp http").clone() { + builder = builder.header("MCP-Protocol-Version", protocol); + } + builder + } + + /// POST one message; for a request (`id` set) return the response that answers it. + async fn post( + &self, + message: &Value, + id: Option, + timeout: Duration, + ) -> Result, McpError> { + let response = self + .builder(reqwest::Method::POST, timeout) + .body(serde_json::to_vec(message).expect("json")) + .send() + .await + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + if let Some(session) = response + .headers() + .get("Mcp-Session-Id") + .and_then(|v| v.to_str().ok()) + { + *self.session.lock().expect("mcp http") = Some(session.to_owned()); + } + let status = response.status(); + if !status.is_success() { + let had_session = self.session.lock().expect("mcp http").is_some(); + let detail: String = response + .text() + .await + .unwrap_or_default() + .chars() + .take(300) + .collect(); + if status.as_u16() == 404 && had_session { + // The session expired: a restart starts a new one. + *self.broken.lock().expect("mcp http") = + Some(failed("the server ended the session")); + } + return Err(failed(format!( + "HTTP {} {}{}", + status.as_u16(), + status.canonical_reason().unwrap_or(""), + if detail.is_empty() { + String::new() + } else { + format!(": {detail}") + } + ))); + } + let Some(id) = id else { return Ok(None) }; // a notification: 202, nothing to read + let is_events = response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.contains("text/event-stream")); + let found = if is_events { + read_events(response, id).await + } else { + let body = response + .text() + .await + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + if body.trim().is_empty() { + None + } else { + let parsed: Value = serde_json::from_str(&body) + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + match parsed { + Value::Array(items) => items, + other => vec![other], + } + .into_iter() + .find(|m| { + m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none() + }) + } + }; + found + .map(Some) + .ok_or_else(|| failed("the server's answer did not contain a response")) + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + mut cancel: Option, + ) -> Result { + if let Some(error) = self.broken.lock().expect("mcp http").clone() { + return Err(error); + } + let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1; + let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + let outcome = tokio::select! { + answer = self.post(&message, Some(id), timeout + Duration::from_secs(5)) => { + return match answer { + Ok(Some(message)) => response_result(&message), + Ok(None) => Err(failed("the server's answer did not contain a response")), + Err(error) => Err(error), + }; + } + () = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))), + () = cancelled(&mut cancel) => McpError::Cancelled, + }; + let _ = self + .notify( + "notifications/cancelled", + Some(json!({"requestId": id, "reason": outcome.to_string()})), + ) + .await; + Err(outcome) + } + + async fn notify(&self, method: &str, params: Option) -> Result<(), McpError> { + let mut message = json!({"jsonrpc": "2.0", "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.post(&message, None, Duration::from_secs(10)) + .await + .map(|_| ()) + } + + async fn close(&self) { + let Some(_) = self.session.lock().expect("mcp http").clone() else { + return; + }; + // End the session on the server (it may not allow that). + let _ = self + .builder(reqwest::Method::DELETE, Duration::from_secs(3)) + .send() + .await; + } +} + +/// Read an event stream until the event that answers `id` (it may carry notifications first). +async fn read_events(mut response: reqwest::Response, id: u64) -> Option { + let mut buffer = Vec::::new(); + let mut data: Vec = Vec::new(); + loop { + let chunk = response.chunk().await.ok().flatten(); + let finished = chunk.is_none(); + if let Some(chunk) = chunk { + buffer.extend_from_slice(&chunk); + } + while let Some(newline) = buffer.iter().position(|b| *b == b'\n') { + let raw: Vec = buffer.drain(..=newline).collect(); + let line = String::from_utf8_lossy(&raw) + .trim_end_matches(['\r', '\n']) + .to_owned(); + if let Some(rest) = line.strip_prefix("data:") { + data.push(rest.trim_start_matches(' ').to_owned()); + } else if line.is_empty() && !data.is_empty() { + let parsed = serde_json::from_str::(&data.join("\n")).ok(); + data.clear(); + let batch = match parsed { + Some(Value::Array(items)) => items, + Some(other) => vec![other], + None => Vec::new(), + }; + if let Some(found) = batch.into_iter().find(|m| { + m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none() + }) { + return Some(found); + } + } + } + if finished { + return None; + } + } +} + +// ------------------------------------------------------------------------------------------------ one server + +type StartResult = + Result<(Arc, Vec, Map), (McpError, Option>)>; + +enum Transport { + Stdio(StdioTransport), + Http(Http), +} + +impl Transport { + fn alive(&self) -> bool { + match self { + Self::Stdio(t) => t.alive(), + Self::Http(t) => t.alive(), + } + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + cancel: Option, + ) -> Result { + match self { + Self::Stdio(t) => t.request(method, params, timeout, cancel).await, + Self::Http(t) => t.request(method, params, timeout, cancel).await, + } + } + + async fn notify(&self, method: &str) -> Result<(), McpError> { + match self { + Self::Stdio(t) => t.notify(method, None).await, + Self::Http(t) => t.notify(method, None).await, + } + } + + async fn close(&self) { + match self { + Self::Stdio(t) => t.close().await, + Self::Http(t) => t.close().await, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + Idle, + Starting, + Ready, + Failed, + Stopped, +} + +impl Status { + fn as_str(&self) -> &'static str { + match self { + Self::Idle => "idle", + Self::Starting => "starting", + Self::Ready => "ready", + Self::Failed => "failed", + Self::Stopped => "stopped", + } + } +} + +struct State { + status: Status, + error: Option, + tools: Vec, + info: Map, + transport: Option>, + last_start: Option, +} + +pub struct Server { + pub name: String, + config: Map, + kind: &'static str, + settings: Settings, + state: AsyncMutex, +} + +impl Server { + fn new(name: String, config: Map, settings: Settings) -> Self { + let kind = if config + .get("url") + .is_some_and(|u| u.as_str().is_some_and(|s| !s.is_empty())) + { + "http" + } else { + "stdio" + }; + Self { + name, + config, + kind, + settings, + state: AsyncMutex::new(State { + status: Status::Idle, + error: None, + tools: Vec::new(), + info: Map::new(), + transport: None, + last_start: None, + }), + } + } + + pub async fn start(&self) -> bool { + let mut state = self.state.lock().await; + self.start_locked(&mut state).await + } + + async fn start_locked(&self, state: &mut State) -> bool { + if let Some(old) = state.transport.take() { + old.close().await; + } + state.status = Status::Starting; + state.error = None; + state.last_start = Some(Instant::now()); + let timeout = Duration::from_secs_f64(self.settings.start_timeout_s); + let transport = if self.kind == "http" { + Ok(Transport::Http(Http::new(&self.config))) + } else { + StdioTransport::spawn(&self.name, &self.config) + .await + .map(Transport::Stdio) + }; + let result: StartResult = async { + let transport = Arc::new(transport.map_err(|e| (e, None))?); + let t = transport.clone(); + let fail = |e: McpError| (e, Some(t.clone())); + let init = transport + .request( + "initialize", + json!({"protocolVersion": PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "strata", "title": "Strata", "version": "1"}}), + timeout, + None, + ) + .await + .map_err(fail)?; + let protocol = init + .get("protocolVersion") + .and_then(Value::as_str) + .filter(|p| !p.is_empty()) + .unwrap_or(PROTOCOL) + .to_owned(); + if let Transport::Http(http) = &*transport { + *http.protocol.lock().expect("mcp http") = Some(protocol.clone()); + } + let mut info: Map = init + .get("serverInfo") + .and_then(Value::as_object) + .map(|o| { + o.iter() + .filter(|(k, _)| matches!(k.as_str(), "name" | "title" | "version")) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() + }) + .unwrap_or_default(); + info.insert("protocol".into(), json!(protocol)); + transport.notify("notifications/initialized").await.map_err(fail)?; + let mut tools: Vec = Vec::new(); + let mut cursor: Option = None; + for _ in 0..100 { + // pages; a server that never stops paging is cut off + let params = cursor.as_ref().map_or_else(|| json!({}), |c| json!({"cursor": c})); + let page = match transport.request("tools/list", params, timeout, None).await { + Ok(page) => page, + // a server without tools (prompts/resources only) + Err(e) if e.to_string().contains("code -32601") && tools.is_empty() => break, + Err(e) => return Err(fail(e)), + }; + tools.extend( + page.get("tools") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|t| t.get("name").and_then(Value::as_str).is_some_and(|n| !n.is_empty())) + .cloned(), + ); + cursor = page + .get("nextCursor") + .and_then(Value::as_str) + .filter(|c| !c.is_empty()) + .map(str::to_owned); + if cursor.is_none() { + break; + } + } + Ok((transport, tools, info)) + } + .await; + match result { + Ok((transport, tools, info)) => { + let names = tools + .iter() + .take(8) + .filter_map(|t| t["name"].as_str()) + .collect::>() + .join(", ") + + if tools.len() > 8 { ", ..." } else { "" }; + eprintln!( + "MCP server {:?}: {} tool{}{}", + self.name, + tools.len(), + if tools.len() == 1 { "" } else { "s" }, + if tools.is_empty() { + String::new() + } else { + format!(" ({names})") + } + ); + state.tools = tools; + state.info = info; + state.transport = Some(transport); + state.status = Status::Ready; + true + } + Err((error, transport)) => { + state.status = Status::Failed; + state.error = Some(error.to_string()); + state.tools = Vec::new(); + if let Some(transport) = transport { + transport.close().await; + } + eprintln!( + "MCP server {:?} did not start: {error}. Its tools are left out; the chat works without them.", + self.name + ); + false + } + } + } + + pub async fn call( + &self, + tool: &str, + arguments: Value, + timeout: Duration, + cancel: Option, + ) -> Result { + let transport = { + let mut state = self.state.lock().await; + if state.transport.as_ref().is_none_or(|t| !t.alive()) { + // It stopped since its last call (a crash, an expired session): start it again; one + // that failed to start is retried at most every 10 s. + if state.status == Status::Failed + && state + .last_start + .is_some_and(|at| at.elapsed() < Duration::from_secs(10)) + { + return Err(failed(format!( + "the server is not running ({})", + state.error.clone().unwrap_or_else(|| "it stopped".into()) + ))); + } + eprintln!("MCP server {:?} had stopped; starting it again", self.name); + if !self.start_locked(&mut state).await { + return Err(failed(format!( + "the server could not be started again: {}", + state.error.clone().unwrap_or_default() + ))); + } + } + state.transport.clone().expect("started") + }; + let result = transport + .request( + "tools/call", + json!({"name": tool, "arguments": arguments}), + timeout, + cancel, + ) + .await; + if let Err(error) = &result + && !transport.alive() + { + let mut state = self.state.lock().await; + state.status = Status::Stopped; + state.error = Some(error.to_string()); + } + result + } + + pub async fn close(&self) { + let mut state = self.state.lock().await; + if let Some(transport) = state.transport.take() { + transport.close().await; + } + if matches!(state.status, Status::Ready | Status::Starting) { + state.status = Status::Stopped; + } + } +} + +// ------------------------------------------------------------------------------------------------ the hub + +/// `result_text`: an MCP tool result as the text the model reads - text blocks as they are, other +/// blocks named. +pub fn result_text(result: &Value) -> String { + let mut parts: Vec = Vec::new(); + for block in result + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let Some(block) = block.as_object() else { + continue; + }; + let text = |key: &str| { + block + .get(key) + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned)) + .unwrap_or_default() + }; + match block.get("type").and_then(Value::as_str) { + Some("text") => parts.push(text("text")), + Some("resource") => { + let resource = block.get("resource").and_then(Value::as_object); + parts.push(match resource.and_then(|r| r.get("text")) { + Some(v) => v.as_str().map_or_else(|| v.to_string(), str::to_owned), + None => format!( + "[resource {} ({}), not shown]", + resource + .and_then(|r| r.get("uri")) + .and_then(Value::as_str) + .unwrap_or(""), + resource + .and_then(|r| r.get("mimeType")) + .and_then(Value::as_str) + .unwrap_or("binary") + ), + }); + } + Some("resource_link") => parts.push( + format!("[resource link: {} {}]", text("name"), text("uri")).replace(" ", " "), + ), + Some(kind @ ("image" | "audio")) => { + let size = block + .get("data") + .and_then(Value::as_str) + .map_or(0, str::len) + * 3 + / 4; + parts.push(format!( + "[{kind} ({}, {} bytes): not shown to the model]", + block.get("mimeType").and_then(Value::as_str).unwrap_or("?"), + group_thousands(size) + )); + } + _ => parts.push(Value::Object(block.clone()).to_string()), + } + } + if parts.is_empty() + && let Some(structured) = result.get("structuredContent").filter(|v| !v.is_null()) + { + parts.push(structured.to_string()); + } + parts.join("\n") +} + +/// Python's `f"{n:,}"`. +fn group_thousands(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +fn clean(name: &str) -> String { + let cleaned: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' || c == '-' { + c + } else { + '_' + } + }) + .collect(); + if cleaned.is_empty() { + "x".into() + } else { + cleaned + } +} + +/// One tool call's outcome (`McpHub.call`). +#[derive(Clone, Debug, PartialEq)] +pub struct CallOutput { + pub ok: bool, + /// What the model reads, capped. + pub text: String, + /// The full length in characters. + pub chars: usize, + pub truncated: bool, + pub ms: u64, + pub server: Option, + pub tool: String, +} + +pub struct Hub { + pub servers: Vec>, + settings: Settings, +} + +impl Hub { + pub fn new(servers: BTreeMap>, settings: Settings) -> Self { + Self { + servers: servers + .into_iter() + .map(|(name, config)| Arc::new(Server::new(name, config, settings.clone()))) + .collect(), + settings, + } + } + + /// Start every server concurrently and wait for all of them (npx may download a package first; + /// callers that must not wait spawn this). + pub async fn start(&self) { + let mut tasks = tokio::task::JoinSet::new(); + for server in &self.servers { + let server = server.clone(); + tasks.spawn(async move { server.start().await }); + } + while tasks.join_next().await.is_some() {} + } + + /// tool name the model sees -> (server, the tool's own name). A server that stopped after it + /// was ready keeps its tools here: a call starts it again. + pub async fn routes(&self) -> Vec<(String, Arc, String)> { + let mut out: Vec<(String, Arc, String)> = Vec::new(); + for server in &self.servers { + let state = server.state.lock().await; + if !matches!(state.status, Status::Ready | Status::Stopped) { + continue; + } + for tool in &state.tools { + let own = tool["name"].as_str().unwrap_or_default().to_owned(); + let mut name: String = format!("{}__{}", clean(&server.name), clean(&own)) + .chars() + .take(64) + .collect(); + let mut n = 2; + while out.iter().any(|(existing, _, _)| *existing == name) { + // two names that differ only in cleaned characters + name = format!("{}_{n}", name.chars().take(60).collect::()); + n += 1; + } + out.push((name, server.clone(), own)); + } + } + out + } + + /// The tools in the chat template's form (`{name, description, parameters}`); `exclude`: names + /// the request brought itself (those win). + pub async fn template_tools(&self, exclude: &[String]) -> Vec { + let mut out = Vec::new(); + for (name, server, own) in self.routes().await { + if exclude.contains(&name) { + continue; + } + let state = server.state.lock().await; + let Some(tool) = state.tools.iter().find(|t| t["name"] == own.as_str()) else { + continue; + }; + let schema = tool + .get("inputSchema") + .filter(|s| s.as_object().is_some_and(|o| !o.is_empty())) + .cloned() + .unwrap_or_else(|| json!({"type": "object", "properties": {}})); + let description = [tool.get("description"), tool.get("title")] + .into_iter() + .flatten() + .filter_map(Value::as_str) + .find(|s| !s.is_empty()) + .unwrap_or(""); + out.push(json!({"name": name, "description": description, "parameters": schema})); + } + out + } + + /// Run one tool. Errors become text starting with `error:`; only a stop (`cancel`) is an `Err`. + pub async fn call( + &self, + name: &str, + arguments: Value, + cancel: Option, + ) -> Result { + let started = Instant::now(); + let route = self.routes().await.into_iter().find(|(n, _, _)| n == name); + let (server, tool) = match &route { + Some((_, server, tool)) => (Some(server.clone()), tool.clone()), + None => (None, name.to_owned()), + }; + let (mut text, ok) = match &server { + None => (format!("error: there is no tool named {name:?}"), false), + Some(server) => { + let arguments = if arguments.is_object() { + arguments + } else { + json!({}) + }; + match server + .call( + &tool, + arguments, + Duration::from_secs_f64(self.settings.timeout_s), + cancel, + ) + .await + { + Ok(result) => { + let text = result_text(&result); + let ok = !result.get("isError").is_some_and(|v| v == &json!(true)); + if ok { + (text, true) + } else { + ( + format!( + "error: {}", + if text.is_empty() { + "the tool reported an error".to_owned() + } else { + text + } + ), + false, + ) + } + } + Err(McpError::Cancelled) => return Err(McpError::Cancelled), + Err(error) => (format!("error: {error}"), false), + } + } + }; + let cap = self.settings.max_result_chars; + let full = text.chars().count(); + let truncated = cap > 0 && full > cap; + if truncated { + text = text.chars().take(cap).collect::() + + &format!( + "\n\n[... truncated: the tool returned {} characters; only the first {} are shown]", + group_thousands(full), + group_thousands(cap) + ); + } + Ok(CallOutput { + ok, + text, + chars: full, + truncated, + ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + server: server.as_ref().map(|s| s.name.clone()), + tool, + }) + } + + /// `GET /mcp`: every server, its state and its tools. + pub async fn status(&self) -> Value { + let routes = self.routes().await; + let mut servers = Vec::new(); + for server in &self.servers { + let state = server.state.lock().await; + let tools: Vec = state + .tools + .iter() + .map(|tool| { + let own = tool["name"].as_str().unwrap_or_default(); + let seen = routes + .iter() + .find(|(_, s, t)| Arc::ptr_eq(s, server) && t == own) + .map_or(own, |(n, _, _)| n.as_str()); + json!({"name": seen, "tool": own, + "description": tool.get("description").and_then(Value::as_str).unwrap_or("") + .chars().take(300).collect::()}) + }) + .collect(); + servers.push(json!({"name": server.name, "transport": server.kind, + "status": state.status.as_str(), "error": state.error, "info": state.info, + "tools": tools})); + } + json!({"servers": servers, "tools": routes.len(), + "settings": {"timeout_s": self.settings.timeout_s, + "max_result_chars": self.settings.max_result_chars, + "max_rounds": self.settings.max_rounds}}) + } + + pub async fn close(&self) { + for server in &self.servers { + server.close().await; + } + } +} + +// ------------------------------------------------------------------------------------------------ config + +/// Python truthiness of a JSON value (`None`, `""`, `0`, `False`, `[]`, `{}`). +fn falsy(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Bool(b) => !b, + Value::Number(n) => n.as_f64() == Some(0.0), + Value::String(s) => s.is_empty(), + Value::Array(a) => a.is_empty(), + Value::Object(o) => o.is_empty(), + } +} + +fn check_server(name: &str, config: &Value, location: &str) -> Result, String> { + let Some(object) = config.as_object() else { + return Err(format!( + "[strata] {location}: MCP server {} must be an object with \"command\" or \"url\"", + leleka_serving_policy::shared::py_str_repr(name) + )); + }; + let quoted = leleka_serving_policy::shared::py_str_repr(name); + let truthy = |key: &str| object.get(key).is_some_and(|v| !falsy(v)); + if truthy("url") { + if object.get("type") == Some(&json!("sse")) { + return Err(format!( + "[strata] {location}: MCP server {quoted} uses the old SSE transport (\"type\": \"sse\"); Strata speaks Streamable HTTP - most servers offer it at /mcp" + )); + } + if object + .get("headers") + .is_some_and(|h| !falsy(h) && !h.is_object()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"headers\" must be an object" + )); + } + return Ok(object.clone()); + } + if object + .get("command") + .and_then(Value::as_str) + .is_none_or(|c| c.trim().is_empty()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted} needs \"command\" (a program to start) or \"url\"" + )); + } + if object + .get("args") + .is_some_and(|a| !falsy(a) && !a.is_array()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"args\" must be a list" + )); + } + if object + .get("env") + .is_some_and(|e| !falsy(e) && !e.is_object()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"env\" must be an object" + )); + } + Ok(object.clone()) +} + +/// `{"name": {...}}` with the entries checked; `"disabled": true` leaves one out. +pub fn servers_from( + block: &Value, + location: &str, +) -> Result>, String> { + let mut out = BTreeMap::new(); + match block { + Value::Null => {} + Value::Object(map) => { + for (name, config) in map { + if config.get("disabled") == Some(&json!(true)) { + continue; + } + out.insert(name.clone(), check_server(name, config, location)?); + } + } + _ => { + return Err(format!( + "[strata] {location}: the MCP servers must be an object {{\"name\": {{...}}}}" + )); + } + } + Ok(out) +} + +/// The run config's optional `mcp` block: `timeout_s`, `max_result_chars`, `max_rounds`, +/// `start_timeout_s`. +pub fn settings_from(block: &Value) -> Result { + let mut settings = Settings::default(); + let Some(map) = block.as_object() else { + return Ok(settings); + }; + for (key, value) in map { + let number = value.is_number(); + let bad = |expected: &str| { + format!( + "[strata] config mcp.{key}={}: {expected}", + leleka_serving_policy::shared::py_repr(value) + ) + }; + match key.as_str() { + "timeout_s" | "start_timeout_s" => { + let seconds = value + .as_f64() + .filter(|v| number && *v > 0.0 && v.is_finite()) + .ok_or_else(|| bad("expected a number of seconds > 0"))?; + if key == "timeout_s" { + settings.timeout_s = seconds; + } else { + settings.start_timeout_s = seconds; + } + } + "max_result_chars" | "max_rounds" => { + let count = value + .as_u64() + .filter(|v| *v >= 1) + .or_else(|| { + value + .as_f64() + .filter(|f| f.fract() == 0.0 && *f >= 1.0) + .map(|f| f as u64) + }) + .ok_or_else(|| bad("expected a positive integer"))?; + if key == "max_result_chars" { + settings.max_result_chars = usize::try_from(count).unwrap_or(usize::MAX); + } else { + settings.max_rounds = usize::try_from(count).unwrap_or(usize::MAX); + } + } + other => eprintln!( + "config mcp.{other}={}: unknown key, ignored", + leleka_serving_policy::shared::py_repr(value) + ), + } + } + Ok(settings) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn results_read_as_text_with_other_blocks_named() { + let result = json!({"content": [ + {"type": "text", "text": "hello"}, + {"type": "resource", "resource": {"uri": "file:///a", "mimeType": "image/png"}}, + {"type": "resource", "resource": {"text": "inline"}}, + {"type": "resource_link", "name": "doc", "uri": "http://x"}, + {"type": "image", "mimeType": "image/png", "data": "AAAAAAAA"}, + {"type": "weird", "k": 1}, + "not a block" + ]}); + assert_eq!( + result_text(&result), + "hello\n[resource file:///a (image/png), not shown]\ninline\n[resource link: doc http://x]\n[image (image/png, 6 bytes): not shown to the model]\n{\"k\":1,\"type\":\"weird\"}" + ); + assert_eq!( + result_text(&json!({"structuredContent": {"a": 1}})), + "{\"a\":1}" + ); + assert_eq!(result_text(&json!({})), ""); + assert_eq!(group_thousands(1234567), "1,234,567"); + assert_eq!(group_thousands(12), "12"); + } + + #[test] + fn json_rpc_errors_read_like_the_originals() { + assert_eq!( + response_result(&json!({"error": {"code": -32602, "message": "unknown tool x"}})) + .unwrap_err(), + failed("unknown tool x (code -32602)") + ); + assert_eq!( + response_result(&json!({"error": "plain"})).unwrap_err(), + failed("\"plain\" (code None)") + ); + assert_eq!(response_result(&json!({"id": 1})).unwrap(), json!({})); + } + + #[test] + fn server_entries_are_checked_at_start() { + let ok = servers_from( + &json!({"a": {"command": "npx", "args": ["x"]}, "b": {"url": "http://h/mcp", "headers": {"k": "v"}}, + "off": {"command": "x", "disabled": true}}), + "config mcp_servers", + ) + .unwrap(); + assert_eq!(ok.keys().collect::>(), vec!["a", "b"]); + for bad in [ + json!({"a": "nope"}), + json!({"a": {}}), + json!({"a": {"command": " "}}), + json!({"a": {"command": "x", "args": "y"}}), + json!({"a": {"command": "x", "env": ["x"]}}), + json!({"a": {"url": "http://h", "type": "sse"}}), + json!({"a": {"url": "http://h", "headers": ["x"]}}), + json!([1]), + ] { + assert!(servers_from(&bad, "w").is_err(), "{bad}"); + } + assert!(servers_from(&Value::Null, "w").unwrap().is_empty()); + } + + #[test] + fn settings_block_is_checked() { + let s = settings_from(&json!({"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3, "start_timeout_s": 7.5, "x": 1})).unwrap(); + assert_eq!( + s, + Settings { + timeout_s: 5.0, + max_result_chars: 100, + max_rounds: 3, + start_timeout_s: 7.5 + } + ); + for bad in [ + json!({"timeout_s": 0}), + json!({"timeout_s": "5"}), + json!({"max_rounds": 0}), + json!({"max_result_chars": 1.5}), + ] { + assert!(settings_from(&bad).is_err(), "{bad}"); + } + assert_eq!(settings_from(&Value::Null).unwrap(), Settings::default()); + } + + #[test] + fn tool_names_are_cleaned_and_made_unique() { + assert_eq!(clean("my server!"), "my_server_"); + assert_eq!(clean(""), "x"); + assert_eq!(fmt_g(60.0), "60"); + assert_eq!(fmt_g(0.5), "0.5"); + } +} diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index 8036d2e6..937e76f9 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -415,14 +415,19 @@ pub async fn create( Ok(v) => v, Err(e) => return error(e.status(), &e.to_string()), }; + // Anthropic's own top_k plus the Original server's extensions go to the native request as written. + let (value, extensions) = crate::sampling::split_extensions(value); let r: Request = match serde_json::from_value(value) { Ok(r) => r, Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()), }; - let (r, stream) = match r.into_responses() { + let (mut r, stream) = match r.into_responses() { Ok(r) => r, Err(e) => return error(StatusCode::BAD_REQUEST, &e), }; + for (key, value) in extensions { + r[key] = value; + } let response = responses::create(State(state), Ok(Json(r))).await; if !response.status().is_success() { return response; diff --git a/control-plane/src/models_api.rs b/control-plane/src/models_api.rs index 5fbe6f87..d6c33832 100644 --- a/control-plane/src/models_api.rs +++ b/control-plane/src/models_api.rs @@ -15,6 +15,31 @@ fn record(id: &str) -> Value { json!({"id":id,"object":"model","created":0,"owned_by":"local"}) } +/// The model and each configured alias (`alias_of` names the model), like the Original; an engine +/// that is unloaded on purpose says so (`status`) and still lists: it loads on use. +async fn records(state: &AppState) -> Vec { + let unloaded = state.worker.read().await.state == crate::worker::WorkerState::Unloaded; + let mark = |mut value: Value| { + if unloaded { + value["status"] = json!({"value": "unloaded"}); + } + value + }; + let Some(model) = state.model.as_deref() else { + return Vec::new(); + }; + let mut out = vec![mark(record(model))]; + if !state.aliases.is_empty() { + out[0]["aliases"] = json!(*state.aliases); + } + for alias in state.aliases.iter() { + let mut value = mark(record(alias)); + value["alias_of"] = json!(model); + out.push(value); + } + out +} + fn query_error(query: Option) -> Option { query.filter(|q| !q.is_empty()).map(|_| { ( @@ -32,7 +57,7 @@ pub async fn list(State(state): State, RawQuery(query): RawQuery) -> R if let Some(error) = query_error(query) { return error; } - let data: Vec<_> = state.model.as_deref().map(record).into_iter().collect(); + let data = records(&state).await; Json(json!({"object":"list","data":data})).into_response() } @@ -44,8 +69,12 @@ pub async fn retrieve( if let Some(error) = query_error(query) { return error; } - if state.model.as_deref() == Some(id.as_str()) { - return Json(record(&id)).into_response(); + if let Some(found) = records(&state) + .await + .into_iter() + .find(|value| value["id"] == id.as_str()) + { + return Json(found).into_response(); } ( StatusCode::NOT_FOUND, diff --git a/control-plane/src/queue.rs b/control-plane/src/queue.rs index f00c0776..06705ff1 100644 --- a/control-plane/src/queue.rs +++ b/control-plane/src/queue.rs @@ -104,8 +104,7 @@ mod tests { request: Generate { token_ids: vec![65], max_new: 1, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result), }, diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 4f488a07..2ea0dfcf 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -500,6 +500,17 @@ pub struct CreateRequest { pub tool_choice: Option, pub temperature: Option, pub top_p: Option, + /// Original-server sampling extensions (top level, like `serve/server.py`): see `sampling`. + pub top_k: Option, + pub min_p: Option, + pub repetition_penalty: Option, + pub frequency_penalty: Option, + pub presence_penalty: Option, + pub penalty_last_n: Option, + pub seed: Option, + pub strata_tune: Option, + pub experimental_speed_projection: Option, + pub reasoning_budget_tokens: Option, pub truncation: Option, pub metadata: Option>, pub store: Option, @@ -528,6 +539,53 @@ pub enum TextFormat { } impl CreateRequest { + /// The request's sampling fields as the Original's serving layer reads them. + pub fn sampling(&self) -> leleka_sampler_ref::RequestSampling { + leleka_sampler_ref::RequestSampling { + temperature: self.temperature, + top_p: self.top_p, + top_k: self.top_k, + min_p: self.min_p, + repetition_penalty: self.repetition_penalty, + frequency_penalty: self.frequency_penalty, + presence_penalty: self.presence_penalty, + penalty_last_n: self.penalty_last_n, + seed: self.seed, + } + } + + /// Fill what the request left out from the server defaults: the config's `sampling` block, + /// then the shared Chat settings (`{**config, **shared}`, request fields win, an explicit + /// `temperature: 0` stays greedy), the shared `max_tokens`, and the shared reasoning effort. + pub fn apply_defaults(&mut self, settings: &crate::settings::Settings) { + let merged = settings.merged(); + let shared = settings.shared(); + let effective = + leleka_sampler_ref::RequestSampling::overlay(&merged.sampling, &self.sampling()); + self.temperature = effective.temperature; + self.top_p = effective.top_p; + self.top_k = effective.top_k; + self.min_p = effective.min_p; + self.repetition_penalty = effective.repetition_penalty; + self.frequency_penalty = effective.frequency_penalty; + self.presence_penalty = effective.presence_penalty; + self.penalty_last_n = effective.penalty_last_n; + self.seed = effective.seed; + self.experimental_speed_projection = self + .experimental_speed_projection + .or(merged.experimental_speed_projection); + if self.max_output_tokens.is_none() + && let Some(limit) = shared.max_tokens + { + self.max_output_tokens = Some(limit.min(u64::from(u32::MAX)) as u32); + } + if self.reasoning.is_none() + && let Some(effort) = &shared.reasoning_effort + { + self.reasoning = Some(json!({"effort": effort})); + } + } + fn forced_tool(&self) -> Option<&str> { self.tool_choice .as_ref() @@ -608,17 +666,20 @@ impl CreateRequest { if self.max_output_tokens == Some(0) { return Err(("max_output_tokens", "max_output_tokens must be positive")); } - if self - .temperature - .is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value)) - { - return Err(("temperature", "temperature must be between 0 and 2")); + crate::sampling::validate(&self.sampling())?; + if let Some(tune) = &self.strata_tune { + crate::sampling::validate_tune(tune)?; } - if self - .top_p - .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) + if leleka_serving_policy::reasoning::parse_budget( + self.reasoning_budget_tokens.as_ref(), + None, + ) + .is_err() { - return Err(("top_p", "top_p must be between 0 and 1")); + return Err(( + "reasoning_budget_tokens", + "reasoning_budget_tokens must be a whole number of tokens (0: no budget)", + )); } if let Some(TextOptions { format: TextFormat::JsonSchema { name, schema, .. }, @@ -773,7 +834,7 @@ fn parse_request( if state .model .as_ref() - .is_some_and(|model| model != &request.model) + .is_some_and(|model| model != &request.model && !state.aliases.contains(&request.model)) { return Err(Box::new(api_error( StatusCode::NOT_FOUND, @@ -910,6 +971,9 @@ pub async fn create( Ok(request) => request, Err(error) => return *error, }; + if let Err(response) = crate::server_api::ensure_loaded(&state).await { + return *response; + } if state.worker.read().await.state != WorkerState::Ready { return api_error( StatusCode::SERVICE_UNAVAILABLE, @@ -937,6 +1001,7 @@ pub async fn create( message, ); } + request.apply_defaults(&state.settings); let token_ids = match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { Ok(ids) => ids, Err(error) => return *error, @@ -957,8 +1022,11 @@ pub async fn create( max_new: request .max_output_tokens .unwrap_or(32768.min(remaining).max(1)), - temperature: request.temperature, - top_p: request.top_p, + sampling: request.sampling(), + tune: request.strata_tune.map(Into::into), + cvec: request.experimental_speed_projection, + embeddings: None, + reasoning: reasoning_plan(&request, &state, tokenizer), }; if request.stream { let (events, received) = mpsc::channel(16); @@ -1327,6 +1395,37 @@ impl ReasoningStream { } } +/// The reasoning-budget wrap-up for this request, if thinking is on and a budget is set (the +/// request's `reasoning_budget_tokens`, else the config's). +fn reasoning_plan( + request: &CreateRequest, + state: &AppState, + tokenizer: &Arc, +) -> Option { + if !reasoning_enabled(request) { + return None; + } + let budget = leleka_serving_policy::reasoning::parse_budget( + request.reasoning_budget_tokens.as_ref(), + state.settings.reasoning_budget_default(), + ) + .ok()??; + let wrap_up = tokenizer + .encode(leleka_serving_policy::reasoning::WRAP_UP, true) + .ok()?; + let stop_ids = ["<|im_end|>", "<|endoftext|>"] + .into_iter() + .filter_map(|name| tokenizer.special_id(name)) + .collect(); + let bytes_of = tokenizer.clone(); + Some(crate::wire::ReasoningPlan { + budget, + wrap_up, + stop_ids, + token_bytes: Arc::new(move |id| bytes_of.decode_bytes(&[id]).unwrap_or_default()), + }) +} + fn is_structured(request: &CreateRequest) -> bool { request .text @@ -4115,6 +4214,264 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + /// Run one request through `route` against a fake worker and return the `Generate` it was handed. + async fn captured_generate( + settings: crate::settings::Settings, + body: Value, + route: F, + ) -> (StatusCode, Option) + where + F: FnOnce( + State, + Result, axum::extract::rejection::JsonRejection>, + ) -> Fut, + Fut: std::future::Future, + { + let (tokenizer, root) = test_tokenizer(); + let (sender, mut receiver) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer); + state.generation = Some(sender); + state.settings = Arc::new(settings); + let worker = tokio::spawn(async move { + let command: GenerationCommand = receiver.recv().await?; + let request = command.request.clone(); + let prompt_tokens = command.request.token_ids.len() as u64; + let events = vec![ + Event::Token(79), + Event::Token(75), + Event::Done(Done { + generated: 2, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: Some(0), + expert_hits: None, + expert_lookups: None, + }), + ]; + match command.result { + GenerationResult::Buffered(result) => { + let _ = result.send(Ok(events)); + } + GenerationResult::Streaming(sender) => { + for event in events { + let _ = sender.send(Ok(event)).await; + } + } + GenerationResult::Finished => {} + } + Some(request) + }); + let response = route(State(state), Ok(Json(body))).await; + let status = response.status(); + let _ = to_bytes(response.into_body(), usize::MAX).await; + // A request refused before the queue never reaches the worker; any other answer (even an + // error about the fake worker's output) means the worker was handed the request. + let generate = if matches!( + status, + StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND | StatusCode::NOT_IMPLEMENTED + ) { + worker.abort(); + None + } else { + worker.await.unwrap() + }; + fs::remove_dir_all(root).unwrap(); + (status, generate) + } + + fn all_sampling_fields() -> Value { + json!({"temperature": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.05, + "repetition_penalty": 1.1, "frequency_penalty": 0.25, "presence_penalty": 0.5, + "penalty_last_n": 128, "seed": 42, + "strata_tune": {"pcie_frac": 0.0, "spec_min_p": 0.25}, "experimental_speed_projection": false}) + } + + const FULL_KEYS: &str = " temperature=0.7 top_p=0.9 top_k=40 min_p=0.05 penalty_repeat=1.1 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=128 seed=42 pcie_frac=0.0 spec_min_p=0.25 cvec=0"; + + fn merge(mut base: Value, extra: Value) -> Value { + base.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + base + } + + #[tokio::test] + async fn responses_forward_every_original_gen_field() { + for stream in [false, true] { + let body = merge( + json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}, "stream": stream}), + all_sampling_fields(), + ); + let (status, generate) = captured_generate(Default::default(), body, create).await; + assert_eq!(status, StatusCode::OK); + let line = generate.unwrap().line().unwrap(); + assert!( + line.starts_with(&format!("GEN 32768{FULL_KEYS} ")), + "{line}" + ); + } + } + + #[tokio::test] + async fn chat_completions_forward_penalties_and_extensions() { + let body = merge( + json!({"model": "strata-local", "messages": [{"role": "user", "content": "Hello"}]}), + all_sampling_fields(), + ); + let (status, generate) = + captured_generate(Default::default(), body, crate::chat::create).await; + assert_eq!(status, StatusCode::OK); + let line = generate.unwrap().line().unwrap(); + assert!( + line.starts_with(&format!("GEN 32768{FULL_KEYS} ")), + "{line}" + ); + } + + #[tokio::test] + async fn messages_forward_anthropic_top_k_and_extensions() { + let body = json!({"model": "strata-local", "max_tokens": 64, + "messages": [{"role": "user", "content": "Hello"}], + "temperature": 0.5, "top_p": 0.8, "top_k": 30, "seed": 9, "repetition_penalty": 1.2}); + let (status, generate) = + captured_generate(Default::default(), body, crate::messages::create).await; + assert_eq!(status, StatusCode::OK); + let line = generate.unwrap().line().unwrap(); + assert!( + line.starts_with( + "GEN 64 temperature=0.5 top_p=0.8 top_k=30 penalty_repeat=1.2 penalty_last_n=64 seed=9 " + ), + "{line}" + ); + } + + #[tokio::test] + async fn out_of_range_sampling_is_refused_before_the_worker() { + for bad in [ + json!({"temperature": 2.5}), + json!({"top_p": 1.5}), + json!({"top_k": -1}), + json!({"min_p": 1.5}), + json!({"repetition_penalty": 0}), + json!({"frequency_penalty": 3}), + json!({"presence_penalty": -3}), + json!({"penalty_last_n": -1}), + json!({"seed": -1}), + json!({"strata_tune": {"pcie_frac": 2}}), + json!({"strata_tune": {"unknown": 1}}), + json!({"reasoning_budget_tokens": "many"}), + ] { + let body = merge( + json!({"model": "strata-local", "input": "Hello"}), + bad.clone(), + ); + let (status, generate) = captured_generate(Default::default(), body, create).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}"); + assert!(generate.is_none()); + } + } + + #[tokio::test] + async fn reasoning_budget_reaches_the_worker_only_when_thinking_is_on() { + let thinking = |extra: Value| { + merge( + json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "high"}}), + extra, + ) + }; + let (_, generate) = captured_generate( + Default::default(), + thinking(json!({"reasoning_budget_tokens": 20})), + create, + ) + .await; + let plan = generate.unwrap().reasoning.expect("a plan"); + assert_eq!(plan.budget, 20); + assert!(!plan.wrap_up.is_empty()); + assert_eq!( + plan.stop_ids, + vec![257], + "<|im_end|> of the test vocabulary" + ); + assert_eq!((plan.token_bytes)(79), b"O".to_vec()); + // Thinking off, a zero budget, or no budget at all: no plan. + for body in [ + merge( + json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}}), + json!({"reasoning_budget_tokens": 20}), + ), + thinking(json!({"reasoning_budget_tokens": 0})), + thinking(json!({})), + ] { + let (_, generate) = captured_generate(Default::default(), body, create).await; + assert!(generate.unwrap().reasoning.is_none()); + } + // The config's default applies, and a request can switch it off. + let settings = crate::settings::Settings::default().with_reasoning_budget(Some(json!(50))); + let (_, generate) = captured_generate(settings, thinking(json!({})), create).await; + assert_eq!(generate.unwrap().reasoning.unwrap().budget, 50); + let settings = crate::settings::Settings::default().with_reasoning_budget(Some(json!(50))); + let (_, generate) = captured_generate( + settings, + thinking(json!({"reasoning_budget_tokens": 0})), + create, + ) + .await; + assert!(generate.unwrap().reasoning.is_none()); + } + + #[tokio::test] + async fn server_defaults_fill_what_the_request_leaves_out() { + use leleka_serving_policy::shared::sampling_defaults_from_config; + let config = + sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1, "top_k": 10})) + .unwrap(); + let settings = crate::settings::Settings::new(config); + settings + .set_shared(&json!({"temperature": 0.9, "seed": 4, "max_tokens": 77})) + .unwrap(); + let body = + json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}}); + let (_, generate) = captured_generate(settings, body.clone(), create).await; + let generate = generate.unwrap(); + assert_eq!(generate.max_new, 77); + assert!( + generate + .line() + .unwrap() + .starts_with("GEN 77 temperature=0.9 top_k=10 min_p=0.1 seed=4 "), + "{}", + generate.line().unwrap() + ); + // The request wins, and an explicit 0 stays greedy. + let settings = crate::settings::Settings::default(); + settings + .set_shared(&json!({"temperature": 0.9, "max_tokens": 77})) + .unwrap(); + let (_, generate) = captured_generate( + settings, + merge(body, json!({"temperature": 0, "max_output_tokens": 5})), + create, + ) + .await; + assert_eq!( + generate + .unwrap() + .line() + .unwrap() + .split(' ') + .take(2) + .collect::>(), + ["GEN", "5"] + ); + } + #[tokio::test] async fn nonstreaming_tool_call_keeps_typed_arguments() { let (tokenizer, root) = test_tokenizer(); diff --git a/control-plane/src/sampling.rs b/control-plane/src/sampling.rs new file mode 100644 index 00000000..546f692e --- /dev/null +++ b/control-plane/src/sampling.rs @@ -0,0 +1,216 @@ +//! Request sampling plumbing shared by the Responses, Chat Completions and Messages routes. +//! +//! The Original's Python server takes every sampling field from the top level of the request body +//! (`StrataEngine.sampling_keys`): `temperature`, `top_p`, `top_k`, `min_p`, `repetition_penalty`, +//! `frequency_penalty`, `presence_penalty`, `penalty_last_n`, `seed`, plus the engine knobs +//! `strata_tune` and `experimental_speed_projection`, and `reasoning_budget_tokens`. This module +//! validates them against the Original's defaults and ranges (`leleka-sampler-ref`) and turns them +//! into the `GEN` request. Chat and Messages forward those keys verbatim into the native Responses +//! request, so one type validates everything. + +use leleka_sampler_ref::RequestSampling; +use serde::Deserialize; +use serde_json::{Map, Value}; + +use crate::wire::EngineTune; + +/// Top-level body keys that the Chat and Messages adapters pass through to the native request +/// unchanged. Removed before their own `deny_unknown_fields` parse. +pub const EXTENSION_KEYS: [&str; 10] = [ + "top_k", + "min_p", + "repetition_penalty", + "frequency_penalty", + "presence_penalty", + "penalty_last_n", + "seed", + "strata_tune", + "experimental_speed_projection", + "reasoning_budget_tokens", +]; + +/// Split an adapter request body into `(rest, extensions)`. +pub fn split_extensions(mut body: Value) -> (Value, Map) { + let mut extensions = Map::new(); + if let Some(object) = body.as_object_mut() { + for key in EXTENSION_KEYS { + if let Some(value) = object.remove(key) { + extensions.insert(key.to_owned(), value); + } + } + } + (body, extensions) +} + +/// `strata_tune`: engine settings for this request only (setup's calibration). +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Tune { + pub pcie_frac: Option, + pub spec_min_p: Option, +} + +impl From for EngineTune { + fn from(tune: Tune) -> Self { + Self { + pcie_frac: tune.pcie_frac, + spec_min_p: tune.spec_min_p, + } + } +} + +pub fn validate_tune(tune: &Tune) -> Result<(), (&'static str, &'static str)> { + for (name, value) in [ + ("pcie_frac", tune.pcie_frac), + ("spec_min_p", tune.spec_min_p), + ] { + if value.is_some_and(|v| !v.is_finite() || !(0.0..=1.0).contains(&v)) { + return Err(( + "strata_tune", + if name == "pcie_frac" { + "strata_tune.pcie_frac must be between 0 and 1" + } else { + "strata_tune.spec_min_p must be between 0 and 1" + }, + )); + } + } + Ok(()) +} + +/// Validate request sampling against the Original's contract; the message is static so it can +/// travel in the Responses `(param, message)` error pair. +pub fn validate(sampling: &RequestSampling) -> Result<(), (&'static str, &'static str)> { + sampling.validate().map_err(|error| match error.field { + "temperature" => ("temperature", "temperature must be between 0 and 2"), + "top_p" => ("top_p", "top_p must be between 0 and 1"), + "min_p" => ("min_p", "min_p must be between 0 and 1"), + "top_k" => ( + "top_k", + "top_k must be an integer >= 0 (0 or above 64 use 64)", + ), + "repetition_penalty" => ( + "repetition_penalty", + "repetition_penalty must be greater than 0 (1 is off)", + ), + "frequency_penalty" => ( + "frequency_penalty", + "frequency_penalty must be between -2 and 2", + ), + "presence_penalty" => ( + "presence_penalty", + "presence_penalty must be between -2 and 2", + ), + "penalty_last_n" => ( + "penalty_last_n", + "penalty_last_n must be an integer between 0 and 2147483647", + ), + _ => ("sampling", "sampling parameters are out of range"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn extensions_are_split_out_of_adapter_bodies() { + let (rest, extensions) = split_extensions(json!({ + "model": "m", "temperature": 0.5, "top_k": 40, "seed": 3, "min_p": null, + "strata_tune": {"pcie_frac": 0.1} + })); + assert_eq!(rest, json!({"model": "m", "temperature": 0.5})); + assert_eq!(extensions.len(), 4); + assert_eq!(extensions["top_k"], 40); + assert!(extensions["min_p"].is_null()); + let (same, none) = split_extensions(json!([1, 2])); + assert_eq!(same, json!([1, 2])); + assert!(none.is_empty()); + } + + #[test] + fn every_sampling_field_has_its_own_error() { + for (bad, field) in [ + ( + RequestSampling { + temperature: Some(3.0), + ..Default::default() + }, + "temperature", + ), + ( + RequestSampling { + top_p: Some(-0.1), + ..Default::default() + }, + "top_p", + ), + ( + RequestSampling { + min_p: Some(1.5), + ..Default::default() + }, + "min_p", + ), + ( + RequestSampling { + top_k: Some(-1), + ..Default::default() + }, + "top_k", + ), + ( + RequestSampling { + repetition_penalty: Some(0.0), + ..Default::default() + }, + "repetition_penalty", + ), + ( + RequestSampling { + frequency_penalty: Some(2.5), + ..Default::default() + }, + "frequency_penalty", + ), + ( + RequestSampling { + presence_penalty: Some(-2.5), + ..Default::default() + }, + "presence_penalty", + ), + ( + RequestSampling { + penalty_last_n: Some(-1), + ..Default::default() + }, + "penalty_last_n", + ), + ] { + assert_eq!(validate(&bad).unwrap_err().0, field); + } + assert!(validate(&RequestSampling::default()).is_ok()); + } + + #[test] + fn tune_is_bounded_and_strict() { + assert!(validate_tune(&Tune::default()).is_ok()); + assert!( + validate_tune(&Tune { + pcie_frac: Some(1.1), + spec_min_p: None + }) + .is_err() + ); + assert!( + validate_tune(&Tune { + pcie_frac: None, + spec_min_p: Some(-0.1) + }) + .is_err() + ); + assert!(serde_json::from_value::(json!({"pcie_frac": 0.5, "x": 1})).is_err()); + } +} diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs new file mode 100644 index 00000000..2214e2e3 --- /dev/null +++ b/control-plane/src/server_api.rs @@ -0,0 +1,542 @@ +//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`) +//! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`, +//! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and +//! the own-page guard. Behaviour is checked against the real Python handlers in +//! `tests/http_surface.rs` (fixtures from `tests/golden/gen_goldens.py http`). +//! +//! One engine at a time: `total_slots` is 1 and `/slots` lists one slot while the engine is loaded. + +use std::{ + sync::Arc, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use axum::{ + Json, + body::Bytes, + extract::{Request, State}, + http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use leleka_serving_policy::{ + cors::{Cors, own_page}, + idle::Outcome, +}; +use serde_json::{Value, json}; +use tokio::sync::{mpsc, oneshot}; + +use crate::{ + app::AppState, + worker::{Control, LoadError, WorkerState, WorkerStatus}, +}; + +/// The chat template the Original serves in `/props` when the model ships none. +pub const DEFAULT_CHAT_TEMPLATE: &str = + include_str!("../../engine/strata/serve/chat_template.jinja"); + +fn error_body(kind: Option<&str>, message: &str) -> Value { + match kind { + Some(kind) => json!({"error": {"type": kind, "message": message}}), + None => json!({"error": {"message": message}}), + } +} + +fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +fn now_s() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers.get(name).and_then(|v| v.to_str().ok()) +} + +fn is_loaded(worker: &WorkerStatus) -> bool { + worker.state == WorkerState::Ready +} + +/// Whether a request is running or waiting for the engine. +fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool { + worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0 +} + +fn context_of(worker: &WorkerStatus) -> usize { + worker.max_context.or(worker.known_max_context).unwrap_or(0) +} + +// ------------------------------------------------------------------------------------------------ loading + +/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every +/// request). Stamps the activity time so the idle timer does not unload between this and the +/// request's own start. `Err` is a ready-made error response. +pub async fn ensure_loaded(state: &AppState) -> Result<(), Box> { + let unloaded = { + let mut worker = state.worker.write().await; + worker.last_activity = Some(tokio::time::Instant::now()); + worker.state == WorkerState::Unloaded + }; + if !unloaded { + return Ok(()); + } + match load(state).await { + Ok(()) => Ok(()), + Err(error) => Err(Box::new(load_error_response(&error))), + } +} + +/// Ask the supervisor to load and wait until it is ready. +pub async fn load(state: &AppState) -> Result<(), LoadError> { + let Some(control) = &state.control else { + return Err(LoadError::Failed( + "the engine cannot be loaded on demand".into(), + )); + }; + let (answer, received) = oneshot::channel(); + control + .send(Control::Load { reply: answer }) + .await + .map_err(|_| LoadError::Failed("the server is shutting down".into()))?; + received + .await + .map_err(|_| LoadError::Failed("the server is shutting down".into()))? +} + +/// `POST /unload`'s core (also the idle thread): the outcome string of the Original. +pub async fn unload(state: &AppState, idle_for: Option) -> Outcome { + let Some(control) = &state.control else { + return Outcome::Unsupported; + }; + { + let worker = state.worker.read().await; + if is_loaded(&worker) && is_busy(state, &worker) { + return Outcome::Busy; + } + } + let (answer, received) = oneshot::channel(); + if control + .send(Control::Unload { + idle_for, + reply: answer, + }) + .await + .is_err() + { + return Outcome::NotLoaded; + } + received.await.unwrap_or(Outcome::NotLoaded) +} + +fn load_error_response(error: &LoadError) -> Response { + let message = match error { + LoadError::GpuBusy(m) | LoadError::Failed(m) => m, + }; + api_server_error(message) +} + +fn api_server_error(message: &str) -> Response { + reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(Some("server_error"), message), + ) +} + +/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran +/// within `idle`. Returns when the control channel closes. +pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) { + loop { + tokio::time::sleep(poll).await; + if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) { + return; + } + let outcome = unload(&state, Some(idle)).await; + if outcome == Outcome::Unloaded { + eprintln!( + "model unloaded after {:.0} s idle; the next request loads it again", + idle.as_secs_f64() + ); + } + } +} + +// ------------------------------------------------------------------------------------------------ handlers + +/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded. +pub async fn api_health(State(state): State) -> Response { + let worker = *state.worker.read().await; + reply( + StatusCode::OK, + json!({"status": "ok", "max_context": context_of(&worker), "model": state.model, + "images": false, "api_key": state.api_key.is_some(), + "loaded": is_loaded(&worker), "service": "strata"}), + ) +} + +fn model_names(state: &AppState) -> Vec { + state + .model + .iter() + .cloned() + .chain(state.aliases.iter().cloned()) + .collect() +} + +/// The first non-blank value of `name` (Python's `parse_qs` drops blank values). +fn query_param(query: Option<&str>, name: &str) -> Option { + query?.split('&').find_map(|pair| { + let (key, value) = pair.split_once('=')?; + (percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value)) + }) +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + match std::str::from_utf8(&bytes[i + 1..i + 3]) + .ok() + .and_then(|hex| u8::from_str_radix(hex, 16).ok()) + { + Some(byte) => { + out.push(byte); + i += 2; + } + None => out.push(b'%'), + } + } + byte => out.push(byte), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// `GET /props` (llama-server compatible): the default generation settings, the chat template and +/// what this server can do. +pub async fn props(State(state): State, request: Request) -> Response { + let asked = query_param(request.uri().query(), "model") + .or_else(|| state.model.clone()) + .unwrap_or_default(); + if !model_names(&state).contains(&asked) { + return reply(StatusCode::NOT_FOUND, error_body(None, "model not found")); + } + let worker = *state.worker.read().await; + if !is_loaded(&worker) && worker.state != WorkerState::Unloaded { + return reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(None, "the engine is not running"), + ); + } + let merged = state.settings.merged(); + let shared = state.settings.shared(); + reply( + StatusCode::OK, + json!({ + "default_generation_settings": { + "n_ctx": context_of(&worker), + "params": merged.props_params(&shared), + }, + "total_slots": 1, + "model_alias": state.model, + "chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE), + "modalities": {"vision": false}, + "models_autoload": state.control.is_some(), + "is_sleeping": !is_loaded(&worker), + "build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")), + }), + ) +} + +/// `GET /slots`: one slot while the engine is loaded, none otherwise. +pub async fn slots(State(state): State) -> Response { + let worker = *state.worker.read().await; + if !is_loaded(&worker) { + return reply(StatusCode::OK, json!([])); + } + reply( + StatusCode::OK, + json!([{"id": 0, "n_ctx": context_of(&worker), + "is_processing": is_busy(&state, &worker)}]), + ) +} + +/// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess. +pub async fn v1_status(State(state): State) -> Response { + reply(StatusCode::OK, status_value(&state).await) +} + +async fn status_value(state: &AppState) -> Value { + let worker = *state.worker.read().await; + let lifecycle = state.lifecycle.snapshot(); + let busy = worker.metrics.active_since.is_some(); + let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy)); + let context = context_of(&worker); + let last_at = worker + .last_activity + .map(|at| now_s().saturating_sub(at.elapsed().as_secs())); + let started = state + .started_at + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let timings = worker.metrics.last_done.map(|done| { + let mut value = leleka_serving_policy::timings::request_timings( + &leleka_serving_policy::timings::Last { + prompt_tokens: done.prompt_tokens, + generated: done.generated_tokens, + prompt_ms: done.prefill_ms, + decode_ms: done.decode_ms, + reused: done.reused_tokens, + drafts_offered: done.drafts_offered, + drafts_accepted: done.drafts_accepted, + }, + done.generated_tokens, + ); + value["at"] = json!(now_s()); + value + }); + json!({ + "service": "strata", "model": state.model, + "loaded": is_loaded(&worker), "auto_load": state.control.is_some(), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": false, "stream_buffered": true}, + "engine": env!("CARGO_PKG_VERSION"), + "started": started, + "uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()), + "cache_max_tokens": context, + "context": {"native": context, "max_positions": context}, + "concurrency": {"serving": 1, "requested": 1}, + "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], + "vision": {"enabled": false, "available": false, "error": null}, + "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, + "last_request_at": last_at}, + "last_timings": timings, + "machine": {"at": now_s(), "gpu": null, "ram": null}, + }) +} + +/// `GET /settings`. +pub async fn settings_get(State(state): State) -> Response { + let shared = state.settings.shared(); + reply( + StatusCode::OK, + json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), + ) +} + +fn own_page_check(state: &AppState, headers: &HeaderMap, what: &str) -> Result<(), Box> { + own_page( + what, + header_str(headers, "content-type"), + header_str(headers, "origin"), + header_str(headers, "host"), + &state.trusted_origins, + ) + .map_err(|e| { + Box::new(reply( + StatusCode::from_u16(e.status()).unwrap_or(StatusCode::FORBIDDEN), + error_body(None, &e.message()), + )) + }) +} + +/// `POST /settings`: replace the Chat settings every client gets for what it leaves out. They change +/// what every client gets, so only the app's own page may set them. +pub async fn settings_post( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + if let Err(response) = own_page_check(&state, &headers, "settings can be changed") { + return *response; + } + let value: Value = if body.is_empty() { + json!({}) + } else { + match serde_json::from_slice(&body) { + Ok(value) => value, + Err(error) => { + return reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &error.to_string()), + ); + } + } + }; + let defaults = value.get("defaults").cloned().unwrap_or(Value::Null); + match state.settings.set_shared(&defaults) { + Ok(shared) => { + if shared.is_empty() { + eprintln!("other apps use their own settings again"); + } else { + eprintln!("other apps now use the Chat settings: {}", shared.to_json()); + } + reply( + StatusCode::OK, + json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), + ) + } + Err(message) => reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &message), + ), + } +} + +/// `POST /unload`: give the GPU back now (between requests). +pub async fn unload_post(State(state): State) -> Response { + let outcome = unload(&state, None).await; + reply( + if outcome == Outcome::Busy { + StatusCode::CONFLICT + } else { + StatusCode::OK + }, + json!({"status": outcome.as_str()}), + ) +} + +/// `POST /load`: load now, e.g. ahead of a request. +pub async fn load_post(State(state): State) -> Response { + state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); + if state.worker.read().await.state == WorkerState::Ready { + return reply(StatusCode::OK, json!({"status": "loaded"})); + } + match load(&state).await { + Ok(()) => reply(StatusCode::OK, json!({"status": "loaded"})), + Err(error) => load_error_response(&error), + } +} + +/// The shared prelude of `POST /v1/load` and `/v1/unload`: a JSON object body, own page only, and +/// the right model. +fn model_control_prelude( + state: &AppState, + headers: &HeaderMap, + body: &Bytes, +) -> Result<(), Box> { + let value: Value = if body.is_empty() { + json!({}) + } else { + serde_json::from_slice(body).map_err(|error| { + Box::new(reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &error.to_string()), + )) + })? + }; + let Some(object) = value.as_object() else { + return Err(Box::new(reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), "send a JSON object"), + ))); + }; + own_page_check(state, headers, "the model can be loaded or unloaded")?; + match object.get("model") { + None | Some(Value::Null) => {} + Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {} + Some(_) => { + return Err(Box::new(reply( + StatusCode::NOT_FOUND, + error_body(None, "model not found"), + ))); + } + } + Ok(()) +} + +fn model_busy() -> Response { + reply( + StatusCode::CONFLICT, + error_body(Some("model_busy"), "a request is running or queued"), + ) +} + +pub async fn v1_unload(State(state): State, headers: HeaderMap, body: Bytes) -> Response { + if let Err(response) = model_control_prelude(&state, &headers, &body) { + return *response; + } + let outcome = unload(&state, None).await; + if outcome == Outcome::Busy { + return model_busy(); + } + let mut value = status_value(&state).await; + value["status"] = json!(outcome.as_str()); + reply(StatusCode::OK, value) +} + +pub async fn v1_load(State(state): State, headers: HeaderMap, body: Bytes) -> Response { + if let Err(response) = model_control_prelude(&state, &headers, &body) { + return *response; + } + { + let worker = state.worker.read().await; + if is_busy(&state, &worker) { + return model_busy(); + } + } + state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); + if state.worker.read().await.state != WorkerState::Ready + && let Err(error) = load(&state).await + { + return load_error_response(&error); + } + let mut value = status_value(&state).await; + value["status"] = json!("loaded"); + reply(StatusCode::OK, value) +} + +/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`. +pub async fn not_found() -> Response { + reply(StatusCode::NOT_FOUND, error_body(None, "not found")) +} + +// ------------------------------------------------------------------------------------------------ CORS + +/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's +/// credential-less `OPTIONS` is answered before authentication, as the Original does. +pub async fn cors_layer(State(cors): State>, request: Request, next: Next) -> Response { + let target = request.uri().path_and_query().map_or_else( + || request.uri().path().to_owned(), + |p| p.as_str().to_owned(), + ); + let headers = cors.headers( + &target, + header_str(request.headers(), "origin"), + header_str(request.headers(), "access-control-request-headers"), + ); + let mut response = if request.method() == Method::OPTIONS { + let mut response = StatusCode::NO_CONTENT.into_response(); + response + .headers_mut() + .insert(header::CONTENT_LENGTH, HeaderValue::from_static("0")); + response + } else { + next.run(request).await + }; + for (name, value) in headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::from_bytes(name.as_bytes()), + HeaderValue::from_str(&value), + ) { + response.headers_mut().insert(name, value); + } + } + response +} + +/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none). +pub async fn mcp_status(State(state): State) -> Response { + let body = match &state.mcp { + Some(hub) => hub.status().await, + None => json!({"servers": [], "tools": 0}), + }; + reply(StatusCode::OK, body) +} diff --git a/control-plane/src/settings.rs b/control-plane/src/settings.rs new file mode 100644 index 00000000..89f37700 --- /dev/null +++ b/control-plane/src/settings.rs @@ -0,0 +1,179 @@ +//! Server-wide sampling defaults: the run config's `sampling` block and the Chat settings every +//! client shares (`POST /settings`), kept next to the config between starts. Port of the +//! settings half of `serve/server.py` `Service` (`set_shared`, `with_shared`, the default merge in +//! `run`). The pure rules live in `leleka-serving-policy`. + +use std::{ + fs, + path::{Path, PathBuf}, + sync::RwLock, +}; + +use leleka_serving_policy::shared::{ + ConfigSampling, MergedDefaults, SharedDefaults, clean_shared_defaults, merged_defaults, +}; +use serde_json::Value; + +#[derive(Default)] +pub struct Settings { + config: ConfigSampling, + shared: RwLock, + shared_path: Option, + /// The config's `reasoning_budget_tokens` (raw, validated at startup). + reasoning_budget_default: Option, +} + +impl Settings { + pub fn new(config: ConfigSampling) -> Self { + Self { + config, + ..Default::default() + } + } + + pub fn with_reasoning_budget(mut self, default: Option) -> Self { + self.reasoning_budget_default = default; + self + } + + /// Persist shared settings in `path` and load what a previous run left there. A missing, + /// unreadable or invalid file means "clients use their own settings" (as in the Original). + pub fn with_shared_file(mut self, path: PathBuf) -> Self { + let loaded = fs::read_to_string(&path) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|value| clean_shared_defaults(&value).ok()) + .unwrap_or_default(); + *self.shared.write().expect("settings lock") = loaded; + self.shared_path = Some(path); + self + } + + pub fn shared(&self) -> SharedDefaults { + self.shared.read().expect("settings lock").clone() + } + + pub fn config(&self) -> &ConfigSampling { + &self.config + } + + pub fn reasoning_budget_default(&self) -> Option<&Value> { + self.reasoning_budget_default.as_ref() + } + + /// `{**config sampling, **shared}`. + pub fn merged(&self) -> MergedDefaults { + merged_defaults(&self.config, &self.shared()) + } + + /// `POST /settings`: validate, replace and persist. `Err` is the 400 message. + pub fn set_shared(&self, defaults: &Value) -> Result { + let cleaned = clean_shared_defaults(defaults)?; + *self.shared.write().expect("settings lock") = cleaned.clone(); + if let Some(path) = &self.shared_path + && let Err(error) = persist(path, &cleaned) + { + eprintln!("could not save the shared settings: {error}"); + } + Ok(cleaned) + } +} + +fn persist(path: &Path, shared: &SharedDefaults) -> std::io::Result<()> { + if shared.is_empty() { + match fs::remove_file(path) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error), + _ => Ok(()), + } + } else { + // Written next to the destination and renamed, so a crash never leaves half a file. + let temporary = path.with_extension("tmp"); + fs::write(&temporary, serde_json::to_string_pretty(&shared.to_json())?)?; + fs::rename(&temporary, path) + } +} + +/// The shared-settings file the Original keeps next to its config: `.shared-settings.json`. +pub fn default_shared_path(config: &Path) -> PathBuf { + let mut name = config.with_extension("").into_os_string(); + name.push(".shared-settings.json"); + PathBuf::from(name) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn temp(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("strata-settings-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn shared_settings_persist_across_starts_and_empty_removes_the_file() { + let dir = temp("persist"); + let path = dir.join("strata.shared-settings.json"); + let first = Settings::default().with_shared_file(path.clone()); + assert!(first.shared().is_empty()); + first + .set_shared(&json!({"temperature": 0.5, "max_tokens": 128})) + .unwrap(); + assert!(path.exists()); + let second = Settings::default().with_shared_file(path.clone()); + assert_eq!(second.shared().temperature, Some(0.5)); + assert_eq!(second.shared().max_tokens, Some(128)); + second.set_shared(&json!({})).unwrap(); + assert!(!path.exists()); + assert!( + Settings::default() + .with_shared_file(path) + .shared() + .is_empty() + ); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_corrupt_file_means_no_shared_settings() { + let dir = temp("corrupt"); + let path = dir.join("s.json"); + fs::write(&path, "{not json").unwrap(); + assert!( + Settings::default() + .with_shared_file(path.clone()) + .shared() + .is_empty() + ); + fs::write(&path, r#"{"temperature": 9}"#).unwrap(); + assert!( + Settings::default() + .with_shared_file(path) + .shared() + .is_empty() + ); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_rejected_update_keeps_the_previous_settings() { + let settings = Settings::default(); + settings.set_shared(&json!({"top_k": 10})).unwrap(); + assert_eq!( + settings.set_shared(&json!({"top_k": 100})).unwrap_err(), + "top_k: an integer 1..64" + ); + assert_eq!(settings.shared().top_k, Some(10)); + } + + #[test] + fn default_path_sits_next_to_the_config() { + assert_eq!( + default_shared_path(Path::new("/etc/strata/run.json")), + PathBuf::from("/etc/strata/run.shared-settings.json") + ); + } +} diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index c49b696b..3dd1afe5 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -1,36 +1,115 @@ //! Typed boundary for the resident Strata `--serve` stdin/stdout protocol. -#[derive(Debug, Clone, PartialEq)] +use leleka_sampler_ref::RequestSampling; + +/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of +/// missed experts and the draft-probability floor, both in `0..=1`. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct EngineTune { + pub pcie_frac: Option, + pub spec_min_p: Option, +} + +/// Reasoning-budget wrap-up (`reasoning_budget_tokens`, issue #123 of the Original): once the model +/// has thought for `budget` tokens, at a clean point the worker stops the pass, appends `wrap_up` +/// to the output and continues from `prompt + generated + wrap_up` so the engine keeps its prefix. +#[derive(Clone)] +pub struct ReasoningPlan { + pub budget: u64, + /// Token ids of `REASONING_WRAP_UP`. + pub wrap_up: Vec, + /// End-of-turn ids: they end the generation and are never counted as thinking. + pub stop_ids: Vec, + /// The bytes one token decodes to. + pub token_bytes: std::sync::Arc Vec + Send + Sync>, +} + +impl std::fmt::Debug for ReasoningPlan { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ReasoningPlan") + .field("budget", &self.budget) + .field("wrap_up", &self.wrap_up) + .finish_non_exhaustive() + } +} + +impl PartialEq for ReasoningPlan { + fn eq(&self, other: &Self) -> bool { + self.budget == other.budget + && self.wrap_up == other.wrap_up + && self.stop_ids == other.stop_ids + } +} + +/// One `GEN` / `GENI` request. Every sampling key the Original's `--serve` loop +/// accepts is carried: `temperature`, `top_p`, `top_k`, `min_p`, the three penalties +/// with `penalty_last_n`, and `seed` (through [`RequestSampling::gen_keys`], which is +/// golden-tested against `StrataEngine.sampling_keys`), plus `strata_tune` +/// (`pcie_frac`, `spec_min_p`) and the per-request control-vector switch `cvec`. +#[derive(Debug, Clone, Default, PartialEq)] pub struct Generate { pub token_ids: Vec, pub max_new: u32, - pub temperature: Option, - pub top_p: Option, + pub sampling: RequestSampling, + pub tune: Option, + /// `experimental_speed_projection`: `Some(b)` emits `cvec=0|1`, `None` leaves the + /// engine default (on when a vector is loaded). + pub cvec: Option, + /// `GENI`: path of the SVE1 image-embeddings file for this request. + pub embeddings: Option, + /// Reasoning-budget wrap-up, executed by the worker; never sent to the engine. + pub reasoning: Option, } impl Generate { + /// The tuning and projection keys after the sampling keys, in the Python order. + fn engine_keys(&self) -> Result { + let mut keys = String::new(); + if let Some(tune) = &self.tune { + for (name, value) in [ + ("pcie_frac", tune.pcie_frac), + ("spec_min_p", tune.spec_min_p), + ] { + if let Some(value) = value { + if !value.is_finite() || !(0.0..=1.0).contains(&value) { + return Err("strata_tune values must be finite and between 0 and 1"); + } + keys.push_str(&format!( + " {name}={}", + leleka_sampler_ref::params::py_float_repr(value) + )); + } + } + } + if let Some(on) = self.cvec { + keys.push_str(&format!(" cvec={}", u8::from(on))); + } + Ok(keys) + } + pub fn line(&self) -> Result { if self.token_ids.is_empty() || self.max_new == 0 { return Err("GEN needs prompt tokens and a positive max_new"); } - if self - .temperature - .is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value)) - { - return Err("temperature must be finite and between 0 and 2"); + // The engine reads the first whitespace-delimited token without `=` as the path. + if self.embeddings.as_ref().is_some_and(|path| { + path.is_empty() || path.contains(|c: char| c.is_whitespace() || c == '=') + }) { + return Err("GENI embeddings path must be nonempty, without whitespace or '='"); } - if self - .top_p - .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) - { - return Err("top_p must be finite and between 0 and 1"); - } - let mut line = format!("GEN {}", self.max_new); - if let Some(value) = self.temperature.filter(|value| *value > 0.0) { - line.push_str(&format!(" temperature={value}")); - } - if let Some(value) = self.top_p.filter(|value| *value < 1.0) { - line.push_str(&format!(" top_p={value}")); + let keys = self + .sampling + .gen_keys() + .map_err(|_| "sampling parameters are out of range")?; + let mut line = match &self.embeddings { + Some(_) => format!("GENI {}", self.max_new), + None => format!("GEN {}", self.max_new), + }; + line.push_str(&keys); + line.push_str(&self.engine_keys()?); + if let Some(path) = &self.embeddings { + line.push(' '); + line.push_str(path); } line.push(' '); for (index, id) in self.token_ids.iter().enumerate() { @@ -174,8 +253,12 @@ mod tests { let request = Generate { token_ids: vec![101, 42, 7], max_new: 256, - temperature: Some(0.7), - top_p: Some(0.9), + sampling: RequestSampling { + temperature: Some(0.7), + top_p: Some(0.9), + ..Default::default() + }, + ..Default::default() }; assert_eq!( request.line().unwrap(), @@ -191,6 +274,120 @@ mod tests { ); } + fn sampling_of(v: &serde_json::Value) -> RequestSampling { + let f = |k: &str| v.get(k).and_then(serde_json::Value::as_f64); + let i = |k: &str| v.get(k).and_then(serde_json::Value::as_i64); + RequestSampling { + temperature: f("temperature"), + top_p: f("top_p"), + top_k: i("top_k"), + min_p: f("min_p"), + repetition_penalty: f("repetition_penalty"), + frequency_penalty: f("frequency_penalty"), + presence_penalty: f("presence_penalty"), + penalty_last_n: i("penalty_last_n"), + seed: v.get("seed").and_then(serde_json::Value::as_u64), + } + } + + /// Every GEN/GENI line equals what the Original's `StrataEngine.generate` writes to the pipe + /// (fixture from `tests/golden/gen_goldens.py`, which runs that real code with a fake pipe). + #[test] + fn gen_lines_equal_the_python_servers_for_every_sampling_key() { + let fixture: serde_json::Value = + serde_json::from_str(include_str!("../tests/fixtures/golden/gen_lines.json")).unwrap(); + let cases = fixture["cases"].as_array().unwrap(); + assert!(cases.len() >= 60); + for case in cases { + let sampling = &case["sampling"]; + let tune = sampling.get("strata_tune").map(|t| EngineTune { + pcie_frac: t.get("pcie_frac").and_then(serde_json::Value::as_f64), + spec_min_p: t.get("spec_min_p").and_then(serde_json::Value::as_f64), + }); + let request = Generate { + token_ids: case["token_ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as u32) + .collect(), + max_new: case["max_new"].as_u64().unwrap() as u32, + sampling: sampling_of(sampling), + tune, + cvec: sampling + .get("experimental_speed_projection") + .and_then(serde_json::Value::as_bool), + embeddings: case["embeddings"].as_str().map(str::to_owned), + reasoning: None, + }; + assert_eq!( + request.line().unwrap(), + case["line"].as_str().unwrap(), + "case {case}" + ); + } + } + + #[test] + fn out_of_contract_generate_fields_are_refused_before_the_pipe() { + let base = Generate { + token_ids: vec![1], + max_new: 1, + ..Default::default() + }; + for bad in [ + RequestSampling { + temperature: Some(2.5), + ..Default::default() + }, + RequestSampling { + top_p: Some(1.5), + ..Default::default() + }, + RequestSampling { + top_k: Some(-1), + ..Default::default() + }, + RequestSampling { + repetition_penalty: Some(0.0), + ..Default::default() + }, + RequestSampling { + presence_penalty: Some(f64::NAN), + ..Default::default() + }, + ] { + let request = Generate { + sampling: bad, + ..base.clone() + }; + assert!(request.line().is_err(), "{request:?}"); + } + for tune in [ + EngineTune { + pcie_frac: Some(1.5), + spec_min_p: None, + }, + EngineTune { + pcie_frac: None, + spec_min_p: Some(f64::NAN), + }, + ] { + let request = Generate { + tune: Some(tune), + ..base.clone() + }; + assert!(request.line().is_err()); + } + for path in ["", "a b", "a=b", "a\nb"] { + let request = Generate { + embeddings: Some(path.into()), + ..base.clone() + }; + assert!(request.line().is_err(), "{path:?}"); + } + } + #[test] fn parses_current_and_older_done_lines() { let current = parse_line("DONE 12 300 45.1 88.2 stop 7 10 240 90 100 2 0 0.0\n") diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index 216a7a00..981d821d 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -8,9 +8,11 @@ use tokio::{ time::timeout, }; -use crate::wire::{self, Event, Generate}; +use crate::wire::{self, Done, Event, Generate}; const STOP_DRAIN_TIMEOUT: Duration = Duration::from_secs(20); +/// Start of the error a stalled request ends with; the client is told, not just disconnected. +const STALL_PREFIX: &str = "engine made no progress"; pub struct GenerationCommand { pub queue: Option, @@ -60,6 +62,9 @@ pub enum WorkerState { Starting, Restarting, Ready, + /// The engine process was stopped on request (`/unload`, idle unload) or never started + /// (`lazy`); the next request or `/load` starts it again. + Unloaded, Stopping, Failed, } @@ -68,6 +73,10 @@ pub enum WorkerState { pub struct WorkerStatus { pub state: WorkerState, pub max_context: Option, + /// The last context the engine reported; kept while unloaded (`/props`, `/slots`). + pub known_max_context: Option, + /// When a request last started or finished, or the engine became ready. + pub last_activity: Option, pub metrics: crate::metrics::GenerationMetrics, } @@ -76,11 +85,22 @@ impl Default for WorkerStatus { Self { state: WorkerState::Unconfigured, max_context: None, + known_max_context: None, + last_activity: None, metrics: Default::default(), } } } +/// How to run the command before a reload. +#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(untagged)] +pub enum BeforeLoad { + /// Run through `sh -c`. + Shell(String), + Argv(Vec), +} + pub struct WorkerConfig { pub cuda_memory: Option, pub executable: OsString, @@ -88,6 +108,53 @@ pub struct WorkerConfig { pub startup_timeout: Duration, pub generation_timeout: Option, pub max_restarts: u32, + /// Start unloaded: the first request (or `POST /load`) starts the engine. + pub lazy: bool, + /// No line from the engine for this long during a request ends it (the stall watchdog seen + /// from outside; see `leleka_serving_policy::watchdog`). `None` = off. + pub stall_timeout: Option, + /// Run before every reload and restart (not the first start): e.g. unload another server's model. + pub before_load: Option, + /// Reload only when this much VRAM is free (MiB); 0 = always. + pub min_free_vram_mib: u64, +} + +impl Default for WorkerConfig { + fn default() -> Self { + Self { + cuda_memory: None, + executable: OsString::new(), + args: Vec::new(), + startup_timeout: Duration::from_secs(600), + generation_timeout: None, + max_restarts: 0, + lazy: false, + stall_timeout: None, + before_load: None, + min_free_vram_mib: 0, + } + } +} + +/// Why a load did not happen. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LoadError { + /// `min_free_vram_mib` is not free: the model stays unloaded until it is. + GpuBusy(String), + Failed(String), +} + +pub type LoadReply = oneshot::Sender>; + +/// Administrative commands to the supervisor. +pub enum Control { + /// `idle_for`: only if no request ran within that long (the idle thread); `None` is `/unload`. + Unload { + idle_for: Option, + reply: oneshot::Sender, + }, + /// Start the engine now if it is unloaded; answers when it is ready. + Load { reply: LoadReply }, } pub async fn run( @@ -101,20 +168,196 @@ pub async fn run( } pub async fn run_with_requests( + config: WorkerConfig, + status: Arc>, + shutdown: watch::Receiver, + requests: mpsc::Receiver, +) { + // The sender stays alive for the duration: with no administrative channel, nothing is ever sent. + let (_idle, control) = mpsc::channel(1); + run_supervised(config, status, shutdown, requests, control).await; +} + +enum Wake { + Shutdown, + Load, + Command(Box), +} + +async fn fail_loads(waiting: &mut Vec, error: &LoadError) { + for reply in waiting.drain(..) { + let _ = reply.send(Err(error.clone())); + } +} + +/// Wait while the engine is unloaded for something that needs it. +async fn wait_unloaded( + shutdown: &mut watch::Receiver, + requests: &mut mpsc::Receiver, + control: &mut mpsc::Receiver, + waiting: &mut Vec, +) -> Wake { + let mut requests_closed = false; + let mut control_closed = false; + loop { + tokio::select! { + biased; + _ = shutdown.changed() => return Wake::Shutdown, + message = control.recv(), if !control_closed => match message { + Some(Control::Load { reply }) => { + waiting.push(reply); + return Wake::Load; + } + Some(Control::Unload { reply, .. }) => { + let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded); + } + None => control_closed = true, + }, + command = requests.recv(), if !requests_closed => match command { + Some(command) => return Wake::Command(Box::new(command)), + None => requests_closed = true, + }, + } + } +} + +/// The checks before an engine is started again (not the first start): the `before_load` command, +/// then the free-VRAM gate. A failing command is logged and the load goes on, as in the Original. +async fn reload_gate(config: &WorkerConfig) -> Result<(), LoadError> { + if let Some(before) = &config.before_load { + eprintln!("before loading: {before:?}"); + let mut command = match before { + BeforeLoad::Shell(line) => { + let mut c = Command::new("sh"); + c.arg("-c").arg(line); + c + } + BeforeLoad::Argv(argv) if !argv.is_empty() => { + let mut c = Command::new(&argv[0]); + c.args(&argv[1..]); + c + } + BeforeLoad::Argv(_) => Command::new("true"), + }; + command.stdin(Stdio::null()).kill_on_drop(true); + match command.spawn() { + Ok(mut child) => match timeout(Duration::from_secs(120), child.wait()).await { + Ok(Ok(_)) => {} + Ok(Err(error)) => { + eprintln!("the before_load command failed ({error}); loading anyway") + } + Err(_) => { + eprintln!("the before_load command timed out; loading anyway"); + let _ = child.kill().await; + } + }, + Err(error) => eprintln!("the before_load command failed ({error}); loading anyway"), + } + } + if config.min_free_vram_mib > 0 { + // Memory another process just gave back can take a moment. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + let mut free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; + while free.is_some_and(|f| f < config.min_free_vram_mib) + && tokio::time::Instant::now() < deadline + { + tokio::time::sleep(Duration::from_millis(500)).await; + free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; + } + if let Some(free) = free.filter(|f| *f < config.min_free_vram_mib) { + return Err(LoadError::GpuBusy(format!( + "the GPU is in use by another program: {free} MiB of VRAM free, the model needs {} (min_free_vram_mib) - it stays unloaded until that is free", + config.min_free_vram_mib + ))); + } + } + Ok(()) +} + +pub async fn run_supervised( config: WorkerConfig, status: Arc>, mut shutdown: watch::Receiver, mut requests: mpsc::Receiver, + mut control: mpsc::Receiver, ) { if config.max_restarts > 3 { eprintln!("worker max_restarts must be between 0 and 3"); update(&status, WorkerState::Failed, None).await; return; } - for attempt in 0..=config.max_restarts { - match run_session(&config, &status, &mut shutdown, &mut requests).await { - SessionExit::Stopped | SessionExit::StartupFailed => return, - SessionExit::RuntimeFailed if attempt == config.max_restarts => return, + // A lazy engine has not reported its context yet: `--max-context N` says what it will be. + if let Some(configured) = config + .args + .windows(2) + .find(|pair| pair[0] == "--max-context") + .and_then(|pair| pair[1].parse::().ok()) + .filter(|context| *context > 0) + { + status.write().await.known_max_context = Some(configured); + } + let mut waiting: Vec = Vec::new(); + let mut inbox: Option = None; + let mut unloaded = config.lazy; + let mut started_before = false; + let mut attempt: u32 = 0; + loop { + if unloaded { + update(&status, WorkerState::Unloaded, None).await; + match wait_unloaded(&mut shutdown, &mut requests, &mut control, &mut waiting).await { + Wake::Shutdown => { + update(&status, WorkerState::Stopping, None).await; + return; + } + Wake::Load => {} + Wake::Command(command) => inbox = Some(*command), + } + unloaded = false; + attempt = 0; + } + if (started_before || config.lazy) + && let Err(error) = reload_gate(&config).await + { + let message = match &error { + LoadError::GpuBusy(m) | LoadError::Failed(m) => m.clone(), + }; + eprintln!("{message}"); + fail_loads(&mut waiting, &error).await; + if let Some(command) = inbox.take() { + send_failure(command.result, message).await; + } + unloaded = true; + continue; + } + started_before = true; + match run_session( + &config, + &status, + &mut shutdown, + &mut requests, + &mut control, + &mut inbox, + &mut waiting, + ) + .await + { + SessionExit::Stopped => return, + SessionExit::StartupFailed => { + fail_loads( + &mut waiting, + &LoadError::Failed("the engine failed to start".into()), + ) + .await; + return; + } + SessionExit::Unloaded => { + unloaded = true; + continue; + } + SessionExit::RuntimeFailed if attempt == config.max_restarts => { + fail_loads(&mut waiting, &LoadError::Failed("the engine failed".into())).await; + return; + } SessionExit::RuntimeFailed => {} } update(&status, WorkerState::Restarting, None).await; @@ -125,6 +368,7 @@ pub async fn run_with_requests( config.max_restarts, delay.as_secs() ); + attempt += 1; while let Ok(command) = requests.try_recv() { send_failure( command.result, @@ -159,6 +403,7 @@ enum SessionExit { Stopped, StartupFailed, RuntimeFailed, + Unloaded, } async fn run_session( @@ -166,6 +411,9 @@ async fn run_session( status: &RwLock, shutdown: &mut watch::Receiver, requests: &mut mpsc::Receiver, + control: &mut mpsc::Receiver, + inbox: &mut Option, + waiting: &mut Vec, ) -> SessionExit { if *shutdown.borrow() { update(status, WorkerState::Stopping, None).await; @@ -209,6 +457,7 @@ async fn run_session( let startup_deadline = tokio::time::sleep(config.startup_timeout); tokio::pin!(startup_deadline); let mut requests_closed = false; + let mut control_closed = false; let max_context = loop { let line = tokio::select! { biased; @@ -223,6 +472,17 @@ async fn run_session( update(status, WorkerState::Failed, None).await; return SessionExit::StartupFailed; } + message = control.recv(), if !control_closed => { + match message { + // A load that arrives while the engine starts is answered at READY. + Some(Control::Load { reply }) => waiting.push(reply), + Some(Control::Unload { reply, .. }) => { + let _ = reply.send(leleka_serving_policy::idle::Outcome::Busy); + } + None => control_closed = true, + } + continue; + } command = requests.recv(), if !requests_closed => { match command { Some(command) => send_failure(command.result, @@ -237,6 +497,10 @@ async fn run_session( Ok(Some(line)) if line.starts_with("READY") => { if let Some(max_context) = parse_ready(&line) { update(status, WorkerState::Ready, Some(max_context)).await; + status.write().await.last_activity = Some(tokio::time::Instant::now()); + for reply in waiting.drain(..) { + let _ = reply.send(Ok(())); + } break max_context; } eprintln!("Strata engine sent an invalid READY line"); @@ -272,18 +536,55 @@ async fn run_session( update(status, WorkerState::Failed, None).await; return SessionExit::RuntimeFailed; }, - command = requests.recv(), if !requests_closed => { + message = control.recv(), if !control_closed => { + match message { + Some(Control::Load { reply }) => { + let _ = reply.send(Ok(())); + } + Some(Control::Unload { idle_for, reply }) => { + let idle_s = status + .read() + .await + .last_activity + .map_or(f64::MAX, |at| at.elapsed().as_secs_f64()); + let outcome = leleka_serving_policy::idle::decide( + leleka_serving_policy::idle::Situation { + supported: true, + loaded: true, + busy: inbox.is_some() || !requests.is_empty(), + idle_s, + }, + idle_for.map(|d| d.as_secs_f64()), + ); + if outcome == leleka_serving_policy::idle::Outcome::Unloaded { + update(status, WorkerState::Unloaded, None).await; + stop(&mut child, &mut stdin).await; + let _ = reply.send(outcome); + return SessionExit::Unloaded; + } + let _ = reply.send(outcome); + } + None => control_closed = true, + } + }, + command = async { + match inbox.take() { + Some(command) => Some(command), + None => requests.recv().await, + } + }, if !requests_closed => { match command { Some(mut command) => { if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) { continue; } + status.write().await.last_activity = Some(tokio::time::Instant::now()); // Retain the command activity until protocol cleanup, // including STOP/QUIT and failed-process termination. let _activity = command.activity.take(); tokio::select! { (timed_out, result) = async { - let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status); + let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status, config.stall_timeout); match config.generation_timeout { Some(duration) => match timeout(duration, generation).await { Ok(result) => (false, result), @@ -299,11 +600,12 @@ async fn run_session( // A full streaming channel must not delay process cleanup // or finite restart indefinitely. Closing it also signals // failure to the response adapter once buffered tokens drain. - if timed_out { + if timed_out || error.starts_with(STALL_PREFIX) { let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await; } return SessionExit::RuntimeFailed; } + status.write().await.last_activity = Some(tokio::time::Instant::now()); } _ = shutdown.changed() => { update(status, WorkerState::Stopping, None).await; @@ -319,12 +621,48 @@ async fn run_session( } } +/// Add up one pass's `DONE` counters (reasoning-budget passes report separately). +fn add_opt(total: Option, part: Option) -> Option { + match (total, part) { + (None, None) => None, + (a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))), + } +} + +/// What the client sees after a budget wrap-up: one `DONE` for the whole request. +fn combine_done(first: &Done, passes: &[Done], generated: u64, finish: wire::Finish) -> Done { + let mut done = Done { + generated, + prompt_tokens: first.prompt_tokens, + prompt_ms: 0.0, + decode_ms: 0.0, + finish, + drafts_accepted: None, + drafts_offered: None, + // Only what the caller's own prompt reused: the tokens of the first pass's prefix, not the + // generated text the second pass re-reads from the engine's own cache. + reused: first.reused, + expert_hits: None, + expert_lookups: None, + }; + for pass in passes { + done.prompt_ms += pass.prompt_ms; + done.decode_ms += pass.decode_ms; + done.drafts_accepted = add_opt(done.drafts_accepted, pass.drafts_accepted); + done.drafts_offered = add_opt(done.drafts_offered, pass.drafts_offered); + done.expert_hits = add_opt(done.expert_hits, pass.expert_hits); + done.expert_lookups = add_opt(done.expert_lookups, pass.expert_lookups); + } + done +} + async fn generate( stdin: &mut Option, lines: &mut tokio::io::Lines>, command: &mut GenerationCommand, max_context: usize, status: &RwLock, + stall_timeout: Option, ) -> Result<(), String> { if command.result.is_closed() { return Ok(()); @@ -359,58 +697,204 @@ async fn generate( let mut stopped = false; let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT); tokio::pin!(stop_deadline); + + // Reasoning budget (issue #123): the thinking is wrapped up at the budget and generation goes on. + let mut budget = command.request.reasoning.clone().map(|plan| { + ( + leleka_serving_policy::reasoning::BudgetTracker::new(plan.budget), + plan, + ) + }); + let budgeted = budget.is_some(); + let mut generated: u64 = 0; // tokens delivered to the client, wrap-up included + let mut segment: Vec = Vec::new(); // this pass's delivered tokens + let mut prompt: Vec = if budgeted { + command.request.token_ids.clone() + } else { + Vec::new() + }; + let mut wrap_pending = false; // a wrap-up STOP is in flight: tokens until its DONE are discarded + let mut passes: Vec = Vec::new(); + let mut first_pass = true; + + // The stall watchdog seen from outside: one poll a second over the engine's lines. + let started = tokio::time::Instant::now(); + let mut lines_read: u64 = 0; + let mut dog = stall_timeout.map(|limit| { + leleka_serving_policy::watchdog::StallWatchdog::new( + i64::try_from(limit.as_secs().max(1)).unwrap_or(i64::MAX), + 0, + leleka_serving_policy::watchdog::Counters { + beats: 0, + busy: true, + ticks: 0, + }, + ) + }); + let mut ticker = tokio::time::interval(Duration::from_secs(1)); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + ticker.reset(); + loop { let line = tokio::select! { biased; - _ = &mut stop_deadline, if stopped => { + _ = &mut stop_deadline, if stopped || wrap_pending => { return Err("engine did not terminate generation within 20 seconds of STOP".to_owned()); } _ = command.result.closed(), if !stopped => { - pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?; - pipe.flush().await.map_err(|error| error.to_string())?; + if !wrap_pending { + pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + } stopped = true; - stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + continue; + } + _ = ticker.tick(), if dog.is_some() => { + if let Some(dog) = dog.as_mut() + && let leleka_serving_policy::watchdog::Verdict::Stalled { quiet_ms, .. } = dog.poll( + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + leleka_serving_policy::watchdog::Counters { beats: lines_read, busy: true, ticks: 0 }, + ) + { + return Err(format!( + "{STALL_PREFIX} for {} s during a request (stall watchdog)", + quiet_ms / 1000 + )); + } continue; } line = lines.next_line() => line.map_err(|error| error.to_string())?, } .ok_or("engine exited before a terminal line")?; + lines_read = lines_read.wrapping_add(1); match wire::parse_line(&line)? { Some(Event::Error(message)) => { status.write().await.metrics.fail(); send_failure(command.result.take(), message).await; return Ok(()); } - Some(event @ Event::Done(_)) => { - let Event::Done(done) = &event else { - unreachable!() - }; - let done = done.clone(); + Some(Event::Done(done)) => { let disconnected = stopped || command.result.is_closed(); - match command.result.take() { - GenerationResult::Buffered(sender) => { - events.push(event); - let _ = sender.send(Ok(events)); + if wrap_pending && !disconnected { + // The budget was reached: close the thinking and let the model answer. + wrap_pending = false; + passes.push(done); + let Some((_, plan)) = budget.take() else { + return Err("reasoning budget state lost".into()); + }; + let room = i64::from(command.request.max_new) + - i64::try_from(generated).unwrap_or(i64::MAX) + - i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX); + if room < 1 { + // No room left to answer: "length", as without a budget. + let combined = + combine_done(&passes[0], &passes, generated, wire::Finish::Length); + return finish(command, events, combined, false, status).await; } - GenerationResult::Streaming(sender) => { - let _ = sender.send(Ok(event)).await; + eprintln!( + "thinking budget reached ({} tokens): wrapping up the thinking", + plan.budget + ); + for id in &plan.wrap_up { + generated += 1; + deliver(command, &mut events, Event::Token(*id)).await; } - GenerationResult::Finished => {} + prompt.extend_from_slice(&segment); + prompt.extend_from_slice(&plan.wrap_up); + segment.clear(); + let next = Generate { + token_ids: prompt.clone(), + max_new: u32::try_from( + i64::from(command.request.max_new) + - i64::try_from(generated).unwrap_or(i64::MAX), + ) + .unwrap_or(1), + reasoning: None, + ..command.request.clone() + }; + let next_line = next.line().map_err(str::to_owned)?; + pipe.write_all(next_line.as_bytes()) + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + first_pass = false; + continue; + } + let done_out = if passes.is_empty() { + done + } else { + passes.push(done.clone()); + combine_done(&passes[0], &passes, generated, done.finish) + }; + return finish(command, events, done_out, disconnected, status).await; + } + Some(Event::PromptProgress { .. }) if !first_pass => {} + Some(_) if stopped || wrap_pending => {} + Some(event) => { + if let (Event::Token(id), Some((tracker, plan))) = (&event, budget.as_mut()) { + generated += 1; + segment.push(*id); + let verdict = if plan.stop_ids.contains(id) { + leleka_serving_policy::reasoning::Verdict::Continue + } else { + tracker.push(&(plan.token_bytes)(*id)) + }; + deliver(command, &mut events, event).await; + if verdict == leleka_serving_policy::reasoning::Verdict::WrapUp { + pipe.write_all(b"STOP\n") + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + wrap_pending = true; + stop_deadline + .as_mut() + .reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + } + } else { + if matches!(event, Event::Token(_)) { + generated += 1; + } + deliver(command, &mut events, event).await; } - status.write().await.metrics.finish(&done, disconnected); - return Ok(()); } - Some(_) if stopped => {} - Some(event) => match &command.result { - GenerationResult::Buffered(_) => events.push(event), - GenerationResult::Streaming(_) => command.result.send_event(event).await, - GenerationResult::Finished => {} - }, None => {} } } } +/// Hand one event to the client side (buffered or streamed). +async fn deliver(command: &GenerationCommand, events: &mut Vec, event: Event) { + match &command.result { + GenerationResult::Buffered(_) => events.push(event), + GenerationResult::Streaming(_) => command.result.send_event(event).await, + GenerationResult::Finished => {} + } +} + +/// The terminal event: hand `done` to the client and record the generation. +async fn finish( + command: &mut GenerationCommand, + mut events: Vec, + done: Done, + disconnected: bool, + status: &RwLock, +) -> Result<(), String> { + let event = Event::Done(done.clone()); + match command.result.take() { + GenerationResult::Buffered(sender) => { + events.push(event); + let _ = sender.send(Ok(events)); + } + GenerationResult::Streaming(sender) => { + let _ = sender.send(Ok(event)).await; + } + GenerationResult::Finished => {} + } + status.write().await.metrics.finish(&done, disconnected); + Ok(()) +} + async fn send_failure(result: GenerationResult, message: String) { match result { GenerationResult::Buffered(sender) => { @@ -439,6 +923,9 @@ async fn update(status: &RwLock, state: WorkerState, max_context: } status.state = state; status.max_context = max_context; + if max_context.is_some() { + status.known_max_context = max_context; + } } async fn stop(child: &mut Child, stdin: &mut Option) { @@ -488,6 +975,7 @@ mod tests { startup_timeout: Duration::from_secs(timeout_s), generation_timeout: None, max_restarts: 0, + ..Default::default() } } @@ -526,8 +1014,7 @@ mod tests { request: Generate { token_ids: vec![10000; 200000], max_new: 1, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result), }) @@ -570,8 +1057,7 @@ mod tests { request: Generate { token_ids: vec![10], max_new: 100, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Streaming(events), }) @@ -649,8 +1135,12 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: Some(0.5), - top_p: Some(0.9), + sampling: leleka_sampler_ref::RequestSampling { + temperature: Some(0.5), + top_p: Some(0.9), + ..Default::default() + }, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -684,8 +1174,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 300_000, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -745,8 +1234,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -769,8 +1257,7 @@ mod tests { request: Generate { token_ids: vec![99], max_new: 1, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -822,8 +1309,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Streaming(events_tx), }) @@ -846,8 +1332,7 @@ mod tests { request: Generate { token_ids: vec![99], max_new: 1, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -900,8 +1385,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -952,8 +1436,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Streaming(events_tx), }) @@ -984,8 +1467,7 @@ mod tests { request: Generate { token_ids: vec![99], max_new: 1, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(result_tx), }) @@ -1037,8 +1519,7 @@ mod tests { request: Generate { token_ids, max_new, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Buffered(sender), }, @@ -1169,8 +1650,7 @@ mod tests { request: Generate { token_ids: vec![10, 20], max_new: 3, - temperature: None, - top_p: None, + ..Default::default() }, result: GenerationResult::Streaming(events_tx), }) @@ -1269,4 +1749,337 @@ mod tests { ); std::fs::remove_dir_all(root).unwrap(); } + + // ---- load, unload, lazy start, reload gate, reasoning budget, stall watchdog ----------------- + + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("strata-worker-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn lines_of(path: &Path) -> usize { + std::fs::read_to_string(path).map_or(0, |text| text.lines().count()) + } + + struct Supervised { + status: Arc>, + requests: mpsc::Sender, + control: mpsc::Sender, + stop: watch::Sender, + task: tokio::task::JoinHandle<()>, + } + + fn supervise(config: WorkerConfig) -> Supervised { + 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 task = tokio::spawn(run_supervised( + config, + status.clone(), + stop_rx, + requests_rx, + control_rx, + )); + Supervised { + status, + requests, + control, + stop, + task, + } + } + + impl Supervised { + async fn unload(&self, idle_for: Option) -> leleka_serving_policy::idle::Outcome { + let (reply, answer) = oneshot::channel(); + self.control + .send(Control::Unload { idle_for, reply }) + .await + .unwrap(); + timeout(Duration::from_secs(10), answer) + .await + .unwrap() + .unwrap() + } + + async fn load(&self) -> Result<(), LoadError> { + let (reply, answer) = oneshot::channel(); + self.control.send(Control::Load { reply }).await.unwrap(); + timeout(Duration::from_secs(10), answer) + .await + .unwrap() + .unwrap() + } + + async fn generate(&self, request: Generate) -> Result, String> { + let (result, received) = oneshot::channel(); + self.requests + .send(GenerationCommand { + queue: None, + activity: None, + request, + result: GenerationResult::Buffered(result), + }) + .await + .unwrap(); + timeout(Duration::from_secs(10), received) + .await + .expect("generation answer") + .unwrap() + } + + async fn shutdown(self) { + self.stop.send(true).unwrap(); + timeout(Duration::from_secs(25), self.task) + .await + .unwrap() + .unwrap(); + } + } + + fn lifecycle_request() -> Generate { + Generate { + token_ids: vec![1, 2], + max_new: 2, + ..Default::default() + } + } + + #[tokio::test] + async fn unload_stops_the_engine_and_the_next_command_loads_it_again() { + use leleka_serving_policy::idle::Outcome; + let dir = scratch("unload"); + let mut config = fixture_config("lifecycle", 5); + config.args.push(dir.to_string_lossy().into_owned()); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + assert_eq!(worker.status.read().await.known_max_context, Some(4096)); + assert_eq!(worker.unload(None).await, Outcome::Unloaded); + wait_for(&worker.status, WorkerState::Unloaded).await; + { + let status = worker.status.read().await; + assert_eq!(status.max_context, None); + assert_eq!( + status.known_max_context, + Some(4096), + "the last context survives an unload" + ); + } + assert_eq!( + lines_of(&dir.join("quits")), + 1, + "the engine is asked to QUIT, not killed" + ); + assert_eq!(worker.unload(None).await, Outcome::NotLoaded); + // A command that arrives while unloaded starts the engine and is served. + let events = worker.generate(lifecycle_request()).await.unwrap(); + assert_eq!(events[..2], [Event::Token(31), Event::Token(32)]); + assert_eq!(worker.status.read().await.state, WorkerState::Ready); + assert_eq!(lines_of(&dir.join("boots")), 2); + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn lazy_start_waits_for_load_and_load_is_idempotent() { + let dir = scratch("lazy"); + let mut config = fixture_config("lifecycle", 5); + config.args.push(dir.to_string_lossy().into_owned()); + config.lazy = true; + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Unloaded).await; + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + lines_of(&dir.join("boots")), + 0, + "no process before the first load" + ); + worker.load().await.unwrap(); + assert_eq!(worker.status.read().await.state, WorkerState::Ready); + worker.load().await.unwrap(); + assert_eq!(lines_of(&dir.join("boots")), 1); + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn idle_unload_waits_for_the_idle_period_and_for_queued_work() { + use leleka_serving_policy::idle::Outcome; + let dir = scratch("idle"); + let mut config = fixture_config("lifecycle", 5); + config.args.push(dir.to_string_lossy().into_owned()); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + assert_eq!( + worker.unload(Some(Duration::from_secs(3600))).await, + Outcome::Busy + ); + assert_eq!(worker.status.read().await.state, WorkerState::Ready); + tokio::time::sleep(Duration::from_millis(1100)).await; + assert_eq!( + worker.unload(Some(Duration::from_secs(1))).await, + Outcome::Unloaded + ); + wait_for(&worker.status, WorkerState::Unloaded).await; + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn the_before_load_command_runs_on_reload_but_not_on_the_first_start() { + let dir = scratch("gate"); + let marker = dir.join("before"); + let mut config = fixture_config("lifecycle", 5); + config.args.push(dir.to_string_lossy().into_owned()); + config.before_load = Some(BeforeLoad::Shell(format!( + "echo hook >> {}", + marker.display() + ))); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + assert_eq!(lines_of(&marker), 0); + worker.unload(None).await; + worker.load().await.unwrap(); + assert_eq!(lines_of(&marker), 1); + worker.unload(None).await; + worker.load().await.unwrap(); + assert_eq!(lines_of(&marker), 2); + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + fn budget_request(max_new: u32) -> Generate { + Generate { + token_ids: vec![10, 20], + max_new, + sampling: leleka_sampler_ref::RequestSampling { + temperature: Some(0.7), + ..Default::default() + }, + reasoning: Some(crate::wire::ReasoningPlan { + budget: 3, + wrap_up: vec![90, 91], + stop_ids: vec![248046], + token_bytes: Arc::new(|id| vec![b'a' + (id % 26) as u8]), + }), + ..Default::default() + } + } + + #[tokio::test] + async fn reasoning_budget_wraps_up_and_continues_from_the_prefix() { + let dir = scratch("budget"); + let mut config = fixture_config("budget", 5); + config.args.push(dir.to_string_lossy().into_owned()); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + let events = worker.generate(budget_request(40)).await.unwrap(); + let tokens: Vec = events + .iter() + .filter_map(|e| match e { + Event::Token(id) => Some(*id), + _ => None, + }) + .collect(); + // Tokens 34 and 35 came after the budget point and are discarded; the wrap-up text is + // delivered as generated tokens, then the continuation. + assert_eq!(tokens, vec![31, 32, 33, 90, 91, 40, 41]); + let progress: Vec<_> = events + .iter() + .filter(|e| matches!(e, Event::PromptProgress { .. })) + .collect(); + assert_eq!( + progress.len(), + 1, + "only the first pass reports prompt progress" + ); + let Some(Event::Done(done)) = events.last() else { + panic!("expected DONE") + }; + assert_eq!(done.generated, 7); + assert_eq!( + done.prompt_tokens, 2, + "the caller's prompt, not the re-read prefix" + ); + assert_eq!(done.reused, Some(0)); + assert_eq!(done.finish, wire::Finish::Stop); + assert_eq!((done.prompt_ms, done.decode_ms), (4.0, 6.0)); + assert_eq!((done.expert_hits, done.expert_lookups), (Some(5), Some(10))); + assert_eq!( + std::fs::read_to_string(dir.join("requests")) + .unwrap() + .lines() + .count(), + 2 + ); + let metrics = worker.status.read().await.metrics; + assert_eq!((metrics.started, metrics.completed), (1, 1)); + assert_eq!(metrics.done_generated_tokens, 7); + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn reasoning_budget_without_room_to_answer_ends_as_length() { + let dir = scratch("budget-length"); + let mut config = fixture_config("budget", 5); + config.args.push(dir.to_string_lossy().into_owned()); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + let events = worker.generate(budget_request(5)).await.unwrap(); + let tokens: Vec = events + .iter() + .filter_map(|e| match e { + Event::Token(id) => Some(*id), + _ => None, + }) + .collect(); + assert_eq!( + tokens, + vec![31, 32, 33], + "no wrap-up fits: nothing is appended" + ); + let Some(Event::Done(done)) = events.last() else { + panic!("expected DONE") + }; + assert_eq!((done.generated, done.finish), (3, wire::Finish::Length)); + assert_eq!( + std::fs::read_to_string(dir.join("requests")) + .unwrap() + .lines() + .count(), + 1 + ); + worker.shutdown().await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn the_stall_watchdog_ends_a_request_that_makes_no_progress() { + let mut config = fixture_config("stall", 5); + config.stall_timeout = Some(Duration::from_secs(1)); + let worker = supervise(config); + wait_for(&worker.status, WorkerState::Ready).await; + let started = std::time::Instant::now(); + let error = worker + .generate(Generate { + token_ids: vec![1], + max_new: 1, + ..Default::default() + }) + .await; + assert!(started.elapsed() < Duration::from_secs(8)); + let message = error.unwrap_err(); + assert!( + message.starts_with("engine made no progress for"), + "{message}" + ); + // The engine is ended and marked failed (no restarts are configured here). + wait_for(&worker.status, WorkerState::Failed).await; + let _ = worker.stop.send(true); + let _ = timeout(Duration::from_secs(25), worker.task).await; + } } diff --git a/control-plane/tests/fixtures/golden/gen_lines.json b/control-plane/tests/fixtures/golden/gen_lines.json new file mode 100644 index 00000000..fdb8a117 --- /dev/null +++ b/control-plane/tests/fixtures/golden/gen_lines.json @@ -0,0 +1,1085 @@ +{ + "source": "serve/server.py StrataEngine.generate (real code, fake pipe)", + "cases": [ + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": {}, + "line": "GEN 16 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.0 + }, + "line": "GEN 16 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7 + }, + "line": "GEN 16 temperature=0.7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GEN 16 temperature=0.7 top_p=0.9 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GEN 16 temperature=1.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GEN 16 temperature=0.8 top_k=40 min_p=0.05 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GEN 16 temperature=0.8 top_k=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GEN 16 temperature=0.8 top_k=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GEN 16 temperature=0.6 top_p=0.95 top_k=20 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GEN 16 penalty_repeat=1.1 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GEN 16 penalty_repeat=1.1 penalty_last_n=256 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GEN 16 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GEN 16 penalty_present=-0.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GEN 16 penalty_freq=1.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GEN 16 temperature=0.7 seed=42 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GEN 16 temperature=0.7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GEN 16 temperature=0.7 seed=18446744073709551615 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.9, + "top_p": 0.8, + "top_k": 33, + "min_p": 0.02, + "repetition_penalty": 1.05, + "presence_penalty": 0.1, + "frequency_penalty": 0.2, + "penalty_last_n": 128, + "seed": 7 + }, + "line": "GEN 16 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GEN 16 pcie_frac=0.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GEN 16 pcie_frac=0.35 spec_min_p=0.2 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GEN 16 spec_min_p=1.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "experimental_speed_projection": true + }, + "line": "GEN 16 cvec=1 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "experimental_speed_projection": false + }, + "line": "GEN 16 cvec=0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GEN 16 temperature=0.5 pcie_frac=0.5 cvec=0 1,2,3\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": {}, + "line": "GEN 4096 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.0 + }, + "line": "GEN 4096 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7 + }, + "line": "GEN 4096 temperature=0.7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GEN 4096 temperature=0.7 top_p=0.9 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GEN 4096 temperature=1.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GEN 4096 temperature=0.8 top_k=40 min_p=0.05 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GEN 4096 temperature=0.8 top_k=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GEN 4096 temperature=0.8 top_k=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GEN 4096 temperature=0.6 top_p=0.95 top_k=20 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GEN 4096 penalty_repeat=1.1 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GEN 4096 penalty_repeat=1.1 penalty_last_n=256 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GEN 4096 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GEN 4096 penalty_present=-0.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GEN 4096 penalty_freq=1.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GEN 4096 temperature=0.7 seed=42 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GEN 4096 temperature=0.7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GEN 4096 temperature=0.7 seed=18446744073709551615 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.9, + "top_p": 0.8, + "top_k": 33, + "min_p": 0.02, + "repetition_penalty": 1.05, + "presence_penalty": 0.1, + "frequency_penalty": 0.2, + "penalty_last_n": 128, + "seed": 7 + }, + "line": "GEN 4096 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GEN 4096 pcie_frac=0.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GEN 4096 pcie_frac=0.35 spec_min_p=0.2 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GEN 4096 spec_min_p=1.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "experimental_speed_projection": true + }, + "line": "GEN 4096 cvec=1 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "experimental_speed_projection": false + }, + "line": "GEN 4096 cvec=0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GEN 4096 temperature=0.5 pcie_frac=0.5 cvec=0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": {}, + "line": "GENI 32 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.0 + }, + "line": "GENI 32 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7 + }, + "line": "GENI 32 temperature=0.7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GENI 32 temperature=0.7 top_p=0.9 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GENI 32 temperature=1.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GENI 32 temperature=0.8 top_k=40 min_p=0.05 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GENI 32 temperature=0.8 top_k=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GENI 32 temperature=0.8 top_k=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GENI 32 temperature=0.6 top_p=0.95 top_k=20 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GENI 32 penalty_repeat=1.1 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GENI 32 penalty_repeat=1.1 penalty_last_n=256 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GENI 32 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GENI 32 penalty_present=-0.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GENI 32 penalty_freq=1.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GENI 32 temperature=0.7 seed=42 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GENI 32 temperature=0.7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GENI 32 temperature=0.7 seed=18446744073709551615 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.9, + "top_p": 0.8, + "top_k": 33, + "min_p": 0.02, + "repetition_penalty": 1.05, + "presence_penalty": 0.1, + "frequency_penalty": 0.2, + "penalty_last_n": 128, + "seed": 7 + }, + "line": "GENI 32 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GENI 32 pcie_frac=0.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GENI 32 pcie_frac=0.35 spec_min_p=0.2 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GENI 32 spec_min_p=1.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "experimental_speed_projection": true + }, + "line": "GENI 32 cvec=1 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "experimental_speed_projection": false + }, + "line": "GENI 32 cvec=0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GENI 32 temperature=0.5 pcie_frac=0.5 cvec=0 /tmp/req-abc123.sve 5,248056,248056,6\n" + } + ] +} diff --git a/control-plane/tests/fixtures/golden/http_surface.json b/control-plane/tests/fixtures/golden/http_surface.json new file mode 100644 index 00000000..c22aea80 --- /dev/null +++ b/control-plane/tests/fixtures/golden/http_surface.json @@ -0,0 +1,4347 @@ +{ + "source": "serve/server.py Handler (real code, resident fake engine)", + "scenarios": { + "cors_off": { + "setup": { + "cors_origins": [] + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984728, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984728, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/nothing", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "not found" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "cors_off_with_key": { + "setup": { + "cors_origins": [], + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": true, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "cors_any": { + "setup": { + "cors_origins": [ + "*" + ] + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization,content-type", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 200, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 200, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984729, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984729, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 200, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 200, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/nothing", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 404, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "message": "not found" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "cors_any_with_key": { + "setup": { + "cors_origins": [ + "*" + ], + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization,content-type", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 401, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 401, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 401, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 401, + "headers": { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": true, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "cors_listed": { + "setup": { + "cors_origins": [ + "https://a.example", + "https://b.example" + ] + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://a.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization,content-type", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 200, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://a.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 200, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://b.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984730, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984730, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "object": "list", + "data": [ + { + "id": "strata-test", + "object": "model", + "status": { + "value": "loaded" + }, + "meta": { + "n_ctx": 4096 + }, + "architecture": { + "input_modalities": [ + "text" + ], + "output_modalities": [ + "text" + ] + } + } + ] + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/nothing", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 404, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://a.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "message": "not found" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "cors_listed_with_key": { + "setup": { + "cors_origins": [ + "https://a.example", + "https://b.example" + ], + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "OPTIONS", + "path": "/v1/chat/completions", + "headers": { + "Origin": "https://a.example", + "Access-Control-Request-Headers": "authorization,content-type" + }, + "body": null + }, + "status": 204, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://a.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization,content-type", + "access-control-max-age": "600" + }, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "OPTIONS", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 204, + "headers": {}, + "body": null, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://a.example/" + }, + "body": null + }, + "status": 401, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://a.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status?x=1", + "headers": { + "Origin": "https://b.example" + }, + "body": null + }, + "status": 401, + "headers": { + "vary": "Origin", + "access-control-allow-origin": "https://b.example", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta", + "access-control-max-age": "600" + }, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": { + "Origin": "https://evil.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/models", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": true, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": { + "Origin": "https://a.example" + }, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "own_page": { + "setup": { + "trusted_origins": [ + "https://strata.example.com" + ] + }, + "steps": [ + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Origin": "http://127.0.0.1:1" + }, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 403, + "headers": {}, + "body": { + "error": { + "message": "settings can be changed only from Strata's own page (or an origin in the config's trusted_origins)" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Origin": "https://evil.example" + }, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 403, + "headers": {}, + "body": { + "error": { + "message": "settings can be changed only from Strata's own page (or an origin in the config's trusted_origins)" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Origin": "https://strata.example.com/" + }, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Origin": "https://strata.example.com", + "Host": "proxy.internal" + }, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Origin": "https://evil.example", + "X-Forwarded-Host": "evil.example", + "CF-Ray": "1" + }, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 403, + "headers": {}, + "body": { + "error": { + "message": "settings can be changed only from Strata's own page (or an origin in the config's trusted_origins)" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Content-Type": "text/plain" + }, + "body": "{\"defaults\": {\"temperature\": 0.5}}" + }, + "status": 415, + "headers": {}, + "body": { + "error": { + "message": "send application/json" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Content-Type": "application/x-www-form-urlencoded" + }, + "body": "{\"defaults\": {\"temperature\": 0.5}}" + }, + "status": 415, + "headers": {}, + "body": { + "error": { + "message": "send application/json" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Content-Type": "application/json; charset=utf-8" + }, + "body": "{\"defaults\": {\"temperature\": 0.5}}" + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + } + ] + }, + "settings": { + "setup": {}, + "steps": [ + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "temperature": 9 + } + } + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "temperature: 0..2" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "nonsense": 1 + } + } + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "unknown setting 'nonsense'" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "top_p": 0, + "temperature": 1 + } + } + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "top_p: 0 < top_p <= 1" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.7, + "top_k": 40, + "seed": 3 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "max_tokens": 128, + "reasoning_effort": "low", + "experimental_speed_projection": true + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "max_tokens": 128, + "reasoning_effort": "low", + "experimental_speed_projection": true + } + }, + "state": { + "loaded": true, + "shared": { + "max_tokens": 128, + "reasoning_effort": "low", + "experimental_speed_projection": true + } + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "max_tokens": 128, + "reasoning_effort": "low", + "experimental_speed_projection": true + } + }, + "state": { + "loaded": true, + "shared": { + "max_tokens": 128, + "reasoning_effort": "low", + "experimental_speed_projection": true + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": [ + 1, + 2 + ] + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "temperature": 0.5 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "temperature": 0.5 + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.5 + } + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": {} + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": 5 + } + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "defaults must be an object" + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "settings_with_key": { + "setup": { + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/settings", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/settings", + "headers": { + "Authorization": "Bearer kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "shared": false, + "defaults": {} + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": {}, + "body": { + "defaults": { + "top_k": 5 + } + } + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/settings", + "headers": { + "Authorization": "Bearer kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "body": { + "defaults": { + "top_k": 5 + } + } + }, + "status": 200, + "headers": {}, + "body": { + "shared": true, + "defaults": { + "top_k": 5 + } + }, + "state": { + "loaded": true, + "shared": { + "top_k": 5 + } + } + } + ] + }, + "reads_loaded": { + "setup": { + "aliases": [ + "alias-one", + "alias-two" + ] + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/props", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=strata-test", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=alias-one", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=nope", + "headers": {}, + "body": null + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "model not found" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": [ + { + "id": 0, + "n_ctx": 4096, + "is_processing": false + } + ], + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/api/health", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984733, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984733, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "reads_loaded_with_defaults": { + "setup": { + "config_sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.2, + "repetition_penalty": 1.05, + "penalty_last_n": 64, + "seed": 8 + }, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + }, + "max_context": 32768 + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/props", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 32768, + "params": { + "temperature": 0.9, + "top_p": 0.95, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.2, + "repeat_penalty": 1.05, + "repeat_last_n": 64, + "seed": 8, + "n_predict": 256 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=strata-test", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 32768, + "params": { + "temperature": 0.9, + "top_p": 0.95, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.2, + "repeat_penalty": 1.05, + "repeat_last_n": 64, + "seed": 8, + "n_predict": 256 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=alias-one", + "headers": {}, + "body": null + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "model not found" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=nope", + "headers": {}, + "body": null + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "model not found" + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 32768, + "params": { + "temperature": 0.9, + "top_p": 0.95, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.2, + "repeat_penalty": 1.05, + "repeat_last_n": 64, + "seed": 8, + "n_predict": 256 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": false, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": [ + { + "id": 0, + "n_ctx": 32768, + "is_processing": false + } + ], + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/api/health", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 32768, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984734, + "uptime_s": 0, + "cache_max_tokens": 32768, + "context": { + "native": 32768, + "max_positions": 32768 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984734, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": { + "temperature": 0.9, + "max_tokens": 256 + } + } + } + ] + }, + "reads_unloaded": { + "setup": { + "loaded": false, + "aliases": [ + "alias-one" + ] + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/props", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": true, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=strata-test", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": true, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=alias-one", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": true, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=nope", + "headers": {}, + "body": null + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "model not found" + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props?model=", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": true, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": [], + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/api/health", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": false, + "loaded": false, + "service": "strata" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": false, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984734, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984734, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": false, + "shared": {} + } + } + ] + }, + "reads_busy": { + "setup": { + "status": { + "busy": true, + "queued": 2 + } + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": [ + { + "id": 0, + "n_ctx": 4096, + "is_processing": true + } + ], + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984735, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 1, + "in_flight": 3, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984735, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "reads_with_key": { + "setup": { + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "GET", + "path": "/props", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/v1/status", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/api/health", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": true, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/health", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "ok", + "max_context": 4096, + "model": "strata-test", + "images": false, + "api_key": true, + "loaded": true, + "service": "strata" + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "lifecycle": { + "setup": {}, + "steps": [ + { + "request": { + "method": "POST", + "path": "/unload", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "unloaded" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/unload", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "not loaded" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/slots", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": [], + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/load", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/load", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": {} + }, + "status": 200, + "headers": {}, + "body": { + "status": "unloaded", + "service": "strata", + "model": "strata-test", + "loaded": false, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984736, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": 1791984736 + }, + "last_timings": null, + "machine": { + "at": 1791984736, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": {} + }, + "status": 200, + "headers": {}, + "body": { + "status": "not loaded", + "service": "strata", + "model": "strata-test", + "loaded": false, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984736, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": 1791984736 + }, + "last_timings": null, + "machine": { + "at": 1791984736, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": {}, + "body": { + "model": "other-model" + } + }, + "status": 404, + "headers": {}, + "body": { + "error": { + "message": "model not found" + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": {}, + "body": { + "model": "strata-test" + } + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded", + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984736, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": 1791984736 + }, + "last_timings": null, + "machine": { + "at": 1791984736, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": {}, + "body": {} + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded", + "service": "strata", + "model": "strata-test", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984736, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": 1791984736 + }, + "last_timings": null, + "machine": { + "at": 1791984736, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": { + "Content-Type": "text/plain" + }, + "body": "{}" + }, + "status": 415, + "headers": {}, + "body": { + "error": { + "message": "send application/json" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": { + "Origin": "https://other.example" + }, + "body": {} + }, + "status": 403, + "headers": {}, + "body": { + "error": { + "message": "the model can be loaded or unloaded only from Strata's own page (or an origin in the config's trusted_origins)" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": [ + 1 + ] + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "send a JSON object" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": { + "Content-Type": "application/json" + }, + "body": "not json" + }, + "status": 400, + "headers": {}, + "body": { + "error": { + "type": "invalid_request_error", + "message": "Expecting value: line 1 column 1 (char 0)" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": { + "model": null + } + }, + "status": 200, + "headers": {}, + "body": { + "status": "unloaded", + "service": "strata", + "model": "strata-test", + "loaded": false, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984736, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": 1791984736 + }, + "last_timings": null, + "machine": { + "at": 1791984736, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "GET", + "path": "/props", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "default_generation_settings": { + "n_ctx": 4096, + "params": { + "n_predict": -1 + } + }, + "total_slots": 1, + "model_alias": "strata-test", + "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set sysns = namespace(count=0, text='') %}\n{%- for message in messages %}\n {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %}\n {%- set sys_content = render_content(message.content, false, true)|trim %}\n {%- if sys_content %}\n {%- set sysns.text = sysns.text + ('\\n' if sysns.text else '') + sys_content %}\n {%- endif %}\n {%- set sysns.count = sysns.count + 1 %}\n {%- endif %}\n{%- endfor %}\n{%- set num_sys = sysns.count %}\n{%- set merged_system = sysns.text %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort == 'high' %}\n {%- set resolved_reasoning_effort = 'xhigh' %}\n {%- endif %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n' }}\n {%- if merged_system %}\n {{- '\\n\\n' + merged_system }}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if merged_system %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('') and content.endswith('')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if loop.index0 >= num_sys %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" or message.role == \"developer\" %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n\\n' + reasoning_content + '\\n\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if tool_call.name is not defined or tool_call.name is none %}\n {{- raise_exception('Tool call is missing a function name.') }}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is mapping %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- elif tool_call.arguments is string %}\n {%- if tool_call.arguments|trim %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }}\n {%- endif %}\n {%- elif tool_call.arguments is defined and tool_call.arguments is not none %}\n {{- raise_exception('Tool call arguments for function \"' + (tool_call.name | string) + '\" must be an object/mapping or a JSON string.') }}\n {%- endif %}\n {{- '\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n\\n' }}\n {{- content }}\n {{- '\\n' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\n' }}\n {%- endif %}\n{%- endif %}\n{#- Unsloth fixes - developer role, merged system messages, tool calling #}", + "modalities": { + "vision": false + }, + "models_autoload": true, + "is_sleeping": true, + "build_info": "Strata 9.9.9" + }, + "state": { + "loaded": false, + "shared": {} + } + } + ] + }, + "lifecycle_busy": { + "setup": { + "status": { + "queued": 1 + } + }, + "steps": [ + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": {} + }, + "status": 409, + "headers": {}, + "body": { + "error": { + "type": "model_busy", + "message": "a request is running or queued" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": {}, + "body": {} + }, + "status": 409, + "headers": {}, + "body": { + "error": { + "type": "model_busy", + "message": "a request is running or queued" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/unload", + "headers": {}, + "body": null + }, + "status": 409, + "headers": {}, + "body": { + "status": "busy" + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/load", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded" + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "lifecycle_unloaded_then_busy": { + "setup": { + "loaded": false, + "status": { + "busy": true + } + }, + "steps": [ + { + "request": { + "method": "POST", + "path": "/v1/load", + "headers": {}, + "body": {} + }, + "status": 409, + "headers": {}, + "body": { + "error": { + "type": "model_busy", + "message": "a request is running or queued" + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/unload", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "not loaded" + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/load", + "headers": {}, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded" + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + }, + "lifecycle_with_key": { + "setup": { + "api_key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "steps": [ + { + "request": { + "method": "POST", + "path": "/unload", + "headers": {}, + "body": null + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": {}, + "body": {} + }, + "status": 401, + "headers": {}, + "body": { + "error": { + "type": "authentication_error", + "message": "missing or wrong API key" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": { + "Authorization": "Bearer kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", + "Origin": "https://other.example" + }, + "body": {} + }, + "status": 403, + "headers": {}, + "body": { + "error": { + "message": "the model can be loaded or unloaded only from Strata's own page (or an origin in the config's trusted_origins)" + } + }, + "state": { + "loaded": true, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/v1/unload", + "headers": { + "Authorization": "Bearer kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "body": {} + }, + "status": 200, + "headers": {}, + "body": { + "status": "unloaded", + "service": "strata", + "model": "strata-test", + "loaded": false, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "9.9.9", + "started": 1791984737, + "uptime_s": 0, + "cache_max_tokens": 4096, + "context": { + "native": 4096, + "max_positions": 4096 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791984737, + "gpu": null, + "ram": null + } + }, + "state": { + "loaded": false, + "shared": {} + } + }, + { + "request": { + "method": "POST", + "path": "/load", + "headers": { + "x-api-key": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + }, + "body": null + }, + "status": 200, + "headers": {}, + "body": { + "status": "loaded" + }, + "state": { + "loaded": true, + "shared": {} + } + } + ] + } + } +} diff --git a/control-plane/tests/fixtures/mock_engine.sh b/control-plane/tests/fixtures/mock_engine.sh index c2234e57..c843f049 100755 --- a/control-plane/tests/fixtures/mock_engine.sh +++ b/control-plane/tests/fixtures/mock_engine.sh @@ -113,6 +113,46 @@ case "$2" in esac done ;; + lifecycle) + printf 'boot\n' >> "$3/boots" + printf 'INFO engine=mock\nREADY %s stop\n' "${4:-4096}" + while IFS= read -r line; do + case "$line" in + 'GEN 2 1,2') printf 'T 31\nT 32\nDONE 2 2 1.0 2.0 stop 0 0 0 0 0\n' ;; + QUIT) printf 'quit\n' >> "$3/quits"; exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + budget) + printf 'READY 4096 stop\n' + while IFS= read -r line; do + case "$line" in + 'GEN 40 temperature=0.7 10,20') + printf '%s\n' "$line" >> "$3/requests" + printf 'PP 2 2 1 2.0\nT 31\nT 32\nT 33\nT 34\nT 35\n' + IFS= read -r stop || exit 3 + [ "$stop" = STOP ] || exit 4 + printf 'DONE 5 2 1.0 2.0 cancel 0 0 0 4 8\n' ;; + 'GEN 35 temperature=0.7 10,20,31,32,33,90,91') + printf '%s\n' "$line" >> "$3/requests" + printf 'PP 7 7 1 2.0\nT 40\nT 41\nDONE 2 7 3.0 4.0 stop 0 0 5 1 2\n' ;; + 'GEN 5 temperature=0.7 10,20') + printf '%s\n' "$line" >> "$3/requests" + printf 'T 31\nT 32\nT 33\nT 34\n' + IFS= read -r stop || exit 3 + [ "$stop" = STOP ] || exit 4 + printf 'DONE 4 2 1.0 2.0 cancel\n' ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + stall) + printf 'READY 4096 stop\n' + IFS= read -r line || exit 3 + sleep 30 + ;; restart-loop) printf 'boot\n' >> "$3/boots" printf 'READY 262144 stop\n' diff --git a/control-plane/tests/golden/gen_goldens.py b/control-plane/tests/golden/gen_goldens.py new file mode 100644 index 00000000..a14b163b --- /dev/null +++ b/control-plane/tests/golden/gen_goldens.py @@ -0,0 +1,553 @@ +"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only). + +Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables +of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of +`crates/serving-policy` compare against these files. + + python3 -I control-plane/tests/golden/gen_goldens.py [section ...] + +Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them. +Sections: gen_lines, shared, props_slots, cors, ... +""" +import json +import os +import queue +import sys +import threading + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.normpath(os.path.join(HERE, "..", "..", "..")) +ENGINE = os.path.join(REPO, "engine", "strata") +sys.path.insert(0, ENGINE) +sys.path.insert(0, os.path.join(ENGINE, "tools")) + +OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden") +OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures") + + +def write(name, obj, dest="control"): + out = OUT_POLICY if dest == "policy" else OUT_CONTROL + os.makedirs(out, exist_ok=True) + path = os.path.join(out, name + ".json") + with open(path, "w", encoding="utf-8") as f: + json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False) + f.write("\n") + print("wrote", os.path.relpath(path, REPO), file=sys.stderr) + + +# ------------------------------------------------------------------------------------------------ gen_lines +def gen_lines(): + from serve.server import StrataEngine + + class Pipe: + def __init__(self): + self.sent = [] + + def write(self, text): + self.sent.append(text) + + def flush(self): + pass + + def capture(ids, max_new, sampling, embeddings=None): + eng = object.__new__(StrataEngine) + eng.proc = type("P", (), {"stdin": Pipe()})() + eng.lines = queue.Queue() + eng.lines.put("DONE 1 1 1.0 1.0 stop\n") + eng.can_stop = False + eng.progress = None + eng.prefill_tok_s_mean = None + eng.last = {} + list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings)) + return "".join(eng.proc.stdin.sent) + + cases = [] + sampling_tables = [ + {}, + {"temperature": 0.0}, + {"temperature": 0.7}, + {"temperature": 0.7, "top_p": 0.9}, + {"temperature": 1, "top_p": 1.0}, + {"temperature": 0.8, "top_k": 40, "min_p": 0.05}, + {"temperature": 0.8, "top_k": 0}, + {"temperature": 0.8, "top_k": 1000}, + {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, + {"repetition_penalty": 1.1}, + {"repetition_penalty": 1.1, "penalty_last_n": 256}, + {"presence_penalty": 0.5, "frequency_penalty": 0.25}, + {"presence_penalty": -0.5}, + {"frequency_penalty": 1.5, "penalty_last_n": 0}, + {"temperature": 0.7, "seed": 42}, + {"temperature": 0.7, "seed": 0}, + {"temperature": 0.7, "seed": 18446744073709551615}, + {"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05, + "presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7}, + {"strata_tune": {"pcie_frac": 0.0}}, + {"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}}, + {"strata_tune": {"spec_min_p": 1.0}}, + {"experimental_speed_projection": True}, + {"experimental_speed_projection": False}, + {"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False}, + ] + for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None), + ([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")): + for sampling in sampling_tables: + cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling, + "line": capture(ids, max_new, sampling, emb)}) + write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases}) + + +# ------------------------------------------------------------------------------------------------ shared +def shared(): + from serve.server import clean_shared_defaults, sampling_defaults_from_config + + clean_cases = [ + None, {}, [], "x", 5, + {"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5}, + {"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"}, + {"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False}, + {"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"}, + {"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615}, + {"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"}, + {"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, + {"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3}, + {"experimental_speed_projection": True}, {"experimental_speed_projection": False}, + {"experimental_speed_projection": 1}, + {"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1}, + {"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100, + "reasoning_effort": "medium", "experimental_speed_projection": False}, + ] + clean = [] + for case in clean_cases: + try: + clean.append({"input": case, "ok": clean_shared_defaults(case)}) + except ValueError as e: + clean.append({"input": case, "error": str(e)}) + + config_cases = [ + None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True}, + {"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2}, + {"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5}, + {"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25}, + {"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0}, + {"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5}, + {"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"}, + {"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"}, + {"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3}, + {"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1, + "frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9}, + ] + import contextlib + import io + config = [] + for case in config_cases: + out = io.StringIO() + try: + with contextlib.redirect_stdout(out): + ok = sampling_defaults_from_config({"sampling": case} if case is not None else {}) + config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines() + if "unknown key" in ln]}) + except SystemExit as e: + config.append({"input": case, "error": str(e)}) + write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)", + "clean": clean, "config": config}, dest="policy") + + +# ------------------------------------------------------------------------------------------------ reasoning +def reasoning(): + import random + from serve.frontend import OutputParser + from serve.server import Detokenizer, Service, ByteTokenizer + + class BytesTok: + """Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer.""" + def __init__(self, table): + self.table = table + + def token_bytes(self, t): + return self.table[t] + + pieces = [b"a", b"b", b" so ", b"think", b"", b"", b"", b"<", b"/", b"\n", + b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"", b"x"] + rng = random.Random(1234) + seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0], + [3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] + for _ in range(120): + seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))]) + cases = [] + for seq in seqs: + row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}} + for budget in (1, 2, 3, 5, 8): + parser = OutputParser(thinking=True, tools=None, stream_tools=True) + detok = Detokenizer(BytesTok(pieces)) + thought, wrap_at = 0, None + for i, t in enumerate(seq): + parser.feed(detok.push(t)) + if parser.state == "reasoning": + thought += 1 + if thought >= budget and not parser.buf and not detok.pending(): + wrap_at = i + break + row["wrap_at"][str(budget)] = wrap_at + cases.append(row) + + parse = [] + svc = Service.__new__(Service) + for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0), + ({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50), + ({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0), + ({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0), + ({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]: + svc.reasoning_budget_tokens = default + try: + parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)}) + except ValueError as e: + parse.append({"request": req, "default": default, "error": str(e)}) + from serve.server import REASONING_WRAP_UP + write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real " + "Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases, + "parse": parse}, dest="policy") + + +# ------------------------------------------------------------------------------------------------ http +def http_surface(): + """The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine).""" + import http.client + from pathlib import Path + from serve.frontend import ChatTemplate + from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve + + class Resident(StrataEngine): + def __init__(self, tok, loaded, max_context): + self.reply = MockEngine(tok, "Hello.", max_context=max_context) + self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {} + self.loaded, self.unloaded, self.progress = loaded, not loaded, None + + def alive(self): + return self.loaded + + def exit_code(self): + return None + + def restart(self): + self.loaded, self.unloaded = True, False + + def close(self): + self.loaded = False + + def unload(self): + self.close() + self.unloaded = True + + def generate(self, *args, **kwargs): + yield from self.reply.generate(*args, **kwargs) + + def run(setup, steps): + tok = ByteTokenizer() + engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096)) + svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), + model_name=setup.get("model", "strata-test"), + sampling_defaults=setup.get("config_sampling") or {}) + svc.set_aliases(setup.get("aliases")) + svc.api_key = setup.get("api_key", "") + svc.cors_origins = setup.get("cors_origins", []) + svc.trusted_origins = setup.get("trusted_origins", []) + if setup.get("shared"): + svc.shared = dict(setup["shared"]) + svc.idle_unload_s = setup.get("idle_unload_s", 0) + for key, value in (setup.get("status") or {}).items(): + svc.status[key] = value + httpd = serve(svc, port=0) + port = httpd.server_address[1] + out = [] + try: + for step in steps: + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + headers = dict(step.get("headers") or {}) + body = step.get("body") + if body is not None and not isinstance(body, str): + body = json.dumps(body) + headers.setdefault("Content-Type", "application/json") + if body is not None: + headers.setdefault("Content-Length", str(len(body.encode()))) + conn.request(step["method"], step["path"], body=body.encode() if body is not None else None, + headers=headers) + response = conn.getresponse() + raw = response.read().decode() + selected = {k.lower(): v for k, v in response.getheaders() + if k.lower().startswith("access-control-") or k.lower() == "vary"} + try: + parsed = json.loads(raw) if raw else None + except ValueError: + parsed = raw + out.append({"request": {"method": step["method"], "path": step["path"], + "headers": step.get("headers") or {}, "body": step.get("body")}, + "status": response.status, "headers": selected, "body": parsed, + "state": {"loaded": engine.loaded, "shared": svc.shared}}) + conn.close() + finally: + httpd.shutdown() + httpd.server_close() + return {"setup": setup, "steps": out} + + scenarios = {} + # ---- CORS + cors_steps = [ + {"method": "OPTIONS", "path": "/v1/chat/completions", + "headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}}, + {"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, + {"method": "OPTIONS", "path": "/v1/models"}, + {"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}}, + {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}}, + {"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}}, + {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, + {"method": "GET", "path": "/v1/models"}, + {"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}}, + {"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}}, + {"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}}, + ] + for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])): + scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps) + # (an unknown path answers 404 before authentication in the Python server; the Rust server + # authenticates every path first, so that one step is left out here) + scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1]) + # ---- own page + page = {"defaults": {"temperature": 0.5}} + own = [ + {"method": "POST", "path": "/settings", "body": page}, + {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}}, + {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}}, + {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}}, + {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com", + "Host": "proxy.internal"}}, + {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example", + "X-Forwarded-Host": "evil.example", + "CF-Ray": "1"}}, + {"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}}, + {"method": "POST", "path": "/settings", "body": json.dumps(page), + "headers": {"Content-Type": "application/x-www-form-urlencoded"}}, + {"method": "POST", "path": "/settings", "body": json.dumps(page), + "headers": {"Content-Type": "application/json; charset=utf-8"}}, + {"method": "GET", "path": "/settings"}, + ] + scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own) + # ---- settings + settings = [ + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}}, + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}}, + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low", + "experimental_speed_projection": True}}}, + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": [1, 2]}, + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}}, + {"method": "POST", "path": "/settings", "body": {}}, + {"method": "GET", "path": "/settings"}, + {"method": "POST", "path": "/settings", "body": {"defaults": 5}}, + ] + scenarios["settings"] = run({}, settings) + scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [ + {"method": "GET", "path": "/settings"}, + {"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}}, + {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}, + "headers": {"Authorization": "Bearer " + "k" * 40}}, + ]) + # ---- props, slots, health, status + reads = [ + {"method": "GET", "path": "/props"}, + {"method": "GET", "path": "/props?model=strata-test"}, + {"method": "GET", "path": "/props?model=alias-one"}, + {"method": "GET", "path": "/props?model=nope"}, + {"method": "GET", "path": "/props?model="}, + {"method": "GET", "path": "/slots"}, + {"method": "GET", "path": "/api/health"}, + {"method": "GET", "path": "/v1/status"}, + ] + scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads) + scenarios["reads_loaded_with_defaults"] = run( + {"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2, + "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8}, + "shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads) + scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads) + scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [ + {"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}]) + scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [ + {"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"}, + {"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"}, + {"method": "GET", "path": "/health"}]) + # ---- load / unload + lifecycle = [ + {"method": "POST", "path": "/unload"}, + {"method": "POST", "path": "/unload"}, + {"method": "GET", "path": "/slots"}, + {"method": "POST", "path": "/load"}, + {"method": "POST", "path": "/load"}, + {"method": "POST", "path": "/v1/unload", "body": {}}, + {"method": "POST", "path": "/v1/unload", "body": {}}, + {"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}}, + {"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}}, + {"method": "POST", "path": "/v1/load", "body": {}}, + {"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}}, + {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}}, + {"method": "POST", "path": "/v1/unload", "body": [1]}, + {"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}}, + {"method": "POST", "path": "/v1/unload", "body": {"model": None}}, + {"method": "GET", "path": "/props"}, + ] + scenarios["lifecycle"] = run({}, lifecycle) + scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [ + {"method": "POST", "path": "/v1/unload", "body": {}}, + {"method": "POST", "path": "/v1/load", "body": {}}, + {"method": "POST", "path": "/unload"}, + {"method": "POST", "path": "/load"}, + ]) + scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [ + {"method": "POST", "path": "/v1/load", "body": {}}, + {"method": "POST", "path": "/unload"}, + {"method": "POST", "path": "/load"}, + ]) + scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [ + {"method": "POST", "path": "/unload"}, + {"method": "POST", "path": "/v1/unload", "body": {}}, + {"method": "POST", "path": "/v1/unload", "body": {}, + "headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}}, + {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}}, + {"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}}, + ]) + write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)", + "scenarios": scenarios}) + + +# ------------------------------------------------------------------------------------------------ timings +def timings(): + from serve.server import ByteTokenizer, MockEngine, Service, request_timings + from serve.frontend import ChatTemplate + from pathlib import Path + + cases = [] + lasts = [ + {"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60}, + {"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0}, + {"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None}, + {"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3}, + {"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15}, + {"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200}, + {"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0}, + {"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1}, + ] + for last in lasts: + for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)): + cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated, + "timings": request_timings(prompt_tokens, generated, last)}) + cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})}) + aliases = [] + tok = ByteTokenizer() + for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]): + svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), + model_name="m") + try: + svc.set_aliases(value) + aliases.append({"input": value, "ok": svc.aliases}) + except ValueError as e: + aliases.append({"input": value, "error": str(e)}) + write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)", + "timings": cases, "aliases": aliases}, dest="policy") + + +# ------------------------------------------------------------------------------------------------ vision +def vision(): + import base64 + import tempfile + from pathlib import Path + from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages + from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision + + # base64 as Vision.load decodes data: URLs + b64 = [] + for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==", + "Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]: + try: + b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()}) + except Exception as e: # binascii.Error and friends + b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)}) + + sources = [ + {"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"}, + {"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}}, + {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}, + {"type": "image", "source": {"type": "base64", "data": "QQ=="}}, + {"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}}, + {"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None}, + ] + src = [{"part": part, "source": _image_source(part)} for part in sources] + + tok = ByteTokenizer() + + class FakeVision: + def __init__(self, counts): + self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-")) + + def encode(self, source): + path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve") + path.write_bytes(source.encode()) + return path, self.counts[source] + + template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") + prepared = [] + cases = [ + ([{"role": "user", "content": "hello"}], {}), + ([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}], + {"A": 3}), + ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}, + {"type": "image_url", "image_url": {"url": "B"}}, + {"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}), + ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]}, + {"role": "assistant", "content": "ok"}, + {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}], + {"A": 1, "C": 4}), + ([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"}, + {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), + ([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}), + ([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"}, + {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), + ] + for messages, counts in cases: + req = {"messages": messages} + norm, tools, kw = openai_to_messages(req) + prompt = template.render(norm, tools=tools, **kw) + ids_before = tok.encode(prompt, parse_special=True) + svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None) + entry = {"messages": messages, "counts": counts, "ids_before": ids_before, + "images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0], + "start": tok.encode(VISION_START, parse_special=True)[0], + "literal": tok.encode(IMAGE_PAD, parse_special=False)} + try: + ids, thinking, max_new = svc.prepare(norm, tools, kw, 10) + entry["ids_after"] = ids + entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None + except ValueError as e: + entry["error"] = str(e) + prepared.append(entry) + write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)", + "base64": b64, "sources": src, "prepare": prepared}, dest="policy") + + +SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface, + "timings": timings, "vision": vision} + + +def main(argv): + names = argv or list(SECTIONS) + for name in names: + SECTIONS[name]() + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/control-plane/tests/http_surface.rs b/control-plane/tests/http_surface.rs new file mode 100644 index 00000000..6d8c6adc --- /dev/null +++ b/control-plane/tests/http_surface.rs @@ -0,0 +1,330 @@ +//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`, +//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python +//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from +//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here +//! against the Rust router with a real worker supervisor and the mock engine. +//! +//! Deliberate differences, skipped in the comparison: the chat template text, the build/version +//! strings, wall-clock fields, JSON parser error wording, the extra `/v1/responses` dialect, and +//! `x-api-key` (the Rust server accepts it on the Messages routes only). + +use std::{path::PathBuf, sync::Arc, time::Duration}; + +use leleka_serving_policy::{cors::Cors, shared::sampling_defaults_from_config}; +use serde_json::{Value, json}; +use strata_control::{ + app::{AppState, router}, + lifecycle::Guard, + settings::Settings, + worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised}, +}; +use tokio::sync::{RwLock, mpsc, watch}; + +struct Harness { + base: String, + state: AppState, + stop: watch::Sender, + worker: tokio::task::JoinHandle<()>, + server: tokio::task::JoinHandle<()>, + dir: PathBuf, + _guards: Vec, +} + +impl Harness { + async fn start(name: &str, setup: &Value) -> Self { + let dir = std::env::temp_dir().join(format!("strata-http-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let context = setup["max_context"].as_u64().unwrap_or(4096); + let loaded = setup["loaded"].as_bool().unwrap_or(true); + let engine = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh"); + let config = WorkerConfig { + executable: engine.into_os_string(), + args: vec![ + "lifecycle".into(), + dir.to_string_lossy().into_owned(), + context.to_string(), + "--max-context".into(), + context.to_string(), + ], + startup_timeout: Duration::from_secs(10), + lazy: !loaded, + ..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 config_sampling = + sampling_defaults_from_config(setup.get("config_sampling").unwrap_or(&Value::Null)) + .unwrap(); + let settings = Settings::new(config_sampling); + if let Some(shared) = setup.get("shared") { + settings.set_shared(shared).unwrap(); + } + let strings = |key: &str| -> Vec { + setup[key] + .as_array() + .map(|a| a.iter().map(|v| v.as_str().unwrap().to_owned()).collect()) + .unwrap_or_default() + }; + let api_key = setup["api_key"] + .as_str() + .filter(|k| !k.is_empty()) + .map(|key| { + let path = dir.join("api-key"); + std::fs::write(&path, key).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) + .unwrap(); + } + Arc::new(strata_control::auth::ApiKey::from_file(&path).unwrap()) + }); + let state = AppState { + model: Some(setup["model"].as_str().unwrap_or("strata-test").to_owned()), + worker: status, + generation: Some(requests), + control: Some(control), + settings: Arc::new(settings), + aliases: Arc::new(strings("aliases")), + cors: Arc::new(Cors::new(strings("cors_origins"))), + trusted_origins: Arc::new(strings("trusted_origins")), + api_key, + ..Default::default() + }; + // The Python scenarios mark a request as running/queued through its status dict. + let mut guards = Vec::new(); + if let Some(status_setup) = setup.get("status") { + let busy = status_setup["busy"].as_bool().unwrap_or(false); + let queued = status_setup["queued"].as_u64().unwrap_or(0); + if busy { + state.worker.write().await.metrics.start(); + } + for _ in 0..(queued + u64::from(busy)) { + guards.push(state.lifecycle.generation()); + } + } + 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 wanted = if loaded { + WorkerState::Ready + } else { + WorkerState::Unloaded + }; + tokio::time::timeout(Duration::from_secs(10), async { + while state.worker.read().await.state != wanted { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("worker state"); + Self { + base, + state, + stop, + worker, + server, + dir, + _guards: guards, + } + } + + async fn finish(self) { + self.server.abort(); + self.stop.send(true).unwrap(); + let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await; + let _ = std::fs::remove_dir_all(self.dir); + } +} + +fn fixture() -> Value { + serde_json::from_str(include_str!("fixtures/golden/http_surface.json")).unwrap() +} + +/// Remove what is allowed to differ and return the rest. +fn normalized(path: &str, mut value: Value) -> Value { + let path = path.split('?').next().unwrap(); + let remove = |value: &mut Value, keys: &[&str]| { + if let Some(map) = value.as_object_mut() { + for key in keys { + map.remove(*key); + } + } + }; + match path { + // Both servers list the model and its aliases; the Python records carry llama-server extras. + "/v1/models" | "/models" => { + let reduced: Vec = value["data"] + .as_array() + .into_iter() + .flatten() + .map(|record| { + json!({"id": record["id"], "alias_of": record["alias_of"], + "aliases": record["aliases"], + "status": record["status"]["value"].as_str().unwrap_or("loaded")}) + }) + .collect(); + value = json!({"data": reduced}); + } + // `/health` stays the minimal liveness body of the existing smoke contract; `/api/health` + // carries the Python fields. + "/health" => value = json!({"status": value["status"]}), + "/props" => remove(&mut value, &["chat_template", "build_info", "model_path"]), + "/v1/status" | "/v1/load" | "/v1/unload" => { + remove( + &mut value, + &[ + "engine", + "started", + "uptime_s", + "machine", + "dialects", + "last_timings", + ], + ); + if let Some(activity) = value.get_mut("activity") { + remove(activity, &["last_request_at"]); + } + } + _ => {} + } + value +} + +/// The Python server forwards its JSON parser's message; the Rust parser words it differently. +fn is_parser_message(status: u64, body: &Value) -> bool { + status == 400 + && body["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("line 1 column") || m.contains("Expecting")) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_rust_surface_answers_like_the_python_server() { + let fixture = fixture(); + let scenarios = fixture["scenarios"].as_object().unwrap(); + assert!(scenarios.len() >= 17); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let mut compared = 0; + let mut skipped = 0; + for (name, scenario) in scenarios { + let harness = Harness::start(name, &scenario["setup"]).await; + for (index, step) in scenario["steps"].as_array().unwrap().iter().enumerate() { + let request = &step["request"]; + let method = request["method"].as_str().unwrap(); + let path = request["path"].as_str().unwrap(); + let context = format!("{name} step {index}: {method} {path}"); + let headers = request["headers"].as_object().cloned().unwrap_or_default(); + if headers.keys().any(|k| k.eq_ignore_ascii_case("x-api-key")) { + skipped += 1; + continue; + } + let mut builder = client.request( + reqwest::Method::from_bytes(method.as_bytes()).unwrap(), + format!("{}{path}", harness.base), + ); + let mut has_content_type = false; + for (key, value) in &headers { + has_content_type |= key.eq_ignore_ascii_case("content-type"); + builder = builder.header(key.as_str(), value.as_str().unwrap()); + } + match &request["body"] { + Value::Null => {} + Value::String(raw) => builder = builder.body(raw.clone()), + other => { + if !has_content_type { + builder = builder.header("content-type", "application/json"); + } + builder = builder.body(other.to_string()); + } + } + let response = builder + .send() + .await + .unwrap_or_else(|e| panic!("{context}: {e}")); + let status = response.status().as_u16(); + let got_headers: Vec<(String, String)> = response + .headers() + .iter() + .filter(|(k, _)| k.as_str().starts_with("access-control-") || k.as_str() == "vary") + .map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap().to_owned())) + .collect(); + let text = response.text().await.unwrap(); + let got_body: Value = if text.is_empty() { + Value::Null + } else { + serde_json::from_str(&text).unwrap_or(Value::String(text)) + }; + + assert_eq!( + u64::from(status), + step["status"].as_u64().unwrap(), + "{context}: {got_body}" + ); + let want_headers = step["headers"].as_object().unwrap(); + assert_eq!( + got_headers.len(), + want_headers.len(), + "{context}: {got_headers:?}" + ); + for (key, value) in want_headers { + assert!( + got_headers + .iter() + .any(|(k, v)| k == key && v == value.as_str().unwrap()), + "{context}: header {key}: {got_headers:?}" + ); + } + if status == 401 { + // The Rust server's authentication body is its own (OpenAI-style code and message). + assert_eq!( + got_body["error"]["type"], step["body"]["error"]["type"], + "{context}" + ); + } else if is_parser_message(step["status"].as_u64().unwrap(), &step["body"]) { + assert_eq!( + got_body["error"]["type"], step["body"]["error"]["type"], + "{context}" + ); + skipped += 1; + } else { + let want_path = path.split('?').next().unwrap(); + let want_body = normalized(want_path, step["body"].clone()); + let got_body = normalized(want_path, got_body); + assert_eq!(got_body, want_body, "{context}"); + } + let loaded = harness.state.worker.read().await.state == WorkerState::Ready; + assert_eq!( + loaded, + step["state"]["loaded"].as_bool().unwrap(), + "{context}: loaded" + ); + assert_eq!( + harness.state.settings.shared().to_json(), + step["state"]["shared"], + "{context}: shared settings" + ); + compared += 1; + } + harness.finish().await; + } + assert!(compared > 120, "{compared} compared, {skipped} skipped"); +} diff --git a/control-plane/tests/mcp_hub.rs b/control-plane/tests/mcp_hub.rs new file mode 100644 index 00000000..25ef696f --- /dev/null +++ b/control-plane/tests/mcp_hub.rs @@ -0,0 +1,444 @@ +//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`, +//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients, +//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation. +//! The tests are skipped (with a message) when `python3` is not installed. + +use std::{ + collections::BTreeMap, + io::{BufRead, BufReader}, + path::PathBuf, + process::{Child, Command, Stdio}, +}; + +use serde_json::{Map, Value, json}; +use strata_control::mcp::{Hub, McpError, Settings, servers_from, settings_from}; +use tokio::sync::watch; + +fn fake_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py") +} + +fn python() -> Option<&'static str> { + Command::new("python3") + .arg("--version") + .stdout(Stdio::null()) + .status() + .ok() + .filter(|s| s.success()) + .map(|_| "python3") +} + +fn stdio(args: &[&str], log: Option<&PathBuf>) -> Map { + let mut all = vec![fake_path().to_string_lossy().into_owned()]; + all.extend(args.iter().map(|a| (*a).to_owned())); + let mut config = json!({"command": "python3", "args": all}); + if let Some(log) = log { + config["env"] = json!({"FAKE_MCP_LOG": log}); + } + config.as_object().unwrap().clone() +} + +fn hub(servers: Vec<(&str, Map)>, settings: Settings) -> Hub { + Hub::new( + servers + .into_iter() + .map(|(n, c)| (n.to_owned(), c)) + .collect::>(), + settings, + ) +} + +fn names(status: &Value, server: &str) -> Vec { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == server) + .unwrap()["tools"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_owned()) + .collect() +} + +const TOOLS: [&str; 6] = ["echo", "fail", "sleep", "big", "die", "add"]; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stdio_servers_list_call_and_fail_like_the_python_hub() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let log = std::env::temp_dir().join(format!("strata-mcp-{}.jsonl", std::process::id())); + let _ = std::fs::remove_file(&log); + let settings = Settings { + timeout_s: 1.5, + max_result_chars: 1000, + ..Settings::default() + }; + let hub = hub( + vec![ + ("fake", stdio(&[], Some(&log))), + ("paged", stdio(&["--page", "4"], None)), + ("broken", stdio(&["--crash-at-start"], None)), + ( + "missing", + json!({"command": "strata-no-such-program"}) + .as_object() + .unwrap() + .clone(), + ), + ], + settings, + ); + hub.start().await; + let status = hub.status().await; + let by_name = |n: &str| -> Value { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == n) + .unwrap() + .clone() + }; + + // initialize + tools/list over every page + assert_eq!(by_name("fake")["status"], "ready"); + assert_eq!(by_name("fake")["transport"], "stdio"); + assert_eq!(by_name("fake")["info"]["name"], "fake"); + assert_eq!(by_name("fake")["info"]["protocol"], "2025-06-18"); + let want: Vec = TOOLS.iter().map(|t| format!("fake__{t}")).collect(); + assert_eq!(names(&status, "fake"), want); + assert_eq!( + names(&status, "paged"), + TOOLS + .iter() + .map(|t| format!("paged__{t}")) + .collect::>() + ); + assert_eq!(status["tools"], 12); + assert_eq!(status["settings"]["max_result_chars"], 1000); + + // servers that do not start are left out, with the reason + assert_eq!(by_name("broken")["status"], "failed"); + assert!( + by_name("broken")["error"] + .as_str() + .unwrap() + .contains("missing configuration"), + "{}", + by_name("broken") + ); + assert_eq!(by_name("missing")["status"], "failed"); + assert!( + by_name("missing")["error"] + .as_str() + .unwrap() + .contains("could not start") + ); + + // the tools in the chat template's form + let tools = hub.template_tools(&["paged__echo".to_owned()]).await; + let echo = tools.iter().find(|t| t["name"] == "fake__echo").unwrap(); + assert_eq!(echo["parameters"]["properties"]["text"]["type"], "string"); + assert_eq!(echo["description"], "Returns the text it is given."); + assert!(tools.iter().all(|t| t["name"] != "paged__echo")); + assert_eq!(tools.len(), 11); + + // calls + let r = hub + .call("fake__echo", json!({"text": "hello wörld"}), None) + .await + .unwrap(); + assert_eq!( + (r.ok, r.text.as_str(), r.server.as_deref(), r.tool.as_str()), + (true, "hello wörld", Some("fake"), "echo") + ); + assert_eq!( + hub.call("fake__add", json!({"a": 2, "b": 40}), None) + .await + .unwrap() + .text, + "42" + ); + let r = hub.call("fake__fail", json!({}), None).await.unwrap(); + assert!(!r.ok); + assert_eq!(r.text, "error: it failed on purpose"); + let r = hub.call("nobody__nothing", json!({}), None).await.unwrap(); + assert!( + !r.ok && r.text.starts_with("error: there is no tool"), + "{}", + r.text + ); + // arguments that are not an object are sent as {} + assert_eq!( + hub.call("fake__echo", json!("x"), None).await.unwrap().text, + "" + ); + // a JSON-RPC error from the server + let fake = hub.servers.iter().find(|s| s.name == "fake").unwrap(); + let error = fake + .call( + "no-such-tool", + json!({}), + std::time::Duration::from_secs(5), + None, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("unknown tool"), "{error}"); + + // a call that outlasts the timeout, then the server still answers + let started = std::time::Instant::now(); + let r = hub + .call("fake__sleep", json!({"seconds": 5}), None) + .await + .unwrap(); + assert!(started.elapsed().as_secs_f64() < 4.0); + assert!(!r.ok); + assert!(r.text.contains("timed out after 1.5 s"), "{}", r.text); + assert_eq!( + hub.call("fake__echo", json!({"text": "still here"}), None) + .await + .unwrap() + .text, + "still here" + ); + + // the result cap + let r = hub + .call("fake__big", json!({"n": 50000}), None) + .await + .unwrap(); + assert!(r.ok && r.truncated); + assert_eq!(r.chars, 50000); + assert!( + r.text + .starts_with(&format!("{}\n\n[... truncated", "y".repeat(1000))) + ); + assert!(r.text.contains("50,000 characters")); + assert!(r.text.chars().count() < 1200); + + // cancellation reaches the server as notifications/cancelled + let (stop, cancel) = watch::channel(false); + let canceller = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let _ = stop.send(true); + }); + let started = std::time::Instant::now(); + let outcome = hub + .call("fake__sleep", json!({"seconds": 1.2}), Some(cancel)) + .await; + assert_eq!(outcome.unwrap_err(), McpError::Cancelled); + assert!(started.elapsed().as_secs_f64() < 1.0); + canceller.await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + let seen = std::fs::read_to_string(&log).unwrap(); + assert!(seen.contains("\"cancelled\""), "{seen}"); + + hub.close().await; + let _ = std::fs::remove_file(&log); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_server_that_dies_mid_call_is_started_again_by_the_next_call() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let hub = hub( + vec![("solo", stdio(&[], None))], + Settings { + timeout_s: 5.0, + ..Settings::default() + }, + ); + hub.start().await; + let r = hub.call("solo__die", json!({}), None).await.unwrap(); + assert!(!r.ok); + assert!(r.text.contains("the server stopped"), "{}", r.text); + assert!(r.text.contains("dying on purpose"), "{}", r.text); + let status = hub.status().await; + assert_eq!(status["servers"][0]["status"], "stopped"); + assert_eq!( + status["tools"], 6, + "its tools stay: the next call restarts it" + ); + let r = hub + .call("solo__echo", json!({"text": "back"}), None) + .await + .unwrap(); + assert_eq!(r.text, "back"); + assert_eq!(hub.status().await["servers"][0]["status"], "ready"); + hub.close().await; +} + +struct HttpFake(Child); + +impl HttpFake { + fn start(port: u16) -> Self { + let mut child = Command::new("python3") + .arg(fake_path()) + .args(["--http", &port.to_string()]) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut line = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + assert!(line.contains("listening"), "{line}"); + Self(child) + } +} + +impl Drop for HttpFake { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn streamable_http_servers_answer_as_json_or_as_an_event_stream() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let port = { + let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + probe.local_addr().unwrap().port() + }; + let _server = HttpFake::start(port); + let hub = + hub( + vec![ + ( + "web", + json!({"url": format!("http://127.0.0.1:{port}/mcp"), "headers": {"X-Test": "1"}}) + .as_object() + .unwrap() + .clone(), + ), + ( + "down", + json!({"url": "http://127.0.0.1:9/mcp"}).as_object().unwrap().clone(), + ), + ], + Settings { + timeout_s: 1.5, + ..Settings::default() + }, + ); + hub.start().await; + let status = hub.status().await; + let server = |n: &str, status: &Value| -> Value { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == n) + .unwrap() + .clone() + }; + assert_eq!(server("web", &status)["transport"], "http"); + assert_eq!(server("web", &status)["status"], "ready", "{status}"); + assert_eq!(names(&status, "web").len(), 6); // paged, with the session id on every request + // tools/call answers as an event stream with a progress notification first + assert_eq!( + hub.call("web__echo", json!({"text": "over http"}), None) + .await + .unwrap() + .text, + "over http" + ); + assert_eq!( + hub.call("web__fail", json!({}), None).await.unwrap().text, + "error: it failed on purpose" + ); + let r = hub + .call("web__sleep", json!({"seconds": 4}), None) + .await + .unwrap(); + assert!(r.text.contains("timed out"), "{}", r.text); + let down = server("down", &hub.status().await); + assert_eq!(down["status"], "failed"); + assert!(down["error"].as_str().unwrap().contains("could not reach")); + hub.close().await; +} + +#[test] +fn config_accepts_both_spellings_and_checks_every_entry() { + let both = servers_from( + &json!({"a": {"command": "x"}, "off": {"url": "http://h/mcp", "disabled": true}}), + "config mcp_servers", + ) + .unwrap(); + assert_eq!(both.keys().collect::>(), ["a"]); + for (bad, why) in [ + (json!({"a": {}}), "needs \"command\""), + ( + json!({"a": {"command": "x", "args": "y"}}), + "\"args\" must be a list", + ), + ( + json!({"a": {"url": "http://h", "type": "sse"}}), + "old SSE transport", + ), + ( + json!({"a": {"url": "http://h", "headers": ["x"]}}), + "\"headers\" must be an object", + ), + ] { + let error = servers_from(&bad, "config mcpServers").unwrap_err(); + assert!(error.contains(why), "{error}"); + assert!( + error.starts_with("[strata] config mcpServers: MCP server 'a'"), + "{error}" + ); + } + assert!( + settings_from(&json!({"max_rounds": 0})) + .unwrap_err() + .contains("positive integer") + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_mcp_reports_the_hub_or_an_empty_list() { + use std::sync::Arc; + use strata_control::app::{AppState, router}; + + async fn get(state: AppState) -> Value { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/mcp", listener.local_addr().unwrap()); + let app = router(state); + let server = tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let text = reqwest::get(url).await.unwrap().text().await.unwrap(); + let answer: Value = serde_json::from_str(&text).unwrap(); + server.abort(); + answer + } + assert_eq!( + get(AppState::default()).await, + json!({"servers": [], "tools": 0}) + ); + let hub = Arc::new(hub( + vec![("broken", stdio(&["--crash-at-start"], None))], + Settings::default(), + )); + hub.start().await; + let state = AppState { + mcp: Some(hub.clone()), + ..Default::default() + }; + let answer = get(state).await; + assert_eq!(answer["servers"][0]["status"], "failed"); + assert_eq!(answer["tools"], 0); + assert_eq!(answer["settings"]["max_rounds"], 8); + hub.close().await; +} diff --git a/crates/serving-policy/Cargo.toml b/crates/serving-policy/Cargo.toml new file mode 100644 index 00000000..07963d95 --- /dev/null +++ b/crates/serving-policy/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "leleka-serving-policy" +version = "0.1.0" +description = "Pure Rust ports of the Original Strata serving-layer policies: shared settings, reasoning budget, stall watchdog, CORS, idle unload, logits stride, image positions, control vectors" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +leleka-sampler-ref = { path = "../sampler-ref" } +serde_json = "1" + +[lints] +workspace = true diff --git a/crates/serving-policy/oracle/build_oracle.sh b/crates/serving-policy/oracle/build_oracle.sh new file mode 100755 index 00000000..3391284e --- /dev/null +++ b/crates/serving-policy/oracle/build_oracle.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Rebuild the host oracles and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA. +# crates/serving-policy/oracle/build_oracle.sh [output_dir] +# The vision oracle compiles code EXTRACTED from the pinned generate.cpp (not retyped): the GENI embeddings / +# M-RoPE block and fnv1a, found by their text, so a change in the pinned source shows up as a failed extraction +# or a fixture diff. +set -eu +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../../.." && pwd) +engine="$root/engine/strata" +out=${1:-"$here/../tests/fixtures"} +work=${TMPDIR:-/tmp}/leleka_serving_oracle.$$ +mkdir -p "$work" "$out" +trap 'rm -rf "$work"' EXIT + +# ---- stride + watchdog +${CXX:-clang++} -std=c++17 -O1 -Wno-unused-function -I "$engine/include" "$here/gen_host_fixtures.cpp" -o "$work/host" +"$work/host" "$out/host_oracle.json" + +# ---- GENI embeddings block, verbatim +gen="$engine/src/program/generate.cpp" +awk '/^uint64_t fnv1a\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/fnv1a.inc" +awk '/if \(geni \|\| !mrope_identity\) \{/ {p=1} /tr\("positions built"/ {p=0} p {print}' "$gen" > "$work/generate_block.inc" +[ -s "$work/fnv1a.inc" ] && [ -s "$work/generate_block.inc" ] || { echo "could not extract the GENI block from $gen" >&2; exit 1; } +grep -q 'bad embeddings file' "$work/generate_block.inc" || { echo "extracted block is not the GENI embeddings code" >&2; exit 1; } +${CXX:-clang++} -std=c++20 -O1 -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ + "$here/gen_vision_fixtures.cpp" -o "$work/vision" +"$work/vision" "$out/vision_oracle.json" + +# ---- control vector loader, verbatim +awk '/^bool load_control_vectors\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/load_control_vectors.inc" +[ -s "$work/load_control_vectors.inc" ] && grep -q 'no direction. tensors' "$work/load_control_vectors.inc" \ + || { echo "could not extract load_control_vectors from $gen" >&2; exit 1; } +${CXX:-clang++} -std=c++20 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ + "$here/gen_cvec_fixtures.cpp" -o "$work/cvec" +"$work/cvec" "$out/cvec_oracle.json" diff --git a/crates/serving-policy/oracle/gen_cvec_fixtures.cpp b/crates/serving-policy/oracle/gen_cvec_fixtures.cpp new file mode 100644 index 00000000..2338d434 --- /dev/null +++ b/crates/serving-policy/oracle/gen_cvec_fixtures.cpp @@ -0,0 +1,206 @@ +// Host oracle for control vectors: `load_control_vectors` of src/program/generate.cpp INCLUDED VERBATIM +// (extracted by build_oracle.sh) with the Options / ModelGeometry / cvec_upload it needs stubbed, driven over +// small GGUF control-vector files this harness writes. The tables it would upload (dir, s) are recorded as +// raw float bits, so the Rust loader can be compared bit for bit (-ffp-contract=off pins the host arithmetic). +// +// Usage: gen_cvec_fixtures OUT.json +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "strata/artifact/gguf_reader.hpp" + +struct Options { + std::vector> cvec_files; + int cvec_first = -1, cvec_last = -1; + int cvec_mode = 1; + int cvec_single = -1; +}; +namespace strata::core { struct ModelGeometry { int64_t n_layers = 0, n_embd = 0, hc = 0; }; } +namespace strata::kernels { +struct Captured { std::vector dir, s; int mode = 0, first = 0, last = 0; bool called = false; }; +Captured g_up; +bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, int64_t, int64_t, + std::string&) { + g_up = {dir, s, mode, first, last, true}; + return true; +} +} // namespace strata::kernels + +#include "load_control_vectors.inc" + +// ---- a minimal GGUF v3 writer --------------------------------------------------------------------------------- +struct Tensor { std::string name; uint32_t type; std::vector dims; std::vector data; }; +static void w32(std::string& s, uint32_t v) { s.append((const char*) &v, 4); } +static void w64(std::string& s, uint64_t v) { s.append((const char*) &v, 8); } +static void wstr(std::string& s, const std::string& v) { w64(s, v.size()); s += v; } +static std::string gguf(const std::vector>& kv, const std::vector& ts) { + std::string s = "GGUF"; + w32(s, 3); + w64(s, ts.size()); + w64(s, kv.size()); + for (const auto& [k, v] : kv) { wstr(s, k); w32(s, 8); wstr(s, v); } + uint64_t offset = 0; + std::vector offsets; + for (const Tensor& t : ts) { + wstr(s, t.name); + w32(s, (uint32_t) t.dims.size()); + for (uint64_t d : t.dims) w64(s, d); + w32(s, t.type); + w64(s, offset); + offsets.push_back(offset); + offset += (t.data.size() * 4 + 31) / 32 * 32; + } + while (s.size() % 32) s += '\0'; + for (const Tensor& t : ts) { + s.append((const char*) t.data.data(), t.data.size() * 4); + while (s.size() % 32) s += '\0'; + } + return s; +} +static std::string hex(const std::string& s) { + static const char* d = "0123456789abcdef"; + std::string o; + for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } + return o; +} +static std::string jstr(const std::string& s) { + std::string o = "\""; + for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } + return o + "\""; +} +static Tensor dir(const std::string& name, int64_t n, float seed, float step = 0.37f) { + Tensor t{name, 0, {(uint64_t) n}, {}}; + for (int64_t j = 0; j < n; ++j) t.data.push_back(seed + step * (float) j - (j % 3 == 0 ? 0.5f : 0.0f)); + return t; +} + +struct Case { + std::string name; + std::vector> files; // index into blobs, scale + int first, last, mode, single; +}; + +int main(int argc, char** argv) { + if (argc < 2) return 2; + constexpr int64_t L = 6, N = 5, HC = 2; + const std::string base = std::string(std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp") + "/strata_cvec_oracle_" + std::to_string((long long) getpid()); + const std::vector> good = {{"general.architecture", "controlvector"}, {"controlvector.model_hint", "qwen4exp"}}; + std::vector blobs = { + // 0: directions for layers 1, 2, 4 (3 and 5 have none) + gguf(good, {dir("direction.1", N, 1.0f), dir("direction.2", N, -0.5f), dir("direction.4", N, 2.0f)}), + // 1: directions for 2, 3 + gguf(good, {dir("direction.2", N, 0.25f, 0.11f), dir("direction.3", N, 3.0f)}), + // 2: not a control vector + gguf({{"general.architecture", "llama"}}, {dir("direction.1", N, 1.0f)}), + // 3: no direction tensors + gguf(good, {dir("other.1", N, 1.0f)}), + // 4: wrong size + gguf(good, {dir("direction.1", N + 1, 1.0f)}), + // 5: wrong type (F16 id 1) + gguf(good, {Tensor{"direction.1", 1, {(uint64_t) N}, std::vector(3, 0.0f)}}), + // 6: layer 0, past the model, a non-number, a padded number: ignored / strtol semantics + gguf(good, {dir("direction.0", N, 9.0f), dir("direction.6", N, 9.0f), dir("direction.99", N, 9.0f), dir("direction.abc", N, 9.0f), + dir("direction.03", N, 0.75f)}), + // 7: all zeros + gguf(good, {Tensor{"direction.1", 0, {(uint64_t) N}, std::vector(N, 0.0f)}, Tensor{"direction.2", 0, {(uint64_t) N}, std::vector(N, 0.0f)}}), + // 8: another model's hint (a warning on stderr only) + gguf({{"general.architecture", "controlvector"}, {"controlvector.model_hint", "llama"}}, {dir("direction.1", N, 1.0f)}), + // 9: no hint at all + gguf({{"general.architecture", "controlvector"}}, {dir("direction.5", N, -1.0f)}), + }; + std::vector cases = { + {"add, one file, default range", {{"0", 1.0f}}, -1, -1, 1, -1}, + {"add, two files scaled and summed", {{"0", 0.5f}, {"1", -2.0f}}, -1, -1, 1, -1}, + {"project, one file", {{"0", 1.0f}}, -1, -1, 0, -1}, + {"project, two files", {{"0", 1.5f}, {"1", 1.0f}}, -1, -1, 0, -1}, + {"add, layer range 2..3", {{"0", 1.0f}, {"1", 1.0f}}, 2, 3, 1, -1}, + {"add, range past the model", {{"0", 1.0f}}, 1, 99, 1, -1}, + {"project, range first only", {{"0", 1.0f}}, 3, -1, 0, -1}, + {"project single:2", {{"0", 1.0f}}, -1, -1, 0, 2}, + {"project single:2 over a range", {{"0", 1.0f}, {"1", 1.0f}}, 2, 5, 0, 2}, + {"add ignores single", {{"0", 1.0f}}, -1, -1, 1, 2}, + {"project single without a direction", {{"0", 1.0f}}, -1, -1, 0, 3}, + {"project single past the model", {{"0", 1.0f}}, -1, -1, 0, 6}, + {"scale zero adds nothing but still counts as found", {{"0", 0.0f}}, -1, -1, 1, -1}, + {"scale zero in project mode steers nothing", {{"0", 0.0f}}, -1, -1, 0, -1}, + {"layers 0 / past-model / non-numeric ignored, 03 is layer 3", {{"6", 1.0f}}, -1, -1, 1, -1}, + {"not a control vector", {{"2", 1.0f}}, -1, -1, 1, -1}, + {"no direction tensors", {{"3", 1.0f}}, -1, -1, 1, -1}, + {"wrong tensor size", {{"4", 1.0f}}, -1, -1, 1, -1}, + {"wrong tensor type", {{"5", 1.0f}}, -1, -1, 1, -1}, + {"all-zero directions in project mode", {{"7", 1.0f}}, -1, -1, 0, -1}, + {"all-zero directions in add mode", {{"7", 1.0f}}, -1, -1, 1, -1}, + {"another model's hint still loads", {{"8", 1.0f}}, -1, -1, 1, -1}, + {"no hint", {{"9", 1.0f}}, -1, -1, 1, -1}, + {"second file bad", {{"0", 1.0f}, {"3", 1.0f}}, -1, -1, 1, -1}, + {"no steered layer in the range", {{"0", 1.0f}}, 5, 5, 1, -1}, + }; + std::FILE* f = std::fopen(argv[1], "w"); + if (!f) return 2; + std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp load_control_vectors (verbatim) over GGUF files written by gen_cvec_fixtures.cpp\",\n" + " \"n_layers\": %lld, \"n_embd\": %lld, \"hc\": %lld,\n \"blobs\": [", (long long) L, (long long) N, (long long) HC); + for (size_t i = 0; i < blobs.size(); ++i) std::fprintf(f, "%s\"%s\"", i ? "," : "", hex(blobs[i]).c_str()); + std::fprintf(f, "],\n \"cases\": ["); + bool first = true; + for (const Case& c : cases) { + Options o; + o.cvec_first = c.first; + o.cvec_last = c.last; + o.cvec_mode = c.mode; + o.cvec_single = c.single; + std::vector> used; + for (size_t k = 0; k < c.files.size(); ++k) { + const int blob = std::atoi(c.files[k].first.c_str()); + const std::string path = base + "_" + std::to_string(blob) + ".gguf"; + std::FILE* w = std::fopen(path.c_str(), "wb"); + std::fwrite(blobs[(size_t) blob].data(), 1, blobs[(size_t) blob].size(), w); + std::fclose(w); + o.cvec_files.push_back({path, c.files[k].second}); + used.push_back({blob, c.files[k].second}); + } + strata::core::ModelGeometry g; + g.n_layers = L; g.n_embd = N; g.hc = HC; + strata::kernels::g_up = {}; + std::string summary, err; + const bool ok = load_control_vectors(o, g, summary, err); + // the temp paths carry this process's id: name the files by their blob instead + for (size_t k = 0; k < used.size(); ++k) { + const std::string path = o.cvec_files[k].first, label = "FILE" + std::to_string(used[k].first); + for (size_t at = err.find(path); at != std::string::npos; at = err.find(path)) err.replace(at, path.size(), label); + } + std::fprintf(f, "%s\n {\"name\": %s, \"files\": [", first ? "" : ",", jstr(c.name).c_str()); + for (size_t k = 0; k < used.size(); ++k) { + uint32_t bits; std::memcpy(&bits, &used[k].second, 4); + std::fprintf(f, "%s[%d, %u]", k ? "," : "", used[k].first, bits); + } + std::fprintf(f, "], \"first\": %d, \"last\": %d, \"mode\": \"%s\", \"single\": %d, \"ok\": %s, \"err\": %s, \"summary\": %s", + c.first, c.last, c.mode == 0 ? "project" : "add", c.single, ok ? "true" : "false", jstr(err).c_str(), jstr(summary).c_str()); + if (ok) { + std::fprintf(f, ", \"up\": {\"mode\": %d, \"first\": %d, \"last\": %d, \"dir_bits\": [", strata::kernels::g_up.mode, + strata::kernels::g_up.first, strata::kernels::g_up.last); + for (size_t i = 0; i < strata::kernels::g_up.dir.size(); ++i) { + uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.dir[i], 4); + std::fprintf(f, "%s%u", i ? "," : "", bits); + } + std::fprintf(f, "], \"s_bits\": ["); + for (size_t i = 0; i < strata::kernels::g_up.s.size(); ++i) { + uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.s[i], 4); + std::fprintf(f, "%s%u", i ? "," : "", bits); + } + std::fprintf(f, "]}"); + } + std::fprintf(f, "}"); + first = false; + for (const auto& [p, s] : o.cvec_files) { (void) s; std::remove(p.c_str()); } + } + std::fprintf(f, "\n ]\n}\n"); + std::fclose(f); + return 0; +} diff --git a/crates/serving-policy/oracle/gen_host_fixtures.cpp b/crates/serving-policy/oracle/gen_host_fixtures.cpp new file mode 100644 index 00000000..44f6675b --- /dev/null +++ b/crates/serving-policy/oracle/gen_host_fixtures.cpp @@ -0,0 +1,113 @@ +// Host oracle for the serving policies that are plain C++ in the Original (no CUDA): +// * logits_selection.hpp - compiled UNMODIFIED from engine/strata/include; +// * the stall watchdog: core/progress.hpp (Progress, progress_now_ms) compiled unmodified, and the +// poll body of the watchdog thread in src/program/generate.cpp (the lines marked below) driven by an +// injected clock instead of sleep_for(1 s). +// Output: tests/fixtures/host_oracle.json (stride + watchdog scenarios). Usage: gen_host_fixtures OUT.json +#include +#include +#include +#include + +#include "strata/core/progress.hpp" +#include "strata/program/logits_selection.hpp" + +namespace ls = strata::program::logits_selection; + +static std::string esc(const std::string& s) { + std::string o; + for (char c : s) { + if (c == '"' || c == '\\') o += '\\'; + o += c; + } + return o; +} + +// ---- the watchdog thread of generate.cpp, with the clock and the counters passed in -------------------------- +struct Dog { + int limit; + uint64_t last; + uint64_t ticks_at; + int64_t since_ms; + Dog(int limit_s, int64_t now_ms, uint64_t beats, uint64_t ticks) + : limit(limit_s), last(beats), ticks_at(ticks), since_ms(now_ms) {} + // Returns -1 healthy, otherwise the "layers served since the last finished step" the report prints. + // The statements below are generate.cpp's loop body (lines "const uint64_t b = ..." to "std::abort()"). + int64_t poll(int64_t now_ms, uint64_t beats, bool busy, uint64_t ticks) { + if (limit <= 0) return -1; // `if (limit > 0) std::thread(...)`: no thread at all + const uint64_t b = beats; + if (!busy || b != last) { last = b; ticks_at = ticks; since_ms = now_ms; return -1; } + if (now_ms - since_ms < (int64_t) limit * 1000) return -1; + return (int64_t) (ticks - ticks_at); // stall_report(stderr, p.ticks.load() - ticks_at); abort + } +}; + +int main(int argc, char** argv) { + if (argc < 2) return 2; + std::FILE* f = std::fopen(argv[1], "w"); + if (!f) return 2; + std::fprintf(f, "{\n \"source\": \"include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)\",\n"); + + // ---- stride + std::fprintf(f, " \"parse\": ["); + const char* texts[] = {"1", "2", "128", "9223372036854775807", "9223372036854775808", "0", "00", "007", "-1", "+1", + " 1", "1 ", "1x", "x", "", "1.5", "99999999999999999999", "12345678901234567890"}; + bool first = true; + for (const char* t : texts) { + int64_t v = -777; + const bool ok = ls::parse_stride(t, v); + std::fprintf(f, "%s\n {\"text\": \"%s\", \"ok\": %s, \"value\": %lld}", first ? "" : ",", esc(t).c_str(), ok ? "true" : "false", + (long long) (ok ? v : -777)); + first = false; + } + std::fprintf(f, "\n ],\n \"selected\": ["); + first = true; + const int64_t totals[] = {-1, 0, 1, 2, 5, 9, 10, 11, 64, 100}; + const int64_t strides[] = {-1, 0, 1, 2, 3, 4, 7, 10, 64, 1000}; + for (int64_t total : totals) + for (int64_t stride : strides) { + std::fprintf(f, "%s\n {\"total\": %lld, \"stride\": %lld, \"rows\": %lld, \"kept\": [", first ? "" : ",", (long long) total, + (long long) stride, (long long) ls::row_count(total, stride)); + bool kf = true; + for (int64_t p = -2; p < total + 2; ++p) + if (ls::selected(p, total, stride)) { + std::fprintf(f, "%s%lld", kf ? "" : ",", (long long) p); + kf = false; + } + std::fprintf(f, "]}"); + first = false; + } + std::fprintf(f, "\n ],\n"); + + // ---- watchdog scenarios: [limit_s, [[dt_ms, beats, busy, ticks], ...]] -> verdicts + struct Step { int64_t at_ms; uint64_t beats; bool busy; uint64_t ticks; }; + struct Scenario { int limit; std::vector steps; }; + std::vector sc = { + {3, {{1000, 0, true, 0}, {2000, 0, true, 5}, {2999, 0, true, 9}, {3000, 0, true, 9}, {4000, 0, true, 9}}}, + {2, {{1900, 1, true, 40}, {3800, 1, true, 40}, {3900, 1, true, 40}, {4000, 2, true, 41}, {5999, 2, true, 41}, {6000, 2, true, 80}}}, + {2, {{1000, 0, false, 1}, {2000, 0, false, 2}, {3000, 0, false, 3}, {100000, 0, true, 100}, {101999, 0, true, 100}, {102000, 0, true, 100}}}, + {0, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, + {-5, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, + {1, {{1000, 0, true, 3}, {2000, 0, true, 3}, {3000, 1, true, 3}, {3999, 1, true, 7}, {4000, 1, true, 7}}}, + {60, {{59000, 0, true, 0}, {59999, 0, true, 0}, {60000, 0, true, 12}, {61000, 5, false, 12}, {200000, 5, true, 12}}}, + }; + std::fprintf(f, " \"watchdog\": ["); + first = true; + for (const Scenario& s : sc) { + Dog dog(s.limit, 0, 0, 0); + std::fprintf(f, "%s\n {\"limit_s\": %d, \"steps\": [", first ? "" : ",", s.limit); + bool sf = true; + for (const Step& st : s.steps) { + const int64_t v = dog.poll(st.at_ms, st.beats, st.busy, st.ticks); + std::fprintf(f, "%s\n {\"at_ms\": %lld, \"beats\": %llu, \"busy\": %s, \"ticks\": %llu, \"layers_since\": %lld}", sf ? "" : ",", + (long long) st.at_ms, (unsigned long long) st.beats, st.busy ? "true" : "false", (unsigned long long) st.ticks, + (long long) v); + sf = false; + } + std::fprintf(f, "\n ]}"); + first = false; + } + std::fprintf(f, "\n ]\n}\n"); + std::fclose(f); + return 0; +} diff --git a/crates/serving-policy/oracle/gen_vision_fixtures.cpp b/crates/serving-policy/oracle/gen_vision_fixtures.cpp new file mode 100644 index 00000000..335a36e0 --- /dev/null +++ b/crates/serving-policy/oracle/gen_vision_fixtures.cpp @@ -0,0 +1,145 @@ +// Host oracle for the image-embeddings path of `--serve` (GENI): the SVE1 record reader and the M-RoPE +// position table of src/program/generate.cpp. +// +// The block between "if (geni || !mrope_identity) {" and "tr(\"positions built\"" is INCLUDED VERBATIM from the +// pinned generate.cpp (extracted by build_oracle.sh, see generate_block.inc) - not retyped - and so is `fnv1a`. +// Everything around it (the variables the block reads, a CUDA-free `put` target) is declared here. +// +// Usage: gen_vision_fixtures OUT.json (writes its scratch embedding files to $TMPDIR) +#include +#include +#include +#include +#include +#include +#include +#include + +#include "strata/core/conversation_cache.hpp" + +using ImgKey = strata::core::ConversationImageKey; + +#include "fnv1a.inc" + +struct Geometry { int64_t n_embd; }; + +struct Result { + std::string ve; + std::vector table; + std::vector row_offset; // float offset into img_rows per token, -1 = none + std::vector imgs; +}; + +constexpr int64_t kImagePad = 248056; + +static Result run(bool geni, const std::vector& ids, const std::string& emb_path, int64_t n_embd, int64_t cells, + bool mrope_identity) { + Geometry g{n_embd}; + const int64_t n = (int64_t) ids.size(); + std::vector req_imgs; + std::vector mrope_host((size_t) cells * 3); + for (int64_t c = 0; c < cells; ++c) mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c; + std::vector img_rows; + std::vector row_ptr; + Result out; + { + // ---------------------------------------------------------------- verbatim from generate.cpp +#include "generate_block.inc" + out.ve = ve; + } // closes the `if (geni || !mrope_identity) {` that the block opens + } + out.table = mrope_host; + out.imgs = req_imgs; + for (const float* p : row_ptr) out.row_offset.push_back(p ? (int64_t) (p - img_rows.data()) : -1); + return out; +} + +// ---- SVE1 file builders --------------------------------------------------------------------------------------- +static void put_i32(std::string& s, int32_t v) { s.append((const char*) &v, 4); } +static std::string image(int32_t n, int32_t nx, int32_t ny, int32_t width, float seed, int32_t magic = 0x31455653) { + std::string s; + for (int32_t v : {magic, n, nx, ny, width}) put_i32(s, v); + for (int32_t i = 0; i < n * width; ++i) { + const float f = seed + (float) i * 0.5f; + s.append((const char*) &f, 4); + } + return s; +} + +static std::string hex(const std::string& s) { + static const char* d = "0123456789abcdef"; + std::string o; + for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } + return o; +} + +static std::string jstr(const std::string& s) { + std::string o = "\""; + for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } + return o + "\""; +} + +int main(int argc, char** argv) { + if (argc < 2) return 2; + const char* tmp = std::getenv("TMPDIR"); + const std::string scratch = std::string(tmp ? tmp : "/tmp") + "/strata_sve_oracle_" + std::to_string((long long) getpid()) + ".sve"; + std::FILE* f = std::fopen(argv[1], "w"); + if (!f) return 2; + std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)\",\n \"cases\": ["); + + struct Case { const char* name; bool geni; std::vector ids; std::string file; int64_t n_embd; int64_t cells; bool identity; }; + const int64_t P = kImagePad; + const std::string i1 = image(1, 1, 1, 4, 1.0f), i6 = image(6, 3, 2, 4, 10.0f), i8 = image(8, 2, 4, 4, 20.0f), i25 = image(25, 5, 5, 4, 30.0f); + std::vector cases = { + {"text identity after an image request", false, {5, 6, 7}, "", 4, 32, false}, + {"text only with no file", true, {5, 6, 7, 8}, "", 4, 32, true}, + {"one 1x1 image", true, {1, 2, P, 3, 4}, i1, 4, 32, true}, + {"one 3x2 image", true, {1, P, P, P, P, P, P, 9, 10}, i6, 4, 40, true}, + {"one 2x4 image (tall: ny > nx)", true, {7, P, P, P, P, P, P, P, P, 8}, i8, 4, 40, true}, + {"two images in order", true, {1, P, P, P, P, P, P, 2, P, P, P, P, P, P, P, P, 3}, i6 + i8, 4, 64, true}, + {"5x5 image then text", true, {1, 2, 3, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, 4, 5}, i25, 4, 64, true}, + {"adjacent images", true, {P, P, P, P, P, P, P, P, P, P, P, P, P, P, 1}, i6 + i8, 4, 40, true}, + {"image at the start", true, {P, 4}, i1, 4, 16, true}, + {"identity request after (not geni, not identity)", false, {1, 2}, "", 4, 16, false}, + // errors + {"prompt ends in an image", true, {1, P, P, P, P, P, P}, i6, 4, 32, true}, + {"more images in the prompt than the file", true, {1, P, 2, P, 3}, i1, 4, 32, true}, + {"more images in the file than the prompt", true, {1, P, 2, 3}, i1 + i1, 4, 32, true}, + {"fewer image_pad tokens than rows", true, {1, P, P, 2, 3, 4, 5, 6, 7}, i6, 4, 32, true}, + {"bad magic", true, {1, P, 2}, image(1, 1, 1, 4, 1.0f, 0x12345678), 4, 32, true}, + {"wrong width", true, {1, P, 2}, image(1, 1, 1, 8, 1.0f), 4, 32, true}, + {"grid does not multiply", true, {1, P, 2}, image(6, 3, 3, 4, 1.0f), 4, 32, true}, + {"zero rows", true, {1, P, 2}, image(0, 0, 0, 4, 1.0f), 4, 32, true}, + {"short header", true, {1, P, 2}, i1.substr(0, 12), 4, 32, true}, + {"short data", true, {1, P, 2}, i1.substr(0, i1.size() - 3), 4, 32, true}, + {"second record truncated", true, {1, P, 2, P, 3}, i1 + i1.substr(0, 25), 4, 32, true}, + }; + bool first = true; + for (const Case& c : cases) { + if (!c.file.empty() || c.geni) { + std::FILE* w = std::fopen(scratch.c_str(), "wb"); + std::fwrite(c.file.data(), 1, c.file.size(), w); + std::fclose(w); + } + // "no file": point at a path that does not exist + const std::string path = c.file.empty() && c.geni ? std::string("/nonexistent/embeddings.sve") : scratch; + const Result r = run(c.geni, c.ids, path, c.n_embd, c.cells, c.identity); + std::fprintf(f, "%s\n {\"name\": %s, \"geni\": %s, \"mrope_identity\": %s, \"n_embd\": %lld, \"cells\": %lld, \"file_hex\": \"%s\", \"ids\": [", + first ? "" : ",", jstr(c.name).c_str(), c.geni ? "true" : "false", c.identity ? "true" : "false", + (long long) c.n_embd, (long long) c.cells, hex(c.file).c_str()); + for (size_t i = 0; i < c.ids.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) c.ids[i]); + std::fprintf(f, "], \"ve\": %s, \"table\": [", jstr(r.ve).c_str()); + for (size_t i = 0; i < r.table.size(); ++i) std::fprintf(f, "%s%d", i ? "," : "", r.table[i]); + std::fprintf(f, "], \"row_offset\": ["); + for (size_t i = 0; i < r.row_offset.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) r.row_offset[i]); + std::fprintf(f, "], \"imgs\": ["); + for (size_t i = 0; i < r.imgs.size(); ++i) + std::fprintf(f, "%s[%lld,\"%016llx\"]", i ? "," : "", (long long) r.imgs[i].start, (unsigned long long) r.imgs[i].hash); + std::fprintf(f, "]}"); + first = false; + } + std::remove(scratch.c_str()); + std::fprintf(f, "\n ]\n}\n"); + std::fclose(f); + return 0; +} diff --git a/crates/serving-policy/src/cors.rs b/crates/serving-policy/src/cors.rs new file mode 100644 index 00000000..fdf6b1b8 --- /dev/null +++ b/crates/serving-policy/src/cors.rs @@ -0,0 +1,286 @@ +//! CORS and the "own page" guard (issue #321 of the Original): `Handler._cors`, `do_OPTIONS`, +//! `Handler._own_page` and `origins_of` in `serve/server.py`. +//! +//! * `cors_origins`: browser pages of these origins may call `/v1/*` (`"*"` = any page, only +//! sensible with an API key). Empty = no CORS headers at all. +//! * `trusted_origins`: origins that count as Strata's own page for `/settings`, `/v1/load` and +//! MCP tools (the web app behind a reverse proxy); never a wildcard. +//! * Only JSON from an origin equal to the server's own `Host`, or a trusted one, may change +//! settings or load/unload the model: a form post or a "simple" cross-site request cannot send +//! JSON without a CORS preflight, which this server never grants for those paths. + +use serde_json::Value; + +use crate::shared::py_str_repr; + +/// The allow-headers answer when the preflight asks for nothing specific. +pub const DEFAULT_ALLOW_HEADERS: &str = + "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta"; + +/// `origins_of`: a config's origin list (`"https://chat.example.com"` or a list of them), +/// `scheme://host[:port]` without a path; `"*"` only where `wildcard` allows it. `Err` is the +/// message that stops the start. +pub fn origins_of(value: &Value, key: &str, wildcard: bool) -> Result, String> { + let items: Vec<&Value> = match value { + Value::Null => return Ok(Vec::new()), + Value::String(s) if s.is_empty() => return Ok(Vec::new()), + Value::Array(a) if a.is_empty() => return Ok(Vec::new()), + Value::String(_) => vec![value], + Value::Array(a) => a.iter().collect(), + _ => { + return Err(format!( + "[strata] {key}: expected an origin or a list of origins" + )); + } + }; + let mut out = Vec::new(); + for item in items { + let Some(text) = item.as_str() else { + return Err(format!( + "[strata] {key}: expected an origin or a list of origins" + )); + }; + let origin = text.trim().trim_end_matches('/'); + if origin == "*" && wildcard { + out.push(origin.to_owned()); + continue; + } + let valid = origin.split_once("://").is_some_and(|(scheme, rest)| { + matches!(scheme, "http" | "https") + && !rest.is_empty() + && !rest.contains('/') + && !rest.contains('*') + }); + if !valid { + return Err(format!( + "[strata] {key}: {} is not an origin like https://chat.example.com{}", + py_str_repr(origin), + if wildcard { "" } else { " (no wildcards here)" } + )); + } + out.push(origin.to_owned()); + } + Ok(out) +} + +/// The origins allowed to call `/v1/*` from a browser. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Cors { + origins: Vec, +} + +impl Cors { + pub fn new(origins: Vec) -> Self { + Self { origins } + } + + pub fn is_enabled(&self) -> bool { + !self.origins.is_empty() + } + + pub fn origins(&self) -> &[String] { + &self.origins + } + + /// The response headers for `request_path` (query string allowed) when the page at `origin` + /// asks; empty when CORS does not apply. `asked_headers` is the preflight's + /// `Access-Control-Request-Headers`. + pub fn headers( + &self, + request_path: &str, + origin: Option<&str>, + asked_headers: Option<&str>, + ) -> Vec<(&'static str, String)> { + let path = request_path.split('?').next().unwrap_or(""); + if self.origins.is_empty() || !path.starts_with("/v1/") { + return Vec::new(); + } + let origin = origin.unwrap_or("").trim_end_matches('/'); + let mut out = Vec::new(); + let allow = if self.origins.iter().any(|o| o == "*") { + "*".to_owned() + } else if !origin.is_empty() && self.origins.iter().any(|o| o == origin) { + out.push(("Vary", "Origin".to_owned())); + origin.to_owned() + } else { + return Vec::new(); + }; + out.push(("Access-Control-Allow-Origin", allow)); + out.push(( + "Access-Control-Allow-Methods", + "GET, POST, OPTIONS".to_owned(), + )); + // "*" does not cover Authorization, so echo what the preflight asked for. + out.push(( + "Access-Control-Allow-Headers", + match asked_headers { + Some(asked) if !asked.is_empty() => asked.to_owned(), + _ => DEFAULT_ALLOW_HEADERS.to_owned(), + }, + )); + out.push(("Access-Control-Max-Age", "600".to_owned())); + out + } +} + +/// Why a request was refused by the own-page guard. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OwnPageError { + /// 415 `send application/json`. + NotJson, + /// 403, with the action in the message. + ForeignOrigin(String), +} + +impl OwnPageError { + pub fn status(&self) -> u16 { + match self { + Self::NotJson => 415, + Self::ForeignOrigin(_) => 403, + } + } + + pub fn message(&self) -> String { + match self { + Self::NotJson => "send application/json".to_owned(), + Self::ForeignOrigin(what) => format!( + "{what} only from Strata's own page (or an origin in the config's trusted_origins)" + ), + } + } +} + +/// `Handler._own_page(what)`: JSON only, and no foreign `Origin`. The origin must be this server's +/// own address (the `Host` header) or an origin the config trusts. Proxy headers +/// (`X-Forwarded-*`, `CF-*`) prove nothing about the page that sent the request, so they open +/// nothing. +pub fn own_page( + what: &str, + content_type: Option<&str>, + origin: Option<&str>, + host: Option<&str>, + trusted_origins: &[String], +) -> Result<(), OwnPageError> { + if !content_type.unwrap_or("").starts_with("application/json") { + return Err(OwnPageError::NotJson); + } + let origin = origin.unwrap_or("").trim_end_matches('/'); + if !origin.is_empty() { + let authority = origin.split_once("://").map_or(origin, |(_, rest)| rest); + if authority != host.unwrap_or("") && !trusted_origins.iter().any(|o| o == origin) { + return Err(OwnPageError::ForeignOrigin(what.to_owned())); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn origin_lists_follow_the_originals_grammar() { + assert_eq!(origins_of(&json!(null), "k", true), Ok(vec![])); + assert_eq!(origins_of(&json!(""), "k", true), Ok(vec![])); + assert_eq!(origins_of(&json!([]), "k", true), Ok(vec![])); + assert_eq!( + origins_of(&json!("https://a.example/"), "k", false), + Ok(vec!["https://a.example".into()]) + ); + assert_eq!( + origins_of(&json!([" http://localhost:3000 ", "*"]), "k", true), + Ok(vec!["http://localhost:3000".into(), "*".into()]) + ); + for bad in [ + json!("ftp://x"), + json!("https://a.example/path"), + json!("https://*.example"), + json!("example.com"), + json!("https://"), + json!(5), + json!([1]), + json!({"a": 1}), + ] { + assert!(origins_of(&bad, "k", true).is_err(), "{bad}"); + } + assert!( + origins_of(&json!("*"), "trusted_origins", false) + .unwrap_err() + .ends_with("(no wildcards here)") + ); + } + + #[test] + fn cors_headers_only_for_listed_origins_on_v1_paths() { + let cors = Cors::new(vec!["https://a.example".into()]); + assert!( + cors.headers("/health", Some("https://a.example"), None) + .is_empty() + ); + assert!( + cors.headers("/v1", Some("https://a.example"), None) + .is_empty() + ); + assert!( + cors.headers("/v1/models", Some("https://b.example"), None) + .is_empty() + ); + assert!(cors.headers("/v1/models", None, None).is_empty()); + let headers = cors.headers("/v1/models?x=1", Some("https://a.example/"), Some("x-foo")); + assert_eq!(headers[0], ("Vary", "Origin".into())); + assert!(headers.contains(&("Access-Control-Allow-Origin", "https://a.example".into()))); + assert!(headers.contains(&("Access-Control-Allow-Headers", "x-foo".into()))); + let any = Cors::new(vec!["*".into()]); + let headers = any.headers("/v1/chat/completions", None, None); + assert!(headers.contains(&("Access-Control-Allow-Origin", "*".into()))); + assert!(headers.contains(&("Access-Control-Allow-Headers", DEFAULT_ALLOW_HEADERS.into()))); + assert!(!headers.iter().any(|(name, _)| *name == "Vary")); + assert!( + Cors::default() + .headers("/v1/models", Some("https://a.example"), None) + .is_empty() + ); + } + + #[test] + fn own_page_requires_json_and_a_local_or_trusted_origin() { + let trusted = vec!["https://strata.example.com".to_owned()]; + let ok = |ct, origin, host| own_page("x", ct, origin, host, &trusted); + assert_eq!( + ok(Some("application/json"), None, Some("localhost:8080")), + Ok(()) + ); + assert_eq!( + ok( + Some("application/json; charset=utf-8"), + Some("http://localhost:8080"), + Some("localhost:8080") + ), + Ok(()) + ); + assert_eq!( + ok( + Some("application/json"), + Some("https://strata.example.com/"), + Some("localhost:8080") + ), + Ok(()) + ); + assert_eq!( + ok(Some("text/plain"), None, None), + Err(OwnPageError::NotJson) + ); + assert_eq!(ok(None, None, None), Err(OwnPageError::NotJson)); + let foreign = ok( + Some("application/json"), + Some("https://evil.example"), + Some("localhost:8080"), + ); + assert_eq!(foreign.as_ref().unwrap_err().status(), 403); + assert_eq!( + foreign.unwrap_err().message(), + "x only from Strata's own page (or an origin in the config's trusted_origins)" + ); + } +} diff --git a/crates/serving-policy/src/cvec.rs b/crates/serving-policy/src/cvec.rs new file mode 100644 index 00000000..187e836a --- /dev/null +++ b/crates/serving-policy/src/cvec.rs @@ -0,0 +1,571 @@ +//! Control vectors (`include/strata/kernels/cvec.hpp`, `load_control_vectors` in +//! `src/program/generate.cpp`): a steering direction added to, or projected out of, the residual +//! stream after chosen layers, loaded from llama.cpp control-vector GGUF files. +//! +//! This is the host side: reading the files and building the `dir` / `s` tables the kernel +//! uploads. The tables are bit-exact against the Original's loader (golden fixture compiled from +//! the verbatim function, `oracle/gen_cvec_fixtures.cpp`). The device side +//! (`h <- h + d` / `h <- h - s (h.v) v`) is a kernel and stays with the engine. +//! +//! * `add`: `d_l` = sum over files of `scale * direction.`; the table row is `d_l`, `s_l = 1`. +//! * `project`: `v_l = d_l / |d_l|`, `s_l = |d_l|` (norm in `f64`). +//! * layer 0 has no direction; `direction.` with `l >= n_layers` is ignored (as in llama.cpp). +//! * `single:L` (project mode only) uses layer `L`'s direction at every steered layer. + +/// The tensor facts the loader needs. +#[derive(Clone, Debug, PartialEq)] +pub struct VectorTensor { + pub name: String, + /// ggml type id (0 = F32). + pub kind: u32, + pub elements: u64, + /// Present for F32 tensors. + pub values: Vec, +} + +/// A parsed control-vector GGUF. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VectorFile { + pub architecture: Option, + pub model_hint: Option, + pub tensors: Vec, +} + +struct Cursor<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Cursor<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + let end = self + .at + .checked_add(n) + .filter(|end| *end <= self.bytes.len()) + .ok_or("GGUF file is truncated")?; + let slice = &self.bytes[self.at..end]; + self.at = end; + Ok(slice) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes( + self.take(4)?.try_into().expect("4 bytes"), + )) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes( + self.take(8)?.try_into().expect("8 bytes"), + )) + } + + fn string(&mut self) -> Result { + let len = usize::try_from(self.u64()?).map_err(|_| "GGUF string is too long")?; + if len > 1 << 24 { + return Err("GGUF string is too long".into()); + } + Ok(String::from_utf8_lossy(self.take(len)?).into_owned()) + } +} + +/// Skip (or read, for strings) one metadata value of type `kind`. +fn value(cursor: &mut Cursor<'_>, kind: u32) -> Result, String> { + let fixed = |bytes: usize, cursor: &mut Cursor<'_>| cursor.take(bytes).map(|_| None); + match kind { + 0 | 1 | 7 => fixed(1, cursor), + 2 | 3 => fixed(2, cursor), + 4..=6 => fixed(4, cursor), + 10..=12 => fixed(8, cursor), + 8 => cursor.string().map(Some), + 9 => { + let element = cursor.u32()?; + let count = cursor.u64()?; + if count > 1 << 28 { + return Err("GGUF array is too long".into()); + } + for _ in 0..count { + value(cursor, element)?; + } + Ok(None) + } + other => Err(format!("unknown GGUF metadata type {other}")), + } +} + +/// Parse a GGUF v2/v3 file held in memory (little endian). +pub fn parse_gguf(bytes: &[u8]) -> Result { + let mut cursor = Cursor { bytes, at: 0 }; + if cursor.take(4)? != b"GGUF" { + return Err("not a GGUF file".into()); + } + let version = cursor.u32()?; + if !(2..=3).contains(&version) { + return Err(format!("unsupported GGUF version {version}")); + } + let tensors = cursor.u64()?; + let entries = cursor.u64()?; + if tensors > 1 << 20 || entries > 1 << 20 { + return Err("GGUF header counts are implausible".into()); + } + let mut file = VectorFile::default(); + let mut alignment = 32u64; + for _ in 0..entries { + let key = cursor.string()?; + let kind = cursor.u32()?; + if key == "general.alignment" && kind == 4 { + alignment = u64::from(cursor.u32()?).max(1); + continue; + } + let text = value(&mut cursor, kind)?; + match key.as_str() { + "general.architecture" => file.architecture = text, + "controlvector.model_hint" => file.model_hint = text, + _ => {} + } + } + struct Info { + name: String, + kind: u32, + elements: u64, + offset: u64, + } + let mut infos = Vec::new(); + for _ in 0..tensors { + let name = cursor.string()?; + let dims = cursor.u32()?; + if dims > 8 { + return Err("GGUF tensor has too many dimensions".into()); + } + let mut elements = 1u64; + for _ in 0..dims { + elements = elements + .checked_mul(cursor.u64()?) + .ok_or("GGUF tensor is too large")?; + } + let kind = cursor.u32()?; + let offset = cursor.u64()?; + infos.push(Info { + name, + kind, + elements, + offset, + }); + } + let data_start = (cursor.at as u64).div_ceil(alignment) * alignment; + for info in infos { + let mut values = Vec::new(); + if info.kind == 0 { + let begin = data_start + .checked_add(info.offset) + .ok_or("GGUF tensor offset overflows")?; + let len = info + .elements + .checked_mul(4) + .ok_or("GGUF tensor is too large")?; + let end = begin + .checked_add(len) + .ok_or("GGUF tensor offset overflows")?; + let data = usize::try_from(begin) + .ok() + .zip(usize::try_from(end).ok()) + .and_then(|(b, e)| bytes.get(b..e)) + .ok_or("GGUF tensor data is truncated")?; + values = data + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + } + file.tensors.push(VectorTensor { + name: info.name, + kind: info.kind, + elements: info.elements, + values, + }); + } + Ok(file) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Project, + Add, +} + +/// The loader's options (`--cvec-mode`, `--cvec-dir`, `--control-vector-layer-range`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Options { + /// `<= 0`: layer 1 (layer 0 has no direction). + pub first: i32, + /// `<= 0` or `>= n_layers`: the last layer. + pub last: i32, + pub mode: Mode, + /// `single:L` (project mode): layer L's direction at every steered layer; `-1` = per layer. + pub single: i32, +} + +impl Default for Options { + fn default() -> Self { + Self { + first: -1, + last: -1, + mode: Mode::Add, + single: -1, + } + } +} + +/// What the kernel uploads. +#[derive(Clone, Debug, PartialEq)] +pub struct Tables { + /// `n_layers * n_embd`: project = the unit `v_l`, add = `d_l`; zero rows elsewhere. + pub dir: Vec, + /// `n_layers`: project = `s_l`, add = 1, 0 = the layer is not steered. + pub s: Vec, + pub mode: Mode, + pub first: i32, + pub last: i32, + pub steered: usize, + /// What `INFO` reports: `project:1-47`, `add:2-3`, `project:1-47:single12`. + pub summary: String, + /// Non-fatal remarks (a vector made for another model). + pub warnings: Vec, +} + +/// C `strtol(s, nullptr, 10)`: whitespace, sign, digits; no digits is 0. +fn strtol(text: &str) -> i64 { + let trimmed = text.trim_start(); + let (negative, digits) = match trimmed.as_bytes().first() { + Some(b'-') => (true, &trimmed[1..]), + Some(b'+') => (false, &trimmed[1..]), + _ => (false, trimmed), + }; + let mut value: i64 = 0; + for byte in digits.bytes().take_while(u8::is_ascii_digit) { + value = value + .saturating_mul(10) + .saturating_add(i64::from(byte - b'0')); + } + if negative { -value } else { value } +} + +/// `load_control_vectors`: `files` are `(label for messages, parsed file, scale)`. +pub fn build_tables( + files: &[(String, VectorFile, f32)], + n_layers: usize, + n_embd: usize, + options: Options, +) -> Result { + let (layers, width) = (n_layers as i64, n_embd as i64); + let mut data = vec![0.0f32; n_layers * n_embd]; + let mut have = vec![false; n_layers]; + let mut warnings = Vec::new(); + for (label, file, scale) in files { + if file.architecture.as_deref() != Some("controlvector") { + return Err(format!( + "{label}: not a control vector GGUF (general.architecture is not 'controlvector')" + )); + } + if let Some(hint) = file.model_hint.as_deref() + && hint != "qwen4exp" + { + warnings.push(format!("{label} was made for '{hint}', not qwen4exp")); + } + let mut found = 0; + for tensor in &file.tensors { + let Some(rest) = tensor.name.strip_prefix("direction.") else { + continue; + }; + let layer = strtol(rest); + if layer < 1 || layer >= layers { + continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp + } + if tensor.kind != 0 || tensor.elements != n_embd as u64 { + return Err(format!("{label}: {} must be {width} f32", tensor.name)); + } + let row = &mut data[layer as usize * n_embd..(layer as usize + 1) * n_embd]; + for (target, source) in row.iter_mut().zip(&tensor.values) { + *target += scale * source; + } + have[layer as usize] = true; + found += 1; + } + if found == 0 { + return Err(format!("{label}: no direction. tensors")); + } + } + let first = if options.first <= 0 { 1 } else { options.first }; + let last = if options.last <= 0 || i64::from(options.last) >= layers { + (layers - 1) as i32 + } else { + options.last + }; + let single = if options.mode == Mode::Project { + options.single + } else { + -1 + }; + if single >= 0 && (i64::from(single) >= layers || !have[single as usize]) { + return Err(format!( + "--cvec-dir single:{single}: the vector has no direction for that layer" + )); + } + let mut dir = vec![0.0f32; n_layers * n_embd]; + let mut s = vec![0.0f32; n_layers]; + let mut steered = 0; + for layer in first..=last { + let source = if single >= 0 { single } else { layer } as usize; + if source >= n_layers || !have[source] || layer as usize >= n_layers { + continue; + } + let d = &data[source * n_embd..(source + 1) * n_embd]; + let target = layer as usize; + match options.mode { + Mode::Project => { + let norm = d + .iter() + .map(|v| f64::from(*v) * f64::from(*v)) + .sum::() + .sqrt(); + if norm <= 0.0 { + continue; + } + s[target] = norm as f32; + for (j, value) in d.iter().enumerate() { + dir[target * n_embd + j] = (f64::from(*value) / norm) as f32; + } + } + Mode::Add => { + s[target] = 1.0; + dir[target * n_embd..(target + 1) * n_embd].copy_from_slice(d); + } + } + steered += 1; + } + if steered == 0 { + return Err(format!( + "the control vector has no direction in layers {first}..{last}" + )); + } + let summary = format!( + "{}:{first}-{last}{}", + if options.mode == Mode::Project { + "project" + } else { + "add" + }, + if single >= 0 { + format!(":single{single}") + } else { + String::new() + } + ); + Ok(Tables { + dir, + s, + mode: options.mode, + first, + last, + steered, + summary, + warnings, + }) +} + +/// `--control-vector-scaled FILE:SCALE[,FILE:SCALE...]`: the last colon splits, so a path with a +/// drive letter keeps it. `Err` is the engine's usage message. +pub fn parse_scaled_list(text: &str) -> Result, String> { + let mut out = Vec::new(); + for item in text.split(',') { + let bad = || format!("--control-vector-scaled: expected FILE:SCALE, got '{item}'"); + let (path, scale) = item.rsplit_once(':').ok_or_else(bad)?; + if path.is_empty() { + return Err(bad()); + } + out.push((path.to_owned(), strtof_exact(scale).ok_or_else(bad)?)); + } + Ok(out) +} + +/// `strtof` that must consume the whole text and find at least one character. +fn strtof_exact(text: &str) -> Option { + if text.is_empty() || text.trim() != text { + return None; + } + text.parse::().ok() +} + +/// `--cvec-dir per-layer|single:L`. +pub fn parse_dir(text: &str) -> Result { + if text == "per-layer" { + return Ok(-1); + } + if let Some(rest) = text.strip_prefix("single:") { + return Ok(i32::try_from(strtol(rest)).unwrap_or(0)); + } + Err(format!("--cvec-dir: per-layer or single:L, got '{text}'")) +} + +/// `--cvec-mode add|project`. +pub fn parse_mode(text: &str) -> Result { + match text { + "project" => Ok(Mode::Project), + "add" => Ok(Mode::Add), + other => Err(format!("--cvec-mode: add or project, got '{other}'")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vector(layers: &[(u32, [f32; 3])]) -> VectorFile { + VectorFile { + architecture: Some("controlvector".into()), + model_hint: Some("qwen4exp".into()), + tensors: layers + .iter() + .map(|(layer, values)| VectorTensor { + name: format!("direction.{layer}"), + kind: 0, + elements: 3, + values: values.to_vec(), + }) + .collect(), + } + } + + #[test] + fn add_mode_sums_scaled_files() { + let a = vector(&[(1, [1.0, 2.0, 3.0])]); + let b = vector(&[(1, [10.0, 10.0, 10.0]), (2, [1.0, 0.0, 0.0])]); + let tables = build_tables( + &[("a".into(), a, 1.0), ("b".into(), b, 0.5)], + 4, + 3, + Options::default(), + ) + .unwrap(); + assert_eq!(&tables.dir[3..6], &[6.0, 7.0, 8.0]); + assert_eq!(&tables.dir[6..9], &[0.5, 0.0, 0.0]); + assert_eq!(tables.s, vec![0.0, 1.0, 1.0, 0.0]); + assert_eq!(tables.summary, "add:1-3"); + assert_eq!(tables.steered, 2); + } + + #[test] + fn project_mode_stores_the_unit_vector_and_its_norm() { + let tables = build_tables( + &[("a".into(), vector(&[(1, [3.0, 4.0, 0.0])]), 1.0)], + 2, + 3, + Options { + mode: Mode::Project, + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(tables.s[1], 5.0); + assert_eq!(&tables.dir[3..6], &[0.6f32, 0.8f32, 0.0]); + assert_eq!(tables.summary, "project:1-1"); + } + + #[test] + fn loader_errors_use_the_engines_words() { + let ok = vector(&[(1, [1.0, 1.0, 1.0])]); + let not_cvec = VectorFile { + architecture: Some("llama".into()), + ..ok.clone() + }; + assert_eq!( + build_tables(&[("f".into(), not_cvec, 1.0)], 4, 3, Options::default()).unwrap_err(), + "f: not a control vector GGUF (general.architecture is not 'controlvector')" + ); + let none = VectorFile { + tensors: vec![], + ..ok.clone() + }; + assert_eq!( + build_tables(&[("f".into(), none, 1.0)], 4, 3, Options::default()).unwrap_err(), + "f: no direction. tensors" + ); + assert_eq!( + build_tables( + &[("f".into(), ok.clone(), 1.0)], + 4, + 3, + Options { + first: 3, + last: 3, + ..Default::default() + } + ) + .unwrap_err(), + "the control vector has no direction in layers 3..3" + ); + assert_eq!( + build_tables( + &[("f".into(), ok, 1.0)], + 4, + 3, + Options { + mode: Mode::Project, + single: 2, + ..Default::default() + } + ) + .unwrap_err(), + "--cvec-dir single:2: the vector has no direction for that layer" + ); + } + + #[test] + fn cli_values_parse_like_the_engine() { + assert_eq!( + parse_scaled_list("a.gguf:0.5,C:\\v.gguf:-2").unwrap(), + vec![("a.gguf".to_owned(), 0.5), ("C:\\v.gguf".to_owned(), -2.0)] + ); + for bad in ["a.gguf", ":1", "a.gguf:", "a.gguf:x", "a.gguf:1x"] { + assert!(parse_scaled_list(bad).is_err(), "{bad}"); + } + assert_eq!(parse_dir("per-layer"), Ok(-1)); + assert_eq!(parse_dir("single:12"), Ok(12)); + assert!(parse_dir("every").is_err()); + assert_eq!(parse_mode("project"), Ok(Mode::Project)); + assert!(parse_mode("x").is_err()); + } + + #[test] + fn gguf_files_round_trip_through_the_parser() { + let mut file = b"GGUF".to_vec(); + file.extend_from_slice(&3u32.to_le_bytes()); + file.extend_from_slice(&1u64.to_le_bytes()); + file.extend_from_slice(&1u64.to_le_bytes()); + let key = b"general.architecture"; + file.extend_from_slice(&(key.len() as u64).to_le_bytes()); + file.extend_from_slice(key); + file.extend_from_slice(&8u32.to_le_bytes()); + file.extend_from_slice(&13u64.to_le_bytes()); + file.extend_from_slice(b"controlvector"); + let name = b"direction.1"; + file.extend_from_slice(&(name.len() as u64).to_le_bytes()); + file.extend_from_slice(name); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&2u64.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&0u64.to_le_bytes()); + while !file.len().is_multiple_of(32) { + file.push(0); + } + file.extend_from_slice(&1.5f32.to_le_bytes()); + file.extend_from_slice(&(-2.0f32).to_le_bytes()); + let parsed = parse_gguf(&file).unwrap(); + assert_eq!(parsed.architecture.as_deref(), Some("controlvector")); + assert_eq!(parsed.tensors[0].values, vec![1.5, -2.0]); + assert!(parse_gguf(&file[..file.len() - 1]).is_err()); + assert!(parse_gguf(b"GGUX").is_err()); + assert!(parse_gguf(&[]).is_err()); + } +} diff --git a/crates/serving-policy/src/fixed.rs b/crates/serving-policy/src/fixed.rs new file mode 100644 index 00000000..260dced1 --- /dev/null +++ b/crates/serving-policy/src/fixed.rs @@ -0,0 +1,258 @@ +//! Sampling fields in the forms the in-process runtime protocol carries them: JSON request +//! fields -> [`RequestSampling`] -> fixed point ([`FixedPoint`], thousandths / millionths). +//! +//! The runtime gRPC contract (`runtime.proto` `GenerateRequest`) and `backend-api` +//! `SamplingOptions` keep requests `Eq` by using integers. A float that a client wrote with more +//! fractional digits than the field carries is *refused*, never rounded: rounding would silently +//! change the distribution the client asked for. + +use leleka_sampler_ref::params::{FixedPoint, RequestSampling, SamplingError}; +use serde_json::{Map, Value}; + +/// JSON keys of the sampling fields. +pub const SAMPLING_KEYS: [&str; 9] = [ + "temperature", + "top_p", + "top_k", + "min_p", + "repetition_penalty", + "frequency_penalty", + "presence_penalty", + "penalty_last_n", + "seed", +]; + +fn err(field: &'static str, expected: &'static str) -> SamplingError { + SamplingError { field, expected } +} + +/// `round(value * scale)` when `result / scale` is exactly `value` again. +fn exact(value: f64, scale: f64) -> Option { + let scaled = (value * scale).round(); + if !scaled.is_finite() || scaled.abs() > 9.0e15 { + return None; + } + let candidate = scaled as i64; + (candidate as f64 / scale == value).then_some(candidate) +} + +const PRECISION_MILLI: &str = "a decimal with at most 3 fractional digits"; +const PRECISION_MICRO: &str = "a decimal with at most 6 fractional digits"; + +/// Validate and convert. Order of checks: the request contract first +/// ([`RequestSampling::validate`]), then representability. +pub fn to_fixed_point(sampling: &RequestSampling) -> Result { + sampling.validate()?; + let micro_u32 = + |field: &'static str, value: Option| -> Result, SamplingError> { + value + .map(|v| { + exact(v, 1_000_000.0) + .and_then(|n| u32::try_from(n).ok()) + .ok_or_else(|| err(field, PRECISION_MICRO)) + }) + .transpose() + }; + let micro_i32 = + |field: &'static str, value: Option| -> Result, SamplingError> { + value + .map(|v| { + exact(v, 1_000_000.0) + .and_then(|n| i32::try_from(n).ok()) + .ok_or_else(|| err(field, PRECISION_MICRO)) + }) + .transpose() + }; + let temperature_milli = match sampling.temperature { + None => 0, + Some(t) => exact(t, 1000.0) + .and_then(|n| u32::try_from(n).ok()) + .ok_or_else(|| err("temperature", PRECISION_MILLI))?, + }; + Ok(FixedPoint { + temperature_milli, + top_p_micro: micro_u32("top_p", sampling.top_p)?, + top_k: sampling.top_k.map(|k| u32::try_from(k).unwrap_or(u32::MAX)), + min_p_micro: micro_u32("min_p", sampling.min_p)?, + repetition_penalty_micro: micro_u32("repetition_penalty", sampling.repetition_penalty)?, + frequency_penalty_micro: micro_i32("frequency_penalty", sampling.frequency_penalty)?, + presence_penalty_micro: micro_i32("presence_penalty", sampling.presence_penalty)?, + penalty_last_n: sampling + .penalty_last_n + .map(|n| { + u32::try_from(n).map_err(|_| err("penalty_last_n", "an integer in 0..=2147483647")) + }) + .transpose()?, + seed: sampling.seed, + }) +} + +fn number(object: &Map, key: &'static str) -> Result, SamplingError> { + match object.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Number(n)) => n + .as_f64() + .map(Some) + .ok_or_else(|| err(key, "a finite number")), + Some(_) => Err(err(key, "a number")), + } +} + +fn integer(object: &Map, key: &'static str) -> Result, SamplingError> { + match object.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Number(n)) => n.as_i64().map(Some).ok_or_else(|| err(key, "an integer")), + Some(_) => Err(err(key, "an integer")), + } +} + +/// Read the sampling fields of a JSON request object (unrelated keys are ignored here; the caller +/// owns the allow-list of the rest of its request). Types are strict: `top_k` must be an integer, +/// `seed` an unsigned integer. Ranges are checked by [`RequestSampling::validate`]. +pub fn sampling_from_object(object: &Map) -> Result { + let seed = match object.get("seed") { + None | Some(Value::Null) => None, + Some(Value::Number(n)) => Some( + n.as_u64() + .ok_or_else(|| err("seed", "an unsigned integer"))?, + ), + Some(_) => return Err(err("seed", "an unsigned integer")), + }; + let sampling = RequestSampling { + temperature: number(object, "temperature")?, + top_p: number(object, "top_p")?, + top_k: integer(object, "top_k")?, + min_p: number(object, "min_p")?, + repetition_penalty: number(object, "repetition_penalty")?, + frequency_penalty: number(object, "frequency_penalty")?, + presence_penalty: number(object, "presence_penalty")?, + penalty_last_n: integer(object, "penalty_last_n")?, + seed, + }; + sampling.validate()?; + Ok(sampling) +} + +/// A short stable error code for a rejected field (gateway error bodies carry codes, not prose). +pub fn error_code(error: &SamplingError) -> &'static str { + match error.field { + "temperature" => "invalid_temperature", + "top_p" => "invalid_top_p", + "top_k" => "invalid_top_k", + "min_p" => "invalid_min_p", + "repetition_penalty" => "invalid_repetition_penalty", + "frequency_penalty" => "invalid_frequency_penalty", + "presence_penalty" => "invalid_presence_penalty", + "penalty_last_n" => "invalid_penalty_last_n", + "seed" => "invalid_seed", + _ => "invalid_sampling", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn obj(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + #[test] + fn decimals_round_trip_through_fixed_point() { + for t in [0.0, 0.1, 0.7, 0.8, 1.0, 1.5, 2.0, 0.123, 0.001] { + let s = RequestSampling { + temperature: Some(t), + ..Default::default() + }; + let f = to_fixed_point(&s).unwrap(); + assert_eq!( + RequestSampling::from_fixed_point(&f).temperature, + Some(t), + "{t}" + ); + } + let s = RequestSampling { + temperature: Some(0.6), + top_p: Some(0.95), + top_k: Some(20), + min_p: Some(0.05), + repetition_penalty: Some(1.05), + frequency_penalty: Some(-0.5), + presence_penalty: Some(0.25), + penalty_last_n: Some(256), + seed: Some(99), + }; + assert_eq!( + RequestSampling::from_fixed_point(&to_fixed_point(&s).unwrap()), + s + ); + } + + #[test] + fn values_finer_than_the_wire_are_refused_not_rounded() { + for s in [ + RequestSampling { + temperature: Some(0.1234), + ..Default::default() + }, + RequestSampling { + top_p: Some(0.9999999), + ..Default::default() + }, + RequestSampling { + frequency_penalty: Some(0.0000001), + ..Default::default() + }, + ] { + assert!(to_fixed_point(&s).is_err(), "{s:?}"); + } + } + + #[test] + fn out_of_contract_values_are_refused() { + for s in [ + RequestSampling { + temperature: Some(2.001), + ..Default::default() + }, + RequestSampling { + top_p: Some(1.5), + ..Default::default() + }, + RequestSampling { + penalty_last_n: Some(-1), + ..Default::default() + }, + ] { + assert!(to_fixed_point(&s).is_err()); + } + } + + #[test] + fn json_fields_are_read_strictly() { + let s = sampling_from_object(&obj(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.5, "penalty_last_n": 64, "seed": 7, + "model": "ignored", "temperature_null": null + }))) + .unwrap(); + assert_eq!(s.top_k, Some(40)); + assert_eq!(s.seed, Some(7)); + for bad in [ + json!({"top_k": 1.5}), + json!({"top_k": "5"}), + json!({"seed": -1}), + json!({"seed": 1.5}), + json!({"temperature": "hot"}), + json!({"temperature": 3}), + json!({"min_p": 2}), + ] { + assert!(sampling_from_object(&obj(bad.clone())).is_err(), "{bad}"); + } + assert_eq!( + sampling_from_object(&obj(json!({"temperature": null}))).unwrap(), + RequestSampling::default() + ); + } +} diff --git a/crates/serving-policy/src/idle.rs b/crates/serving-policy/src/idle.rs new file mode 100644 index 00000000..d8e454af --- /dev/null +++ b/crates/serving-policy/src/idle.rs @@ -0,0 +1,120 @@ +//! Idle unload (`Service.unload` / `start_idle_unload` of `serve/server.py`): give the GPU back +//! after a period without requests so other programs can use it; the next request loads the model +//! again. Pure decision logic with injected time; the supervisor in `control-plane` performs the +//! actual stop. + +/// `--idle-unload SECONDS` polling interval: `max(1, min(30, idle / 4))` seconds. +pub fn poll_interval_s(idle_s: f64) -> f64 { + (idle_s / 4.0).clamp(0.0, 30.0).max(1.0) +} + +/// The outcome strings `/unload` answers with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + Unloaded, + NotLoaded, + Busy, + Unsupported, +} + +impl Outcome { + pub fn as_str(self) -> &'static str { + match self { + Self::Unloaded => "unloaded", + Self::NotLoaded => "not loaded", + Self::Busy => "busy", + Self::Unsupported => "unsupported", + } + } +} + +/// What the supervisor knows when asked to unload. +#[derive(Clone, Copy, Debug)] +pub struct Situation { + /// The engine can be unloaded at all (`hasattr(engine, "unload")`). + pub supported: bool, + /// The engine process is running. + pub loaded: bool, + /// A request is running or waiting. + pub busy: bool, + /// Seconds since a request last started or finished (or since start). + pub idle_s: f64, +} + +/// `Service.unload(idle_for)`: `idle_for = None` is the explicit `/unload`, `Some(n)` the idle +/// thread (only if no request ran within the last `n` seconds). +pub fn decide(situation: Situation, idle_for: Option) -> Outcome { + if !situation.supported { + return Outcome::Unsupported; + } + if !situation.loaded { + return Outcome::NotLoaded; + } + if situation.busy { + return Outcome::Busy; + } + if idle_for.is_some_and(|limit| situation.idle_s < limit) { + return Outcome::Busy; + } + Outcome::Unloaded +} + +#[cfg(test)] +mod tests { + use super::*; + + fn situation(loaded: bool, busy: bool, idle_s: f64) -> Situation { + Situation { + supported: true, + loaded, + busy, + idle_s, + } + } + + #[test] + fn poll_interval_follows_the_originals_formula() { + assert_eq!(poll_interval_s(1.0), 1.0); + assert_eq!(poll_interval_s(8.0), 2.0); + assert_eq!(poll_interval_s(60.0), 15.0); + assert_eq!(poll_interval_s(600.0), 30.0); + assert_eq!(poll_interval_s(0.5), 1.0); + } + + #[test] + fn explicit_unload_ignores_idle_time_but_not_a_running_request() { + assert_eq!(decide(situation(true, false, 0.0), None), Outcome::Unloaded); + assert_eq!(decide(situation(true, true, 99.0), None), Outcome::Busy); + assert_eq!( + decide(situation(false, false, 99.0), None), + Outcome::NotLoaded + ); + assert_eq!( + decide( + Situation { + supported: false, + ..situation(true, false, 0.0) + }, + None + ), + Outcome::Unsupported + ); + } + + #[test] + fn the_idle_thread_waits_for_the_full_idle_period() { + assert_eq!( + decide(situation(true, false, 59.9), Some(60.0)), + Outcome::Busy + ); + assert_eq!( + decide(situation(true, false, 60.0), Some(60.0)), + Outcome::Unloaded + ); + assert_eq!( + decide(situation(false, false, 1e9), Some(60.0)), + Outcome::NotLoaded + ); + assert_eq!(Outcome::NotLoaded.as_str(), "not loaded"); + } +} diff --git a/crates/serving-policy/src/lib.rs b/crates/serving-policy/src/lib.rs new file mode 100644 index 00000000..5f7464cd --- /dev/null +++ b/crates/serving-policy/src/lib.rs @@ -0,0 +1,16 @@ +//! Pure Rust ports of the Original Strata serving-layer policies (`engine/strata/serve/*.py` and the +//! host-side parts of `src/program/generate.cpp`). No I/O, no async runtime, no `unsafe`. +//! +//! Each module cites the Original code it transcribes and is tested against fixtures produced by running +//! that code (see `control-plane/tests/golden/gen_goldens.py` and `oracle/`). + +pub mod cors; +pub mod cvec; +pub mod fixed; +pub mod idle; +pub mod reasoning; +pub mod shared; +pub mod stride; +pub mod timings; +pub mod vision; +pub mod watchdog; diff --git a/crates/serving-policy/src/reasoning.rs b/crates/serving-policy/src/reasoning.rs new file mode 100644 index 00000000..b8041bd0 --- /dev/null +++ b/crates/serving-policy/src/reasoning.rs @@ -0,0 +1,251 @@ +//! Reasoning-budget wrap-up (issue #123 of the Original): `Service.reasoning_budget` and the +//! budget branch of `Service.run` in `serve/server.py`. +//! +//! A request may cap how many tokens the model spends thinking (`reasoning_budget_tokens`, else +//! the config default). When the thinking reaches the cap at a *clean point* - no part of a +//! `` tag held back, no UTF-8 character split across tokens - generation is stopped, the +//! fixed [`WRAP_UP`] text (which ends the thinking the way the model would) is appended to the +//! output, and generation continues from `prompt + generated + wrap-up`, so the engine keeps the +//! prefix it already holds. +//! +//! [`BudgetTracker`] is the pure decision part: feed it each generated token's bytes, it answers +//! when to wrap up. It reproduces the interplay of the Original's incremental UTF-8 `Detokenizer` +//! and `OutputParser` (state `reasoning`, `buf` = a held prefix of ``). + +use serde_json::Value; + +use crate::shared::py_repr; + +/// What closes the thinking when the budget is reached (`REASONING_WRAP_UP`). +pub const WRAP_UP: &str = + "\n\nI have thought about this long enough; time to give my answer.\n\n\n"; + +const THINK_END: &str = ""; + +/// `Service.reasoning_budget`: the request's `reasoning_budget_tokens`, else the config's; `0` or +/// less means no budget (so a request can switch a configured one off); anything that is not a +/// whole number is an error (a 400 in the Original). +pub fn parse_budget( + request: Option<&Value>, + config_default: Option<&Value>, +) -> Result, String> { + let value = match request { + Some(v) if !v.is_null() => Some(v), + _ => config_default.filter(|v| !v.is_null()), + }; + let Some(value) = value else { + return Ok(None); + }; + let whole = match value { + Value::Number(n) => n + .as_i64() + .map(i128::from) + .or_else(|| n.as_u64().map(i128::from)) + .or_else(|| { + n.as_f64() + .filter(|f| f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18) + .map(|f| f as i128) + }), + _ => None, + }; + match whole { + Some(n) if n > 0 => Ok(Some(u64::try_from(n).unwrap_or(u64::MAX))), + Some(_) => Ok(None), + None => Err(format!( + "reasoning_budget_tokens={}: expected a whole number of tokens (0: no budget)", + py_repr(value) + )), + } +} + +/// The verdict after one generated token. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + Continue, + /// Stop now and append [`WRAP_UP`]. + WrapUp, +} + +#[derive(Clone, Debug)] +pub struct BudgetTracker { + budget: u64, + thought: u64, + reasoning: bool, + /// The parser's `buf` in the reasoning state: a held proper prefix of ``. + held: String, + /// Bytes of a UTF-8 character not yet complete (`Detokenizer.pending`). + partial: Vec, +} + +impl BudgetTracker { + /// `budget` must be positive (a missing budget means no tracker). + pub fn new(budget: u64) -> Self { + Self { + budget, + thought: 0, + reasoning: true, + held: String::new(), + partial: Vec::new(), + } + } + + /// Reasoning tokens counted so far. + pub fn thought(&self) -> u64 { + self.thought + } + + /// Still inside the thinking (before ``). + pub fn in_reasoning(&self) -> bool { + self.reasoning + } + + /// Feed the next generated token's bytes. + pub fn push(&mut self, token: &[u8]) -> Verdict { + if !self.reasoning { + return Verdict::Continue; + } + let text = self.decode(token); + self.held.push_str(&text); + if let Some(at) = self.held.find(THINK_END) { + self.held.drain(..at + THINK_END.len()); + self.reasoning = false; + return Verdict::Continue; + } + let keep = hold(&self.held, THINK_END); + let cut = self.held.len() - keep; + self.held.drain(..cut); + self.thought += 1; + if self.thought >= self.budget && self.held.is_empty() && self.partial.is_empty() { + Verdict::WrapUp + } else { + Verdict::Continue + } + } + + /// Incremental UTF-8 decode with replacement characters (Python's + /// `codecs.getincrementaldecoder("utf-8")(errors="replace")`). + fn decode(&mut self, token: &[u8]) -> String { + self.partial.extend_from_slice(token); + let mut out = String::new(); + loop { + match std::str::from_utf8(&self.partial) { + Ok(valid) => { + out.push_str(valid); + self.partial.clear(); + return out; + } + Err(error) => { + let valid = error.valid_up_to(); + out.push_str( + std::str::from_utf8(&self.partial[..valid]).expect("valid prefix"), + ); + match error.error_len() { + None => { + self.partial.drain(..valid); + return out; + } + Some(bad) => { + out.push('\u{FFFD}'); + self.partial.drain(..valid + bad); + } + } + } + } + } + } +} + +/// `OutputParser._hold`: the length of the longest suffix of `text` that is a proper prefix of `tag`. +fn hold(text: &str, tag: &str) -> usize { + (1..tag.len()) + .rev() + .find(|n| text.ends_with(&tag[..*n])) + .unwrap_or(0) +} + +/// What the wrap-up appends, for the caller to turn into token ids. +pub fn wrap_up_text() -> &'static str { + WRAP_UP +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn budget_parsing_follows_the_originals_rules() { + let none = None; + assert_eq!(parse_budget(none, none), Ok(None)); + assert_eq!(parse_budget(Some(&json!(20)), none), Ok(Some(20))); + assert_eq!(parse_budget(Some(&json!(20.0)), none), Ok(Some(20))); + assert_eq!(parse_budget(Some(&json!(0)), Some(&json!(50))), Ok(None)); + assert_eq!(parse_budget(Some(&json!(-3)), none), Ok(None)); + assert_eq!(parse_budget(None, Some(&json!(50))), Ok(Some(50))); + assert_eq!( + parse_budget(Some(&json!(null)), Some(&json!(50))), + Ok(Some(50)) + ); + for bad in [json!(true), json!("5"), json!(2.5), json!([1])] { + let error = parse_budget(Some(&bad), none).unwrap_err(); + assert!(error.starts_with("reasoning_budget_tokens="), "{error}"); + assert!(error.ends_with("expected a whole number of tokens (0: no budget)")); + } + assert_eq!( + parse_budget(Some(&json!("5")), none).unwrap_err(), + "reasoning_budget_tokens='5': expected a whole number of tokens (0: no budget)" + ); + } + + #[test] + fn wraps_up_at_the_budget_on_a_clean_token() { + let mut t = BudgetTracker::new(3); + assert_eq!(t.push(b"a"), Verdict::Continue); + assert_eq!(t.push(b"b"), Verdict::Continue); + assert_eq!(t.push(b"c"), Verdict::WrapUp); + assert_eq!(t.thought(), 3); + } + + #[test] + fn a_held_tag_prefix_delays_the_wrap_up() { + let mut t = BudgetTracker::new(2); + assert_eq!(t.push(b"x"), Verdict::Continue); + // the second token ends with ""), Verdict::Continue); + assert!(!t.in_reasoning()); + assert_eq!(t.push(b"b"), Verdict::Continue); + assert_eq!(t.push(b"c"), Verdict::Continue); + assert_eq!(t.thought(), 1); + } + + #[test] + fn a_tag_split_over_tokens_is_still_found() { + let mut t = BudgetTracker::new(100); + for piece in [&b""] { + let _ = t.push(piece); + } + assert!(!t.in_reasoning()); + } + + #[test] + fn invalid_utf8_becomes_replacement_characters_not_a_stall() { + let mut t = BudgetTracker::new(2); + assert_eq!(t.push(&[0xFF]), Verdict::Continue); + assert_eq!(t.push(&[0xFF]), Verdict::WrapUp); + } +} diff --git a/crates/serving-policy/src/shared.rs b/crates/serving-policy/src/shared.rs new file mode 100644 index 00000000..a131aed6 --- /dev/null +++ b/crates/serving-policy/src/shared.rs @@ -0,0 +1,547 @@ +//! The server-wide Chat settings (`POST /settings`), the run config's `sampling` block, and how +//! both are merged under a request. Port of `serve/server.py` `clean_shared_defaults`, +//! `sampling_defaults_from_config`, `Service.with_shared`, `Service.run`'s default merge and +//! the `defaults` part of `GET /props`. +//! +//! Differences from the Original, all on the safe side: +//! +//! * integers wider than `u64` (a `seed`/`max_tokens`/`top_k` Python would keep as a big int) +//! are rejected; +//! * config `temperature` above 2 is rejected here (the Original accepts any `>= 0` in the +//! config but the request boundary of this port caps `temperature` at 2, so a larger default +//! could never be applied); +//! * error text mirrors the Original's for the common cases and is golden-tested. + +use leleka_sampler_ref::RequestSampling; +use leleka_sampler_ref::params::py_float_repr; +use serde_json::{Map, Number, Value}; + +/// The keys `POST /settings` accepts (`SHARED_KEYS`). +pub const SHARED_KEYS: [&str; 7] = [ + "reasoning_effort", + "temperature", + "top_p", + "top_k", + "seed", + "max_tokens", + "experimental_speed_projection", +]; + +/// `clean_shared_defaults` output: only the keys a client set. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SharedDefaults { + pub reasoning_effort: Option, + pub temperature: Option, + pub top_p: Option, + pub top_k: Option, + pub seed: Option, + pub max_tokens: Option, + pub experimental_speed_projection: Option, +} + +impl SharedDefaults { + pub fn is_empty(&self) -> bool { + *self == Self::default() + } + + /// The JSON object `/settings` answers with and persists (`defaults`). + pub fn to_json(&self) -> Value { + let mut out = Map::new(); + if let Some(v) = &self.reasoning_effort { + out.insert("reasoning_effort".into(), Value::String(v.clone())); + } + if let Some(v) = self.temperature { + out.insert("temperature".into(), float_value(v)); + } + if let Some(v) = self.top_p { + out.insert("top_p".into(), float_value(v)); + } + if let Some(v) = self.top_k { + out.insert("top_k".into(), Value::from(v)); + } + if let Some(v) = self.seed { + out.insert("seed".into(), Value::from(v)); + } + if let Some(v) = self.max_tokens { + out.insert("max_tokens".into(), Value::from(v)); + } + if let Some(v) = self.experimental_speed_projection { + out.insert("experimental_speed_projection".into(), Value::Bool(v)); + } + Value::Object(out) + } + + /// The sampling subset the shared settings carry. + pub fn sampling(&self) -> RequestSampling { + RequestSampling { + temperature: self.temperature, + top_p: self.top_p, + top_k: self.top_k, + seed: self.seed, + ..Default::default() + } + } +} + +fn float_value(v: f64) -> Value { + Number::from_f64(v).map_or(Value::Null, Value::Number) +} + +/// Python's `repr()` of a JSON-ish value, for the Original's error text. +pub fn py_repr(value: &Value) -> String { + match value { + Value::Null => "None".into(), + Value::Bool(true) => "True".into(), + Value::Bool(false) => "False".into(), + Value::Number(n) => match n.as_i64() { + Some(i) => i.to_string(), + None => match n.as_u64() { + Some(u) => u.to_string(), + None => py_float_repr(n.as_f64().unwrap_or(f64::NAN)), + }, + }, + Value::String(s) => py_str_repr(s), + Value::Array(items) => format!( + "[{}]", + items.iter().map(py_repr).collect::>().join(", ") + ), + Value::Object(map) => format!( + "{{{}}}", + map.iter() + .map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v))) + .collect::>() + .join(", ") + ), + } +} + +/// Python's `repr(str)`: single quotes unless the text has a single and no double quote. +pub fn py_str_repr(s: &str) -> String { + let quote = if s.contains('\'') && !s.contains('"') { + '"' + } else { + '\'' + }; + let mut out = String::new(); + out.push(quote); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c == quote => { + out.push('\\'); + out.push(c); + } + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + out.push_str(&format!("\\x{:02x}", c as u32)); + } + c => out.push(c), + } + } + out.push(quote); + out +} + +fn is_number(v: &Value) -> bool { + v.is_number() +} + +fn as_f64(v: &Value) -> Option { + v.as_f64() +} + +/// An integral number as `i128`, or `None`. +fn integral(v: &Value) -> Option { + if let Some(i) = v.as_i64() { + return Some(i128::from(i)); + } + if let Some(u) = v.as_u64() { + return Some(i128::from(u)); + } + let f = v.as_f64()?; + (f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18).then_some(f as i128) +} + +/// `clean_shared_defaults`: `Ok` with only the known, valid keys; `Err` names the first bad one +/// (the message the Original's `ValueError` carries). +pub fn clean_shared_defaults(defaults: &Value) -> Result { + let map = match defaults { + Value::Null => return Ok(SharedDefaults::default()), + Value::Object(map) => map, + _ => return Err("defaults must be an object".into()), + }; + let mut out = SharedDefaults::default(); + for (key, value) in map { + if value.is_null() || value.as_str() == Some("") { + continue; + } + match key.as_str() { + "reasoning_effort" => match value.as_str() { + Some(e @ ("none" | "low" | "medium" | "high")) => { + out.reasoning_effort = Some(e.to_owned()); + } + _ => return Err("reasoning_effort: none, low, medium or high".into()), + }, + "temperature" => match as_f64(value) { + Some(t) if is_number(value) && (0.0..=2.0).contains(&t) => { + out.temperature = Some(t) + } + _ => return Err("temperature: 0..2".into()), + }, + "top_p" => match as_f64(value) { + Some(p) if is_number(value) && p > 0.0 && p <= 1.0 => out.top_p = Some(p), + _ => return Err("top_p: 0 < top_p <= 1".into()), + }, + "top_k" => match integral(value) { + Some(k) if is_number(value) && (1..=64).contains(&k) => out.top_k = Some(k as i64), + _ => return Err("top_k: an integer 1..64".into()), + }, + "seed" => match integral(value) { + Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { + out.seed = Some(s as u64); + } + _ => return Err("seed: a positive integer".into()), + }, + "max_tokens" => match integral(value) { + Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { + out.max_tokens = Some(s as u64); + } + _ => return Err("max_tokens: a positive integer".into()), + }, + "experimental_speed_projection" => match value.as_bool() { + Some(b) => out.experimental_speed_projection = Some(b), + None => return Err("experimental_speed_projection: true or false".into()), + }, + other => return Err(format!("unknown setting {}", py_str_repr(other))), + } + } + Ok(out) +} + +/// The run config's `sampling` block (`sampling_defaults_from_config`). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConfigSampling { + pub sampling: RequestSampling, + pub experimental_speed_projection: Option, + /// Keys the Original names at startup and ignores. + pub ignored: Vec, +} + +fn config_error(key: &str, value: &Value, expected: &str) -> String { + format!( + "[strata] config sampling.{key}={}: {expected}", + py_repr(value) + ) +} + +/// Parse the config's `sampling` object. A bad value is an error (the Original stops the start). +pub fn sampling_defaults_from_config(block: &Value) -> Result { + let map = match block { + Value::Null => return Ok(ConfigSampling::default()), + Value::Object(map) => map, + _ => return Err("[strata] config sampling: expected an object".into()), + }; + let mut out = ConfigSampling::default(); + for (key, value) in map { + if value.is_null() { + continue; + } + let number = is_number(value); + let f = as_f64(value).filter(|_| number); + match key.as_str() { + "temperature" => match f { + Some(v) if v >= 0.0 => out.sampling.temperature = Some(v), + _ => { + return Err(config_error( + key, + value, + "expected a number >= 0 (0 = greedy)", + )); + } + }, + "top_p" => match f { + Some(v) if v > 0.0 && v <= 1.0 => out.sampling.top_p = Some(v), + _ => return Err(config_error(key, value, "expected 0 < top_p <= 1")), + }, + "min_p" => match f { + Some(v) if (0.0..=1.0).contains(&v) => out.sampling.min_p = Some(v), + _ => return Err(config_error(key, value, "expected 0 <= min_p <= 1")), + }, + "top_k" => match integral(value) { + Some(k) if number && (1..=64).contains(&k) => out.sampling.top_k = Some(k as i64), + _ => { + return Err(config_error( + key, + value, + "the sampled path takes an integer 1..64", + )); + } + }, + "presence_penalty" => match f { + Some(v) if v >= 0.0 => out.sampling.presence_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number >= 0")), + }, + "frequency_penalty" => match f { + Some(v) if v >= 0.0 => out.sampling.frequency_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number >= 0")), + }, + "repetition_penalty" => match f { + Some(v) if v > 0.0 => out.sampling.repetition_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number > 0 (1 = off)")), + }, + "penalty_last_n" => match integral(value) { + Some(n) if number && (0..=i128::from(i32::MAX)).contains(&n) => { + out.sampling.penalty_last_n = Some(n as i64); + } + _ => { + return Err(config_error(key, value, "expected a non-negative integer")); + } + }, + "seed" => match integral(value) { + Some(s) if number && s > 0 && s <= i128::from(u64::MAX) => { + out.sampling.seed = Some(s as u64); + } + _ => return Err(config_error(key, value, "expected a positive integer")), + }, + "experimental_speed_projection" => match value.as_bool() { + Some(b) => out.experimental_speed_projection = Some(b), + None => { + return Err(config_error( + key, + value, + "expected true or false (the default for requests that leave it out, when the engine has the vector)", + )); + } + }, + other => out.ignored.push(other.to_owned()), + } + } + // The request boundary of this port refuses temperatures above 2; a default must be usable. + out.sampling + .validate_config_defaults() + .map_err(|e| format!("[strata] config sampling.{}: {}", e.field, e.expected))?; + Ok(out) +} + +/// `Service.set_aliases`: the config's `aliases` - a list of names (or one comma-separated string), like +/// llama-server's `--alias`. Names are trimmed; empty names, the model's own name and duplicates are +/// dropped. `Err` for anything else. +pub fn normalize_aliases(value: &Value, model: &str) -> Result, String> { + let names: Vec = match value { + Value::Null => Vec::new(), + Value::String(text) => text.split(',').map(str::to_owned).collect(), + Value::Array(items) if items.iter().all(Value::is_string) => items + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + other => { + return Err(format!( + "aliases={}: expected a list of model names", + py_repr(other) + )); + } + }; + let mut out: Vec = Vec::new(); + for name in names { + let name = name.trim().to_owned(); + if !name.is_empty() && name != model && !out.contains(&name) { + out.push(name); + } + } + Ok(out) +} + +/// The defaults a request starts from: the config block, then the shared settings on top +/// (`{**sampling_defaults, **shared}`). The speed-projection default comes the same way. +pub fn merged_defaults(config: &ConfigSampling, shared: &SharedDefaults) -> MergedDefaults { + MergedDefaults { + sampling: RequestSampling::overlay(&config.sampling, &shared.sampling()), + experimental_speed_projection: shared + .experimental_speed_projection + .or(config.experimental_speed_projection), + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MergedDefaults { + pub sampling: RequestSampling, + pub experimental_speed_projection: Option, +} + +impl MergedDefaults { + /// `default_generation_settings.params` of `GET /props` (llama-server names). + pub fn props_params(&self, shared: &SharedDefaults) -> Value { + let mut params = Map::new(); + let s = &self.sampling; + let mut put = |name: &str, value: Option| { + if let Some(v) = value { + params.insert(name.to_owned(), v); + } + }; + put("temperature", s.temperature.map(float_value)); + put("top_p", s.top_p.map(float_value)); + put("top_k", s.top_k.map(Value::from)); + put("min_p", s.min_p.map(float_value)); + put("seed", s.seed.map(Value::from)); + put("repeat_penalty", s.repetition_penalty.map(float_value)); + put("presence_penalty", s.presence_penalty.map(float_value)); + put("frequency_penalty", s.frequency_penalty.map(float_value)); + put("repeat_last_n", s.penalty_last_n.map(Value::from)); + params.insert( + "n_predict".into(), + shared.max_tokens.map_or(Value::from(-1), Value::from), + ); + Value::Object(params) + } +} + +/// `with_shared`, `max_tokens` half: the shared limit when the request has none of its own. +pub fn shared_max_tokens(request_max: Option, shared: &SharedDefaults) -> Option { + match request_max { + Some(n) if n > 0 => Some(n), + _ => shared.max_tokens.or(request_max), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn unknown_keys_are_refused_unless_their_value_is_empty() { + let d = clean_shared_defaults(&json!({"top_p": null, "x": null, "min_p": ""})).unwrap(); + assert!(d.is_empty()); + assert_eq!( + clean_shared_defaults(&json!({"min_p": 0.1})), + Err("unknown setting 'min_p'".to_owned()) + ); + } + + #[test] + fn empty_and_null_values_are_dropped() { + let d = clean_shared_defaults(&json!({"temperature": "", "top_p": null})).unwrap(); + assert!(d.is_empty()); + assert!(clean_shared_defaults(&Value::Null).unwrap().is_empty()); + assert!(clean_shared_defaults(&json!([1])).is_err()); + } + + #[test] + fn valid_values_are_normalised_like_the_original() { + let d = clean_shared_defaults(&json!({"temperature": 1, "top_k": 40.0, "seed": 7, + "reasoning_effort": "high", "max_tokens": 100, "top_p": 1})) + .unwrap(); + assert_eq!(d.temperature, Some(1.0)); + assert_eq!(d.top_k, Some(40)); + assert_eq!(d.seed, Some(7)); + assert_eq!(d.max_tokens, Some(100)); + assert_eq!(d.top_p, Some(1.0)); + assert_eq!( + d.to_json(), + json!({"reasoning_effort": "high", "temperature": 1.0, "top_p": 1.0, "top_k": 40, + "seed": 7, "max_tokens": 100}) + ); + } + + #[test] + fn config_block_checks_the_originals_ranges() { + let c = sampling_defaults_from_config(&json!({"temperature": 0.7, "top_p": 0.9, + "top_k": 40, "min_p": 0.05, "presence_penalty": 0.5, "repetition_penalty": 1.1, + "frequency_penalty": 0.0, "penalty_last_n": 128, "seed": 5, + "experimental_speed_projection": true, "nonsense": 1})) + .unwrap(); + assert_eq!(c.sampling.top_k, Some(40)); + assert_eq!(c.ignored, vec!["nonsense".to_owned()]); + assert_eq!(c.experimental_speed_projection, Some(true)); + for (key, bad) in [ + ("temperature", json!(-1)), + ("top_p", json!(0)), + ("min_p", json!(1.5)), + ("top_k", json!(0)), + ("top_k", json!(65)), + ("top_k", json!(1.5)), + ("presence_penalty", json!(-0.1)), + ("repetition_penalty", json!(0)), + ("penalty_last_n", json!(-1)), + ("seed", json!(0)), + ("seed", json!(true)), + ("experimental_speed_projection", json!(1)), + ] { + assert!( + sampling_defaults_from_config(&json!({ key: bad.clone() })).is_err(), + "{key}={bad}" + ); + } + } + + #[test] + fn shared_wins_over_config_and_the_request_wins_over_both() { + let config = + sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1})).unwrap(); + let shared = clean_shared_defaults(&json!({"temperature": 0.9, "seed": 4})).unwrap(); + let merged = merged_defaults(&config, &shared); + assert_eq!(merged.sampling.temperature, Some(0.9)); + assert_eq!(merged.sampling.min_p, Some(0.1)); + assert_eq!(merged.sampling.seed, Some(4)); + let request = RequestSampling { + temperature: Some(0.0), + ..Default::default() + }; + let effective = RequestSampling::overlay(&merged.sampling, &request); + assert_eq!(effective.temperature, Some(0.0), "explicit 0 stays greedy"); + assert_eq!(effective.min_p, Some(0.1)); + } + + #[test] + fn props_params_use_llama_server_names() { + let config = sampling_defaults_from_config( + &json!({"repetition_penalty": 1.1, "penalty_last_n": 64}), + ) + .unwrap(); + let shared = clean_shared_defaults(&json!({"max_tokens": 512})).unwrap(); + let params = merged_defaults(&config, &shared).props_params(&shared); + assert_eq!( + params, + json!({"repeat_penalty": 1.1, "repeat_last_n": 64, "n_predict": 512}) + ); + } + + #[test] + fn aliases_are_trimmed_deduplicated_and_never_the_model() { + assert_eq!( + normalize_aliases(&json!([" gpt ", "gpt", "", "m", "claude"]), "m"), + Ok(vec!["gpt".to_owned(), "claude".to_owned()]) + ); + assert_eq!( + normalize_aliases(&json!("a, b ,a,,m"), "m"), + Ok(vec!["a".to_owned(), "b".to_owned()]) + ); + assert_eq!(normalize_aliases(&Value::Null, "m"), Ok(vec![])); + assert_eq!( + normalize_aliases(&json!([1]), "m").unwrap_err(), + "aliases=[1]: expected a list of model names" + ); + assert!(normalize_aliases(&json!({"a": 1}), "m").is_err()); + } + + #[test] + fn python_repr_of_values() { + assert_eq!(py_repr(&json!(true)), "True"); + assert_eq!(py_repr(&json!(null)), "None"); + assert_eq!(py_repr(&json!("it's")), "\"it's\""); + assert_eq!(py_repr(&json!(1.5)), "1.5"); + assert_eq!(py_repr(&json!([1, "a"])), "[1, 'a']"); + assert_eq!(py_repr(&json!({"a": 1})), "{'a': 1}"); + } + + #[test] + fn shared_max_tokens_only_fills_a_missing_limit() { + let shared = clean_shared_defaults(&json!({"max_tokens": 77})).unwrap(); + assert_eq!(shared_max_tokens(None, &shared), Some(77)); + assert_eq!(shared_max_tokens(Some(0), &shared), Some(77)); + assert_eq!(shared_max_tokens(Some(5), &shared), Some(5)); + assert_eq!(shared_max_tokens(None, &SharedDefaults::default()), None); + } +} diff --git a/crates/serving-policy/src/stride.rs b/crates/serving-policy/src/stride.rs new file mode 100644 index 00000000..bc2cf76b --- /dev/null +++ b/crates/serving-policy/src/stride.rs @@ -0,0 +1,83 @@ +//! Logits-selection stride (`include/strata/program/logits_selection.hpp`): which prompt positions +//! keep their logits rows when a diagnostic dump asks for every `stride`-th row. +//! +//! "Storage selection only: callers must still condition on every input token." The functions are +//! integer-exact transcriptions, golden-tested against the Original's header compiled on the host. + +/// Positive decimal `int64`, with no sign, whitespace, suffix or overflow (`parse_stride`). +pub fn parse_stride(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.first().is_none_or(|b| !b.is_ascii_digit()) { + return None; + } + if !bytes.iter().all(u8::is_ascii_digit) { + return None; + } + text.parse::().ok().filter(|v| *v > 0) +} + +/// Zero-based multiples of `stride`, followed by the final input position once. +pub fn selected(position: i64, total: i64, stride: i64) -> bool { + total > 0 + && stride > 0 + && position >= 0 + && position < total + && (position % stride == 0 || position == total - 1) +} + +/// How many positions [`selected`] keeps. +pub fn row_count(total: i64, stride: i64) -> i64 { + if total > 0 && stride > 0 { + (total - 1) / stride + 1 + i64::from((total - 1) % stride != 0) + } else { + 0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_is_strict() { + assert_eq!(parse_stride("1"), Some(1)); + assert_eq!(parse_stride("128"), Some(128)); + assert_eq!(parse_stride("9223372036854775807"), Some(i64::MAX)); + for bad in [ + "", + "0", + "00", + "-1", + "+1", + " 1", + "1 ", + "1x", + "x", + "9223372036854775808", + "1", + ] { + assert_eq!(parse_stride(bad), None, "{bad:?}"); + } + } + + #[test] + fn selection_is_multiples_plus_the_last_position() { + let kept: Vec = (0..10).filter(|p| selected(*p, 10, 4)).collect(); + assert_eq!(kept, vec![0, 4, 8, 9]); + assert_eq!(row_count(10, 4), 4); + assert_eq!(row_count(9, 4), 3); + assert_eq!(row_count(1, 5), 1); + assert_eq!(row_count(0, 5), 0); + assert_eq!(row_count(5, 0), 0); + } + + #[test] + fn row_count_equals_the_number_of_selected_positions() { + for total in 0..60 { + for stride in 0..13 { + let n = (-1..=total).filter(|p| selected(*p, total, stride)).count() as i64; + assert_eq!(n, row_count(total, stride), "total {total} stride {stride}"); + } + } + } +} diff --git a/crates/serving-policy/src/timings.rs b/crates/serving-policy/src/timings.rs new file mode 100644 index 00000000..804b6967 --- /dev/null +++ b/crates/serving-policy/src/timings.rs @@ -0,0 +1,128 @@ +//! One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's +//! own clock: `request_timings` of `serve/server.py`. +//! +//! `prompt_n` is what was read, `cache_n` what the conversation cache already held. Rounding is +//! Python's `round(x, n)`: the exactly rounded decimal of the binary value, ties to even. + +use serde_json::{Map, Value}; + +/// The engine's `DONE` figures for one request (`StrataEngine.last`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Last { + pub prompt_tokens: u64, + /// The engine's own count of generated tokens (0 = not reported). + pub generated: u64, + pub prompt_ms: f64, + pub decode_ms: f64, + pub reused: Option, + pub drafts_offered: Option, + pub drafts_accepted: Option, +} + +/// Python's `round(x, digits)` for finite `x`. +pub fn py_round(x: f64, digits: usize) -> f64 { + format!("{x:.digits$}").parse().unwrap_or(x) +} + +fn rounded(x: f64, digits: usize) -> Value { + Value::from(py_round(x, digits)) +} + +/// `request_timings(prompt_tokens, generated, last)`. `generated` is the client-visible completion +/// token count. +pub fn request_timings(last: &Last, generated: u64) -> Value { + let cache_n = last.reused.unwrap_or(0); + let prompt_n = last.prompt_tokens.saturating_sub(cache_n); + let (prompt_ms, decode_ms) = (last.prompt_ms, last.decode_ms); + let decoded = if last.generated > 0 { + last.generated + } else { + generated + }; + let mut out = Map::new(); + out.insert("cache_n".into(), cache_n.into()); + out.insert("prompt_n".into(), prompt_n.into()); + out.insert("prompt_ms".into(), rounded(prompt_ms, 1)); + out.insert( + "prompt_per_token_ms".into(), + if prompt_n > 0 { + rounded(prompt_ms / prompt_n as f64, 3) + } else { + Value::Null + }, + ); + out.insert( + "prompt_per_second".into(), + if prompt_n > 0 && prompt_ms > 0.0 { + rounded(prompt_n as f64 / (prompt_ms / 1000.0), 1) + } else { + Value::Null + }, + ); + out.insert("predicted_n".into(), generated.into()); + out.insert("predicted_ms".into(), rounded(decode_ms, 1)); + out.insert( + "predicted_per_token_ms".into(), + if decoded > 0 { + rounded(decode_ms / decoded as f64, 3) + } else { + Value::Null + }, + ); + out.insert( + "predicted_per_second".into(), + if decoded > 0 && decode_ms > 0.0 { + rounded(decoded as f64 / (decode_ms / 1000.0), 1) + } else { + Value::Null + }, + ); + if let Some(offered) = last.drafts_offered { + out.insert("draft_n".into(), offered.into()); + out.insert( + "draft_n_accepted".into(), + last.drafts_accepted.unwrap_or(0).into(), + ); + } + Value::Object(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn python_rounding_is_exact_and_ties_to_even() { + assert_eq!(py_round(2.675, 2), 2.67); // the binary value is below the tie + assert_eq!(py_round(0.25, 1), 0.2); // an exact tie goes to even + assert_eq!(py_round(0.35, 1), 0.3); // 0.35 is below the tie in binary + assert_eq!(py_round(1234.5678, 1), 1234.6); + assert_eq!(py_round(0.0, 3), 0.0); + } + + #[test] + fn timings_use_llama_cpp_names() { + let t = request_timings( + &Last { + prompt_tokens: 100, + generated: 50, + prompt_ms: 250.0, + decode_ms: 1000.0, + reused: Some(60), + drafts_offered: Some(10), + drafts_accepted: Some(7), + }, + 50, + ); + assert_eq!(t["cache_n"], 60); + assert_eq!(t["prompt_n"], 40); + assert_eq!(t["prompt_per_token_ms"], 6.25); + assert_eq!(t["prompt_per_second"], 160.0); + assert_eq!(t["predicted_per_second"], 50.0); + assert_eq!(t["draft_n"], 10); + assert_eq!(t["draft_n_accepted"], 7); + let none = request_timings(&Last::default(), 0); + assert!(none["prompt_per_token_ms"].is_null()); + assert!(none.get("draft_n").is_none()); + } +} diff --git a/crates/serving-policy/src/vision.rs b/crates/serving-policy/src/vision.rs new file mode 100644 index 00000000..8a69d22f --- /dev/null +++ b/crates/serving-policy/src/vision.rs @@ -0,0 +1,500 @@ +//! The image path of the Original, host side: SVE1 embedding files, the M-RoPE position table, image +//! sources, and the `<|image_pad|>` expansion of a prompt (`Service.prepare` in `serve/server.py`, +//! `GENI` handling in `src/program/generate.cpp`, `serve/frontend.py` `_image_source`/`images_of`). +//! +//! * [`parse_embeddings`] and [`build_positions`] are transcriptions of the verbatim block of +//! `generate.cpp` (`if (geni || !mrope_identity)`), golden-tested against that block compiled on +//! the host (`oracle/gen_vision_fixtures.cpp`). +//! * Qwen's interleaved M-RoPE gives each rotated pair a position from one of three streams (time +//! `t`, height `h`, width `w`): text has `t = h = w`, an image's tokens share `t = p` and differ in +//! `h = p + y`, `w = p + x`, and the text after it continues at `p + max(nx, ny)`. + +use serde_json::Value; + +/// `'SVE1'` little-endian: the magic of a strata-vision record. +pub const SVE1_MAGIC: i32 = 0x3145_5653; + +/// Token id of `<|image_pad|>` (`qwen4exp.ple.image_token_id`). +pub const IMAGE_PAD_ID: i64 = 248_056; + +/// One image of an embeddings file: `n` rows of `n_embd` floats laid out on an `nx` x `ny` grid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Image { + pub n: i64, + pub nx: i64, + pub ny: i64, + /// Offset of its first float in [`Embeddings::rows`]. + pub offset: usize, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Embeddings { + pub images: Vec, + pub rows: Vec, +} + +/// Parse one or more strata-vision records: `int32 'SVE1', n, nx, ny, n_embd`, then `n x n_embd` +/// `f32`s. Records are in prompt order. Error text is the engine's. +pub fn parse_embeddings(bytes: &[u8], n_embd: i64) -> Result { + let bad = || format!("bad embeddings file (expected strata-vision records of width {n_embd})"); + let mut out = Embeddings::default(); + let mut at = 0usize; + while at < bytes.len() { + let Some(header) = bytes.get(at..at + 20) else { + return Err(bad()); + }; + let word = + |i: usize| i32::from_le_bytes(header[4 * i..4 * i + 4].try_into().expect("4 bytes")); + let (magic, n, nx, ny, width) = (word(0), word(1), word(2), word(3), word(4)); + if magic != SVE1_MAGIC + || n < 1 + || nx < 1 + || ny < 1 + || i64::from(nx) * i64::from(ny) != i64::from(n) + || i64::from(width) != n_embd + { + return Err(bad()); + } + at += 20; + let count = usize::try_from(i64::from(n) * i64::from(width)).map_err(|_| bad())?; + let Some(data) = bytes.get(at..at + count * 4) else { + return Err("short embeddings file".to_owned()); + }; + let offset = out.rows.len(); + out.rows.extend( + data.as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)), + ); + at += count * 4; + out.images.push(Image { + n: i64::from(n), + nx: i64::from(nx), + ny: i64::from(ny), + offset, + }); + } + Ok(out) +} + +/// FNV-1a (`fnv1a` in generate.cpp), continuing from `h`. +pub fn fnv1a(data: &[u8], mut h: u64) -> u64 { + for byte in data { + h ^= u64::from(*byte); + h = h.wrapping_mul(1_099_511_628_211); + } + h +} + +const FNV_OFFSET: u64 = 1_469_598_103_934_665_603; + +/// What the request's pictures look like to the conversation cache: where each starts and a hash of +/// its grid and embeddings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ImageKey { + pub start: i64, + pub hash: u64, +} + +/// The `[cells][3]` `(t, h, w)` rotary position table, the embedding row each prompt token takes +/// (`None` for ordinary tokens) and the picture keys. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Positions { + pub table: Vec<[i32; 3]>, + /// Offset into [`Embeddings::rows`] of the row that replaces the token's embedding. + pub row_offset: Vec>, + pub images: Vec, +} + +/// The identity table of a text request: every stream is the cell index. +pub fn identity_table(cells: usize) -> Vec<[i32; 3]> { + (0..cells) + .map(|c| { + let c = c as i32; + [c, c, c] + }) + .collect() +} + +/// Positions for every cell a request can reach. `ids` are the prompt token ids with one +/// `image_pad` per image row; `cells` is the table length (`max_context + 64`). +pub fn build_positions( + ids: &[i64], + cells: usize, + embeddings: &Embeddings, + n_embd: i64, + image_pad: i64, +) -> Result { + let n = ids.len() as i64; + let mut table = identity_table(cells); + let mut row_offset: Vec> = vec![None; ids.len()]; + let mut keys = Vec::new(); + let put = |table: &mut Vec<[i32; 3]>, c: i64, t: i64, h: i64, w: i64| -> Result<(), String> { + let slot = usize::try_from(c) + .ok() + .and_then(|c| table.get_mut(c)) + .ok_or_else(|| "the prompt is longer than the position table".to_owned())?; + *slot = [t as i32, h as i32, w as i32]; + Ok(()) + }; + let (mut p, mut i, mut k) = (0i64, 0i64, 0usize); + while i < n { + if ids[i as usize] != image_pad { + put(&mut table, i, p, p, p)?; + p += 1; + i += 1; + continue; + } + let Some(image) = embeddings.images.get(k) else { + return Err("the prompt has more images than the embeddings file".into()); + }; + k += 1; + let float_bytes = |from: usize, count: usize| -> Vec { + embeddings.rows[from..from + count] + .iter() + .flat_map(|f| f.to_le_bytes()) + .collect() + }; + let grid: Vec = [image.n, image.nx, image.ny] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let mut hash = fnv1a(&grid, FNV_OFFSET); + let count = usize::try_from(image.n * n_embd).map_err(|_| "bad image size".to_owned())?; + hash = fnv1a(&float_bytes(image.offset, count), hash); + keys.push(ImageKey { start: i, hash }); + for j in 0..image.n { + if i + j >= n || ids[(i + j) as usize] != image_pad { + return Err(format!( + "image {k} has {} rows but fewer <|image_pad|> tokens", + image.n + )); + } + } + for j in 0..image.n { + let (y, x) = (j / image.nx, j % image.nx); + put(&mut table, i + j, p, p + y, p + x)?; + row_offset[(i + j) as usize] = Some(image.offset + (j * n_embd) as usize); + } + i += image.n; + p += image.nx.max(image.ny); + } + if k != embeddings.images.len() { + return Err("the embeddings file has more images than the prompt".into()); + } + if n > 0 && ids[(n - 1) as usize] == image_pad { + return Err("the prompt cannot end in an image".into()); + } + for c in n..cells as i64 { + put(&mut table, c, p + (c - n), p + (c - n), p + (c - n))?; + } + Ok(Positions { + table, + row_offset, + images: keys, + }) +} + +// ------------------------------------------------------------------------------------------------ sources + +/// Content-part types that carry an image (`IMAGE_PARTS`). +pub const IMAGE_PARTS: [&str; 3] = ["image_url", "input_image", "image"]; + +pub fn is_image_part(part: &Value) -> bool { + part.get("type") + .and_then(Value::as_str) + .is_some_and(|kind| IMAGE_PARTS.contains(&kind)) +} + +/// `_image_source`: an image part's source as one string - a `data:` URL, an http(s) URL or a local +/// path. OpenAI `{"type": "image_url", "image_url": {"url": ...}}` (or `"image_url": "..."`), +/// Responses `{"type": "input_image", "image_url": ...}`, Anthropic `{"type": "image", "source": +/// {"type": "base64", ...}}` or `{"source": {"type": "url", "url": ...}}`. +pub fn image_source(part: &Value) -> String { + let text = |value: Option<&Value>| value.and_then(Value::as_str).unwrap_or("").to_owned(); + if part.get("type").and_then(Value::as_str) == Some("image") { + let source = part.get("source").filter(|v| v.is_object()); + let get = |key: &str| source.and_then(|s| s.get(key)); + if get("type").and_then(Value::as_str) == Some("base64") { + let media = get("media_type") + .and_then(Value::as_str) + .unwrap_or("image/png"); + return format!("data:{media};base64,{}", text(get("data"))); + } + let url = text(get("url")); + return if url.is_empty() { + text(get("path")) + } else { + url + }; + } + match part.get("image_url") { + Some(Value::Object(object)) => text(object.get("url")), + other => text(other), + } +} + +/// Python's `base64.b64decode(s)` (non-strict `binascii.a2b_base64`): characters outside the alphabet +/// (and `\r`, `\n`, space) are skipped; a complete pad sequence ends the data; what is left over +/// is an error with CPython's wording. +pub fn b64decode(text: &str) -> Result, String> { + let value = |c: u8| -> Option { + match c { + b'A'..=b'Z' => Some(c - b'A'), + b'a'..=b'z' => Some(c - b'a' + 26), + b'0'..=b'9' => Some(c - b'0' + 52), + b'+' => Some(62), + b'/' => Some(63), + _ => None, + } + }; + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let (mut quad, mut left, mut pads) = (0u8, 0u8, 0u8); + for byte in text.bytes() { + if byte > 0x7f || matches!(byte, b'\r' | b'\n' | b' ') { + continue; + } + if byte == b'=' { + pads += 1; + if quad >= 2 && quad + pads >= 4 { + return Ok(out); // a complete pad sequence: no more input is read + } + continue; + } + let Some(v) = value(byte) else { continue }; + pads = 0; + match quad { + 0 => { + quad = 1; + left = v; + } + 1 => { + quad = 2; + out.push((left << 2) | (v >> 4)); + left = v & 0x0f; + } + 2 => { + quad = 3; + out.push((left << 4) | (v >> 2)); + left = v & 0x03; + } + _ => { + quad = 0; + out.push((left << 6) | v); + left = 0; + } + } + } + match quad { + 0 => Ok(out), + 1 => Err(format!( + "Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4", + out.len() / 3 * 4 + 1 + )), + _ => Err("Incorrect padding".into()), + } +} + +/// `Vision.normalize` for the formats `strata-vision`'s decoder reads directly (JPEG, PNG, BMP, +/// GIF). Anything else needs an image library to convert it to PNG first. +pub fn is_native_image_format(data: &[u8]) -> bool { + data.starts_with(&[0xFF, 0xD8, 0xFF]) + || data.starts_with(b"\x89PNG\r\n\x1a\n") + || data.starts_with(b"BM") + || data.starts_with(b"GIF87a") + || data.starts_with(b"GIF89a") +} + +/// `Service.prepare`'s pad expansion: one `<|image_pad|>` per image becomes `counts[k]` of them. Only +/// the markers the template writes for an image (right after `<|vision_start|>`) are images; the +/// same text inside a message is kept as `literal` plain text (the ids of the pad text tokenized +/// without special parsing). +pub fn expand_image_pads( + ids: &[u32], + pad: u32, + start: u32, + literal: &[u32], + counts: &[usize], +) -> Result, String> { + let mut out = Vec::with_capacity(ids.len()); + let mut k = 0usize; + for (j, id) in ids.iter().enumerate() { + if *id == pad && j > 0 && ids[j - 1] == start && k < counts.len() { + out.extend(std::iter::repeat_n(pad, counts[k])); + k += 1; + } else if *id == pad { + out.extend_from_slice(literal); + } else { + out.push(*id); + } + } + if k != counts.len() { + return Err("the prompt and its images do not match".into()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn record(n: i32, nx: i32, ny: i32, width: i32, seed: f32) -> Vec { + let mut out = Vec::new(); + for v in [SVE1_MAGIC, n, nx, ny, width] { + out.extend_from_slice(&v.to_le_bytes()); + } + for i in 0..n * width { + out.extend_from_slice(&(seed + i as f32 * 0.5).to_le_bytes()); + } + out + } + + #[test] + fn identity_positions_for_text() { + let ids: Vec = vec![5, 6, 7]; + let positions = build_positions(&ids, 8, &Embeddings::default(), 4, IMAGE_PAD_ID).unwrap(); + assert_eq!(positions.table, identity_table(8)); + assert!(positions.images.is_empty()); + } + + #[test] + fn an_image_shares_t_and_text_continues_after_its_larger_side() { + let file = record(6, 3, 2, 4, 1.0); + let embeddings = parse_embeddings(&file, 4).unwrap(); + let p = IMAGE_PAD_ID; + let ids = vec![1, p, p, p, p, p, p, 9]; + let positions = build_positions(&ids, 12, &embeddings, 4, p).unwrap(); + assert_eq!(positions.table[0], [0, 0, 0]); + assert_eq!(positions.table[1], [1, 1, 1]); + assert_eq!(positions.table[3], [1, 1, 3]); + assert_eq!(positions.table[4], [1, 2, 1]); + assert_eq!(positions.table[6], [1, 2, 3]); + // the text after the image: p = 1 + max(3, 2) = 4 + assert_eq!(positions.table[7], [4, 4, 4]); + assert_eq!(positions.table[8], [5, 5, 5]); + assert_eq!(positions.row_offset[1], Some(0)); + assert_eq!(positions.row_offset[2], Some(4)); + assert_eq!(positions.row_offset[0], None); + } + + #[test] + fn every_failure_has_the_engines_words() { + let one = record(1, 1, 1, 4, 1.0); + let p = IMAGE_PAD_ID; + let embed = |bytes: &[u8]| parse_embeddings(bytes, 4); + assert_eq!( + embed(&one[..12]).unwrap_err(), + "bad embeddings file (expected strata-vision records of width 4)" + ); + assert_eq!( + embed(&one[..one.len() - 3]).unwrap_err(), + "short embeddings file" + ); + assert!(embed(&record(1, 1, 1, 8, 1.0)).is_err()); + assert!(embed(&record(6, 3, 3, 4, 1.0)).is_err()); + let embeddings = embed(&one).unwrap(); + assert_eq!( + build_positions(&[1, p, 2, p, 3], 16, &embeddings, 4, p).unwrap_err(), + "the prompt has more images than the embeddings file" + ); + assert_eq!( + build_positions(&[1, 2], 16, &embeddings, 4, p).unwrap_err(), + "the embeddings file has more images than the prompt" + ); + assert_eq!( + build_positions(&[1, p], 16, &embeddings, 4, p).unwrap_err(), + "the prompt cannot end in an image" + ); + let six = embed(&record(6, 3, 2, 4, 0.0)).unwrap(); + assert_eq!( + build_positions(&[1, p, p, 2, 3], 16, &six, 4, p).unwrap_err(), + "image 1 has 6 rows but fewer <|image_pad|> tokens" + ); + assert_eq!( + build_positions(&[1, 2, 3, 4, 5], 3, &Embeddings::default(), 4, p).unwrap_err(), + "the prompt is longer than the position table" + ); + } + + #[test] + fn sources_follow_the_frontends() { + assert_eq!( + image_source(&json!({"type": "image_url", "image_url": {"url": "https://x/y.png"}})), + "https://x/y.png" + ); + assert_eq!( + image_source(&json!({"type": "image_url", "image_url": "data:abc"})), + "data:abc" + ); + assert_eq!( + image_source(&json!({"type": "input_image", "image_url": "file:///a.png"})), + "file:///a.png" + ); + assert_eq!( + image_source( + &json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}) + ), + "data:image/jpeg;base64,QQ==" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"type": "base64", "data": "QQ=="}})), + "data:image/png;base64,QQ==" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"type": "url", "url": "http://u"}})), + "http://u" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"path": "/p.png"}})), + "/p.png" + ); + assert_eq!(image_source(&json!({"type": "image"})), ""); + assert!(is_image_part(&json!({"type": "input_image"}))); + assert!(!is_image_part(&json!({"type": "text"}))); + } + + #[test] + fn only_markers_after_vision_start_are_images() { + let (pad, start) = (9, 8); + let ids = [1, start, pad, 7, pad, 2, start, pad, 3]; + let out = expand_image_pads(&ids, pad, start, &[50, 51], &[3, 2]).unwrap(); + assert_eq!(out, vec![1, 8, 9, 9, 9, 7, 50, 51, 2, 8, 9, 9, 3]); + // More markers than images: the surplus marker stays plain text (as in the Original). + assert_eq!( + expand_image_pads(&ids, pad, start, &[50], &[3]).unwrap(), + vec![1, 8, 9, 9, 9, 7, 50, 2, 8, 50, 3] + ); + // More images than markers is the error. + assert_eq!( + expand_image_pads(&ids, pad, start, &[50], &[1, 1, 1]).unwrap_err(), + "the prompt and its images do not match" + ); + } + + #[test] + fn native_formats_pass_through() { + assert!(is_native_image_format(&[0xFF, 0xD8, 0xFF, 0xE0])); + assert!(is_native_image_format(b"\x89PNG\r\n\x1a\nrest")); + assert!(is_native_image_format(b"BM....")); + assert!(is_native_image_format(b"GIF89a..")); + assert!(!is_native_image_format(b"RIFF....WEBP")); + assert!(!is_native_image_format(b"")); + } + + #[test] + fn base64_matches_pythons_lenient_decoder() { + assert_eq!(b64decode("QQ==").unwrap(), b"A"); + assert_eq!(b64decode("QUI=").unwrap(), b"AB"); + assert_eq!(b64decode("QUJD").unwrap(), b"ABC"); + assert_eq!(b64decode("QU\nJD").unwrap(), b"ABC"); + assert_eq!(b64decode("").unwrap(), b""); + assert_eq!(b64decode("QQ").unwrap_err(), "Incorrect padding"); + assert!( + b64decode("Q") + .unwrap_err() + .contains("1 more than a multiple of 4") + ); + } +} diff --git a/crates/serving-policy/src/watchdog.rs b/crates/serving-policy/src/watchdog.rs new file mode 100644 index 00000000..ac249050 --- /dev/null +++ b/crates/serving-policy/src/watchdog.rs @@ -0,0 +1,231 @@ +//! The stall watchdog (issue #29 of the Original): `include/strata/core/progress.hpp` and the +//! watchdog thread in `src/program/generate.cpp` (`--serve`). +//! +//! The engine's host loop and the GPU wait on each other through flags; a protocol bug there does +//! not crash, it spins. A request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 60, +//! `0` = off) ends the engine with the stage it was stuck in, so the server starts it again instead +//! of hanging. Tokens, prompt chunks and verify windows *beat*; `ticks` (layers served) tells a slow +//! step from a stopped one in the report. +//! +//! [`StallWatchdog`] is the thread's decision logic with injected time: poll it once a second with +//! a snapshot of the progress counters. [`Stage`] formats the stage text of the report. + +/// `STRATA_WATCHDOG_S` default: one step (a prompt layer, a verify window) takes seconds. +pub const DEFAULT_LIMIT_S: i64 = 60; + +/// C `atoi`: optional whitespace and sign, then digits; anything else is `0`. +pub fn atoi(text: &str) -> i64 { + let trimmed = text.trim_start(); + let (negative, digits) = match trimmed.as_bytes().first() { + Some(b'-') => (true, &trimmed[1..]), + Some(b'+') => (false, &trimmed[1..]), + _ => (false, trimmed), + }; + let mut value: i64 = 0; + for byte in digits.bytes() { + if !byte.is_ascii_digit() { + break; + } + value = value + .saturating_mul(10) + .saturating_add(i64::from(byte - b'0')); + } + if negative { -value } else { value } +} + +/// The limit in seconds from the environment variable's value (`None` = unset); `<= 0` disables. +pub fn limit_from_env(value: Option<&str>) -> i64 { + value.map_or(DEFAULT_LIMIT_S, atoi) +} + +/// The counters the engine publishes (`core::Progress`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Counters { + /// Heartbeats: tokens, prompt chunks, verify windows. + pub beats: u64, + /// A request is running. + pub busy: bool, + /// Layers served. + pub ticks: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + Healthy, + /// No heartbeat for the limit during a request: stop the engine. `layers_since` is the number + /// of layers served since the last beat (0 = stopped, more = slow). + Stalled { + quiet_ms: u64, + layers_since: u64, + }, +} + +#[derive(Clone, Debug)] +pub struct StallWatchdog { + limit_ms: Option, + last_beats: u64, + ticks_at: u64, + since_ms: u64, +} + +impl StallWatchdog { + /// `limit_s <= 0` builds a watchdog that never fires (the Original starts no thread then). + pub fn new(limit_s: i64, now_ms: u64, counters: Counters) -> Self { + Self { + limit_ms: u64::try_from(limit_s) + .ok() + .filter(|s| *s > 0) + .map(|s| s.saturating_mul(1000)), + last_beats: counters.beats, + ticks_at: counters.ticks, + since_ms: now_ms, + } + } + + pub fn enabled(&self) -> bool { + self.limit_ms.is_some() + } + + /// One poll (the Original sleeps one second between polls). + pub fn poll(&mut self, now_ms: u64, counters: Counters) -> Verdict { + let Some(limit) = self.limit_ms else { + return Verdict::Healthy; + }; + if !counters.busy || counters.beats != self.last_beats { + self.last_beats = counters.beats; + self.ticks_at = counters.ticks; + self.since_ms = now_ms; + return Verdict::Healthy; + } + let quiet = now_ms.saturating_sub(self.since_ms); + if quiet < limit { + return Verdict::Healthy; + } + Verdict::Stalled { + quiet_ms: quiet, + layers_since: counters.ticks.wrapping_sub(self.ticks_at), + } + } +} + +/// `stage_text()`: `" "`, plus the prompt chunk a batched read is in (#251). +pub fn stage_text(location: &str, detail: i64, chunk: i64) -> String { + let mut text = format!("{location} {detail}"); + if chunk >= 0 { + text.push_str(&format!(" of the prompt chunk from token {chunk}")); + } + text +} + +/// The line the watchdog prints before it stops the engine. +pub fn stall_message(limit_s: i64, stage: &str) -> String { + format!( + "strata serve: no progress for {limit_s} s during a request ({stage}) - stopping the engine so the server starts it again (issue #29)" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn busy(beats: u64, ticks: u64) -> Counters { + Counters { + beats, + busy: true, + ticks, + } + } + + #[test] + fn atoi_follows_c() { + for (text, want) in [ + ("60", 60), + (" 12abc", 12), + ("-5", -5), + ("+7", 7), + ("abc", 0), + ("", 0), + ("0", 0), + ("3.9", 3), + ("99999999999999999999999", i64::MAX), + ] { + assert_eq!(atoi(text), want, "{text:?}"); + } + assert_eq!(limit_from_env(None), 60); + assert_eq!(limit_from_env(Some("0")), 0); + assert_eq!(limit_from_env(Some("x")), 0); + assert_eq!(limit_from_env(Some("5")), 5); + } + + #[test] + fn fires_only_after_the_limit_of_silence_during_a_request() { + let mut dog = StallWatchdog::new(3, 0, busy(0, 0)); + assert_eq!(dog.poll(1000, busy(0, 0)), Verdict::Healthy); + assert_eq!(dog.poll(2000, busy(0, 5)), Verdict::Healthy); + assert_eq!(dog.poll(2999, busy(0, 9)), Verdict::Healthy); + assert_eq!( + dog.poll(3000, busy(0, 9)), + Verdict::Stalled { + quiet_ms: 3000, + layers_since: 9 + } + ); + } + + #[test] + fn a_beat_restarts_the_clock_and_the_layer_baseline() { + let mut dog = StallWatchdog::new(2, 0, busy(0, 0)); + assert_eq!(dog.poll(1900, busy(1, 40)), Verdict::Healthy); + assert_eq!(dog.poll(3800, busy(1, 40)), Verdict::Healthy); + assert_eq!( + dog.poll(3900, busy(1, 40)), + Verdict::Stalled { + quiet_ms: 2000, + layers_since: 0 + } + ); + } + + #[test] + fn idle_engine_never_stalls_and_resets_the_baseline() { + let mut dog = StallWatchdog::new(2, 0, Counters::default()); + for second in 1..100 { + let idle = Counters { + beats: 0, + busy: false, + ticks: second, + }; + assert_eq!(dog.poll(second * 1000, idle), Verdict::Healthy); + } + // The clock restarts at the last idle poll (99 s), not at the request's start: the Original polls once a + // second, so a request can be flagged up to one poll early. + assert_eq!(dog.poll(100_000, busy(0, 100)), Verdict::Healthy); + assert_eq!(dog.poll(100_999, busy(0, 100)), Verdict::Healthy); + assert!(matches!( + dog.poll(101_000, busy(0, 100)), + Verdict::Stalled { .. } + )); + } + + #[test] + fn a_disabled_watchdog_never_fires() { + for limit in [0, -1] { + let mut dog = StallWatchdog::new(limit, 0, busy(0, 0)); + assert!(!dog.enabled()); + assert_eq!(dog.poll(10_000_000, busy(0, 0)), Verdict::Healthy); + } + } + + #[test] + fn stage_text_names_the_prompt_chunk() { + assert_eq!(stage_text("layer", 12, -1), "layer 12"); + assert_eq!( + stage_text("prefill", 3, 8192), + "prefill 3 of the prompt chunk from token 8192" + ); + assert_eq!( + stall_message(60, "layer 12"), + "strata serve: no progress for 60 s during a request (layer 12) - stopping the engine so the server starts it again (issue #29)" + ); + } +} diff --git a/crates/serving-policy/tests/fixtures/cvec_oracle.json b/crates/serving-policy/tests/fixtures/cvec_oracle.json new file mode 100644 index 00000000..c5c853a6 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/cvec_oracle.json @@ -0,0 +1,32 @@ +{ + "source": "src/program/generate.cpp load_control_vectors (verbatim) over GGUF files written by gen_cvec_fixtures.cpp", + "n_layers": 6, "n_embd": 5, "hc": 2, + "blobs": ["474755460300000003000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e310100000005000000000000000000000000000000000000000b00000000000000646972656374696f6e2e320100000005000000000000000000000020000000000000000b00000000000000646972656374696f6e2e340100000005000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000003f295caf3f52b8de3f7c14ce3f52b81e40000000000000000000000000000080bfb81e05be90c2753eb047e13d48e17a3f0000000000000000000000000000c03f14ae1740295c2f403e0a274052b85e40000000000000000000000000","474755460300000002000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e320100000005000000000000000000000000000000000000000b00000000000000646972656374696f6e2e33010000000500000000000000000000002000000000000000000000000000000000000080beec51b83ed7a3f03e08d7a33dd7a3303f0000000000000000000000000000204014ae5740295c6f403e0a6740295c8f40000000000000000000000000","474755460300000001000000000000000100000000000000140000000000000067656e6572616c2e6172636869746563747572650800000005000000000000006c6c616d610b00000000000000646972656374696f6e2e31010000000500000000000000000000000000000000000000000000000000000000000000000000000000003f295caf3f52b8de3f7c14ce3f52b81e40000000000000000000000000","474755460300000001000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e3465787007000000000000006f746865722e310100000005000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003f295caf3f52b8de3f7c14ce3f52b81e40000000000000000000000000","474755460300000001000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e3101000000060000000000000000000000000000000000000000000000000000000000000000000000000000000000003f295caf3f52b8de3f7c14ce3f52b81e40666636400000000000000000","474755460300000001000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e3101000000050000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","474755460300000005000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e300100000005000000000000000000000000000000000000000b00000000000000646972656374696f6e2e360100000005000000000000000000000020000000000000000c00000000000000646972656374696f6e2e39390100000005000000000000000000000040000000000000000d00000000000000646972656374696f6e2e6162630100000005000000000000000000000060000000000000000c00000000000000646972656374696f6e2e3033010000000500000000000000000000008000000000000000000000000000084185eb15410ad71b418fc2194114ae27410000000000000000000000000000084185eb15410ad71b418fc2194114ae27410000000000000000000000000000084185eb15410ad71b418fc2194114ae27410000000000000000000000000000084185eb15410ad71b418fc2194114ae27410000000000000000000000000000803e295c8f3f52b8be3f7b14ae3f52b80e40000000000000000000000000","474755460300000002000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000008000000000000007177656e346578700b00000000000000646972656374696f6e2e310100000005000000000000000000000000000000000000000b00000000000000646972656374696f6e2e3201000000050000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","474755460300000001000000000000000200000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f721800000000000000636f6e74726f6c766563746f722e6d6f64656c5f68696e740800000005000000000000006c6c616d610b00000000000000646972656374696f6e2e3101000000050000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003f295caf3f52b8de3f7c14ce3f52b81e40000000000000000000000000","474755460300000001000000000000000100000000000000140000000000000067656e6572616c2e617263686974656374757265080000000d00000000000000636f6e74726f6c766563746f720b00000000000000646972656374696f6e2e3501000000050000000000000000000000000000000000000000000000000000000000c0bfae4721bfb81e85be14aec7be90c2f53e000000000000000000000000"], + "cases": [ + {"name": "add, one file, default range", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1056964608,1068457001,1071560786,1070470268,1075755090,3212836864,3188006584,1047904912,1038174128,1065017672,0,0,0,0,0,1069547520,1075293716,1076845609,1076300350,1079949394,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,0,1065353216,0]}}, + {"name": "add, two files scaled and summed", "files": [[0, 1056964608],[1, 3221225472]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1048576000,1060068393,1063172178,1062081660,1067366482,0,3209229763,3209816965,3184986680,3210991370,3231711232,3235360276,3236912169,3236366910,3239009321,1061158912,1066905108,1068457001,1067911742,1071560786,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,1065353216,1065353216,0]}}, + {"name": "project, one file", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": -1, "ok": true, "err": "", "summary": "project:1-5", "up": {"mode": 0, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1040799755,1052518722,1055849081,1054678956,1059737204,3207785947,3183089175,1043056032,1033729321,1060067773,0,0,0,0,0,1048781743,1053766466,1055886406,1055141563,1058545447,0,0,0,0,0], "s_bits": [0,1080989028,1068966475,0,1086023510,0]}}, + {"name": "project, two files", "files": [[0, 1069547520],[1, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": -1, "ok": true, "err": "", "summary": "project:1-5", "up": {"mode": 0, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1040799755,1052518722,1055849082,1054678956,1059737204,3206127572,1030209752,1049737537,1034686251,1061002695,1050616516,1054245851,1055789361,1055247047,1057920495,1048781743,1053766465,1055886406,1055141563,1058545447,0,0,0,0,0], "s_bits": [0,1085468683,1077584665,1090564595,1091341696,0]}}, + {"name": "add, layer range 2..3", "files": [[0, 1065353216],[1, 1065353216]], "first": 2, "last": 3, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:2-3", "up": {"mode": 1, "first": 2, "last": 3, "dir_bits": [0,0,0,0,0,0,0,0,0,0,3214934016,1047233824,1060487824,1044549468,1070973584,1075838976,1079488020,1081039913,1080494654,1083137065,0,0,0,0,0,0,0,0,0,0], "s_bits": [0,0,1065353216,1065353216,0,0]}}, + {"name": "add, range past the model", "files": [[0, 1065353216]], "first": 1, "last": 99, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1056964608,1068457001,1071560786,1070470268,1075755090,3212836864,3188006584,1047904912,1038174128,1065017672,0,0,0,0,0,1069547520,1075293716,1076845609,1076300350,1079949394,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,0,1065353216,0]}}, + {"name": "project, range first only", "files": [[0, 1065353216]], "first": 3, "last": -1, "mode": "project", "single": -1, "ok": true, "err": "", "summary": "project:3-5", "up": {"mode": 0, "first": 3, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1048781743,1053766466,1055886406,1055141563,1058545447,0,0,0,0,0], "s_bits": [0,0,0,0,1086023510,0]}}, + {"name": "project single:2", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": 2, "ok": true, "err": "", "summary": "project:1-5:single2", "up": {"mode": 0, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,3207785947,3183089175,1043056032,1033729321,1060067773,3207785947,3183089175,1043056032,1033729321,1060067773,3207785947,3183089175,1043056032,1033729321,1060067773,3207785947,3183089175,1043056032,1033729321,1060067773,3207785947,3183089175,1043056032,1033729321,1060067773], "s_bits": [0,1068966475,1068966475,1068966475,1068966475,1068966475]}}, + {"name": "project single:2 over a range", "files": [[0, 1065353216],[1, 1065353216]], "first": 2, "last": 5, "mode": "project", "single": 2, "ok": true, "err": "", "summary": "project:2-5:single2", "up": {"mode": 0, "first": 2, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,3205490886,1037292959,1050901279,1034878561,1061176135,3205490886,1037292959,1050901279,1034878561,1061176135,3205490886,1037292959,1050901279,1034878561,1061176135,3205490886,1037292959,1050901279,1034878561,1061176135], "s_bits": [0,0,1074679768,1074679768,1074679768,1074679768]}}, + {"name": "add ignores single", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": 2, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1056964608,1068457001,1071560786,1070470268,1075755090,3212836864,3188006584,1047904912,1038174128,1065017672,0,0,0,0,0,1069547520,1075293716,1076845609,1076300350,1079949394,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,0,1065353216,0]}}, + {"name": "project single without a direction", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": 3, "ok": false, "err": "--cvec-dir single:3: the vector has no direction for that layer", "summary": ""}, + {"name": "project single past the model", "files": [[0, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": 6, "ok": false, "err": "--cvec-dir single:6: the vector has no direction for that layer", "summary": ""}, + {"name": "scale zero adds nothing but still counts as found", "files": [[0, 0]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,0,1065353216,0]}}, + {"name": "scale zero in project mode steers nothing", "files": [[0, 0]], "first": -1, "last": -1, "mode": "project", "single": -1, "ok": false, "err": "the control vector has no direction in layers 1..5", "summary": ""}, + {"name": "layers 0 / past-model / non-numeric ignored, 03 is layer 3", "files": [[6, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1048576000,1066359849,1069463634,1068373115,1074706514,0,0,0,0,0,0,0,0,0,0], "s_bits": [0,0,0,1065353216,0,0]}}, + {"name": "not a control vector", "files": [[2, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": false, "err": "FILE2: not a control vector GGUF (general.architecture is not 'controlvector')", "summary": ""}, + {"name": "no direction tensors", "files": [[3, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": false, "err": "FILE3: no direction. tensors", "summary": ""}, + {"name": "wrong tensor size", "files": [[4, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": false, "err": "FILE4: direction.1 must be 5 f32", "summary": ""}, + {"name": "wrong tensor type", "files": [[5, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": false, "err": "FILE5: direction.1 must be 5 f32", "summary": ""}, + {"name": "all-zero directions in project mode", "files": [[7, 1065353216]], "first": -1, "last": -1, "mode": "project", "single": -1, "ok": false, "err": "the control vector has no direction in layers 1..5", "summary": ""}, + {"name": "all-zero directions in add mode", "files": [[7, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], "s_bits": [0,1065353216,1065353216,0,0,0]}}, + {"name": "another model's hint still loads", "files": [[8, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,1056964608,1068457001,1071560786,1070470268,1075755090,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], "s_bits": [0,1065353216,0,0,0,0]}}, + {"name": "no hint", "files": [[9, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": true, "err": "", "summary": "add:1-5", "up": {"mode": 1, "first": 1, "last": 5, "dir_bits": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3217031168,3206629294,3196395192,3200757268,1056293520], "s_bits": [0,0,0,0,0,1065353216]}}, + {"name": "second file bad", "files": [[0, 1065353216],[3, 1065353216]], "first": -1, "last": -1, "mode": "add", "single": -1, "ok": false, "err": "FILE3: no direction. tensors", "summary": ""}, + {"name": "no steered layer in the range", "files": [[0, 1065353216]], "first": 5, "last": 5, "mode": "add", "single": -1, "ok": false, "err": "the control vector has no direction in layers 5..5", "summary": ""} + ] +} diff --git a/crates/serving-policy/tests/fixtures/host_oracle.json b/crates/serving-policy/tests/fixtures/host_oracle.json new file mode 100644 index 00000000..badee882 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/host_oracle.json @@ -0,0 +1,172 @@ +{ + "source": "include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)", + "parse": [ + {"text": "1", "ok": true, "value": 1}, + {"text": "2", "ok": true, "value": 2}, + {"text": "128", "ok": true, "value": 128}, + {"text": "9223372036854775807", "ok": true, "value": 9223372036854775807}, + {"text": "9223372036854775808", "ok": false, "value": -777}, + {"text": "0", "ok": false, "value": -777}, + {"text": "00", "ok": false, "value": -777}, + {"text": "007", "ok": true, "value": 7}, + {"text": "-1", "ok": false, "value": -777}, + {"text": "+1", "ok": false, "value": -777}, + {"text": " 1", "ok": false, "value": -777}, + {"text": "1 ", "ok": false, "value": -777}, + {"text": "1x", "ok": false, "value": -777}, + {"text": "x", "ok": false, "value": -777}, + {"text": "", "ok": false, "value": -777}, + {"text": "1.5", "ok": false, "value": -777}, + {"text": "99999999999999999999", "ok": false, "value": -777}, + {"text": "12345678901234567890", "ok": false, "value": -777} + ], + "selected": [ + {"total": -1, "stride": -1, "rows": 0, "kept": []}, + {"total": -1, "stride": 0, "rows": 0, "kept": []}, + {"total": -1, "stride": 1, "rows": 0, "kept": []}, + {"total": -1, "stride": 2, "rows": 0, "kept": []}, + {"total": -1, "stride": 3, "rows": 0, "kept": []}, + {"total": -1, "stride": 4, "rows": 0, "kept": []}, + {"total": -1, "stride": 7, "rows": 0, "kept": []}, + {"total": -1, "stride": 10, "rows": 0, "kept": []}, + {"total": -1, "stride": 64, "rows": 0, "kept": []}, + {"total": -1, "stride": 1000, "rows": 0, "kept": []}, + {"total": 0, "stride": -1, "rows": 0, "kept": []}, + {"total": 0, "stride": 0, "rows": 0, "kept": []}, + {"total": 0, "stride": 1, "rows": 0, "kept": []}, + {"total": 0, "stride": 2, "rows": 0, "kept": []}, + {"total": 0, "stride": 3, "rows": 0, "kept": []}, + {"total": 0, "stride": 4, "rows": 0, "kept": []}, + {"total": 0, "stride": 7, "rows": 0, "kept": []}, + {"total": 0, "stride": 10, "rows": 0, "kept": []}, + {"total": 0, "stride": 64, "rows": 0, "kept": []}, + {"total": 0, "stride": 1000, "rows": 0, "kept": []}, + {"total": 1, "stride": -1, "rows": 0, "kept": []}, + {"total": 1, "stride": 0, "rows": 0, "kept": []}, + {"total": 1, "stride": 1, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 2, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 3, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 4, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 7, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 10, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 64, "rows": 1, "kept": [0]}, + {"total": 1, "stride": 1000, "rows": 1, "kept": [0]}, + {"total": 2, "stride": -1, "rows": 0, "kept": []}, + {"total": 2, "stride": 0, "rows": 0, "kept": []}, + {"total": 2, "stride": 1, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 2, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 3, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 4, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 7, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 10, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 64, "rows": 2, "kept": [0,1]}, + {"total": 2, "stride": 1000, "rows": 2, "kept": [0,1]}, + {"total": 5, "stride": -1, "rows": 0, "kept": []}, + {"total": 5, "stride": 0, "rows": 0, "kept": []}, + {"total": 5, "stride": 1, "rows": 5, "kept": [0,1,2,3,4]}, + {"total": 5, "stride": 2, "rows": 3, "kept": [0,2,4]}, + {"total": 5, "stride": 3, "rows": 3, "kept": [0,3,4]}, + {"total": 5, "stride": 4, "rows": 2, "kept": [0,4]}, + {"total": 5, "stride": 7, "rows": 2, "kept": [0,4]}, + {"total": 5, "stride": 10, "rows": 2, "kept": [0,4]}, + {"total": 5, "stride": 64, "rows": 2, "kept": [0,4]}, + {"total": 5, "stride": 1000, "rows": 2, "kept": [0,4]}, + {"total": 9, "stride": -1, "rows": 0, "kept": []}, + {"total": 9, "stride": 0, "rows": 0, "kept": []}, + {"total": 9, "stride": 1, "rows": 9, "kept": [0,1,2,3,4,5,6,7,8]}, + {"total": 9, "stride": 2, "rows": 5, "kept": [0,2,4,6,8]}, + {"total": 9, "stride": 3, "rows": 4, "kept": [0,3,6,8]}, + {"total": 9, "stride": 4, "rows": 3, "kept": [0,4,8]}, + {"total": 9, "stride": 7, "rows": 3, "kept": [0,7,8]}, + {"total": 9, "stride": 10, "rows": 2, "kept": [0,8]}, + {"total": 9, "stride": 64, "rows": 2, "kept": [0,8]}, + {"total": 9, "stride": 1000, "rows": 2, "kept": [0,8]}, + {"total": 10, "stride": -1, "rows": 0, "kept": []}, + {"total": 10, "stride": 0, "rows": 0, "kept": []}, + {"total": 10, "stride": 1, "rows": 10, "kept": [0,1,2,3,4,5,6,7,8,9]}, + {"total": 10, "stride": 2, "rows": 6, "kept": [0,2,4,6,8,9]}, + {"total": 10, "stride": 3, "rows": 4, "kept": [0,3,6,9]}, + {"total": 10, "stride": 4, "rows": 4, "kept": [0,4,8,9]}, + {"total": 10, "stride": 7, "rows": 3, "kept": [0,7,9]}, + {"total": 10, "stride": 10, "rows": 2, "kept": [0,9]}, + {"total": 10, "stride": 64, "rows": 2, "kept": [0,9]}, + {"total": 10, "stride": 1000, "rows": 2, "kept": [0,9]}, + {"total": 11, "stride": -1, "rows": 0, "kept": []}, + {"total": 11, "stride": 0, "rows": 0, "kept": []}, + {"total": 11, "stride": 1, "rows": 11, "kept": [0,1,2,3,4,5,6,7,8,9,10]}, + {"total": 11, "stride": 2, "rows": 6, "kept": [0,2,4,6,8,10]}, + {"total": 11, "stride": 3, "rows": 5, "kept": [0,3,6,9,10]}, + {"total": 11, "stride": 4, "rows": 4, "kept": [0,4,8,10]}, + {"total": 11, "stride": 7, "rows": 3, "kept": [0,7,10]}, + {"total": 11, "stride": 10, "rows": 2, "kept": [0,10]}, + {"total": 11, "stride": 64, "rows": 2, "kept": [0,10]}, + {"total": 11, "stride": 1000, "rows": 2, "kept": [0,10]}, + {"total": 64, "stride": -1, "rows": 0, "kept": []}, + {"total": 64, "stride": 0, "rows": 0, "kept": []}, + {"total": 64, "stride": 1, "rows": 64, "kept": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63]}, + {"total": 64, "stride": 2, "rows": 33, "kept": [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,63]}, + {"total": 64, "stride": 3, "rows": 22, "kept": [0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63]}, + {"total": 64, "stride": 4, "rows": 17, "kept": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,63]}, + {"total": 64, "stride": 7, "rows": 10, "kept": [0,7,14,21,28,35,42,49,56,63]}, + {"total": 64, "stride": 10, "rows": 8, "kept": [0,10,20,30,40,50,60,63]}, + {"total": 64, "stride": 64, "rows": 2, "kept": [0,63]}, + {"total": 64, "stride": 1000, "rows": 2, "kept": [0,63]}, + {"total": 100, "stride": -1, "rows": 0, "kept": []}, + {"total": 100, "stride": 0, "rows": 0, "kept": []}, + {"total": 100, "stride": 1, "rows": 100, "kept": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]}, + {"total": 100, "stride": 2, "rows": 51, "kept": [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,99]}, + {"total": 100, "stride": 3, "rows": 34, "kept": [0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99]}, + {"total": 100, "stride": 4, "rows": 26, "kept": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,99]}, + {"total": 100, "stride": 7, "rows": 16, "kept": [0,7,14,21,28,35,42,49,56,63,70,77,84,91,98,99]}, + {"total": 100, "stride": 10, "rows": 11, "kept": [0,10,20,30,40,50,60,70,80,90,99]}, + {"total": 100, "stride": 64, "rows": 3, "kept": [0,64,99]}, + {"total": 100, "stride": 1000, "rows": 2, "kept": [0,99]} + ], + "watchdog": [ + {"limit_s": 3, "steps": [ + {"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}, + {"at_ms": 2000, "beats": 0, "busy": true, "ticks": 5, "layers_since": -1}, + {"at_ms": 2999, "beats": 0, "busy": true, "ticks": 9, "layers_since": -1}, + {"at_ms": 3000, "beats": 0, "busy": true, "ticks": 9, "layers_since": 9}, + {"at_ms": 4000, "beats": 0, "busy": true, "ticks": 9, "layers_since": 9} + ]}, + {"limit_s": 2, "steps": [ + {"at_ms": 1900, "beats": 1, "busy": true, "ticks": 40, "layers_since": -1}, + {"at_ms": 3800, "beats": 1, "busy": true, "ticks": 40, "layers_since": -1}, + {"at_ms": 3900, "beats": 1, "busy": true, "ticks": 40, "layers_since": 0}, + {"at_ms": 4000, "beats": 2, "busy": true, "ticks": 41, "layers_since": -1}, + {"at_ms": 5999, "beats": 2, "busy": true, "ticks": 41, "layers_since": -1}, + {"at_ms": 6000, "beats": 2, "busy": true, "ticks": 80, "layers_since": 39} + ]}, + {"limit_s": 2, "steps": [ + {"at_ms": 1000, "beats": 0, "busy": false, "ticks": 1, "layers_since": -1}, + {"at_ms": 2000, "beats": 0, "busy": false, "ticks": 2, "layers_since": -1}, + {"at_ms": 3000, "beats": 0, "busy": false, "ticks": 3, "layers_since": -1}, + {"at_ms": 100000, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97}, + {"at_ms": 101999, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97}, + {"at_ms": 102000, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97} + ]}, + {"limit_s": 0, "steps": [ + {"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}, + {"at_ms": 10000000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1} + ]}, + {"limit_s": -5, "steps": [ + {"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}, + {"at_ms": 10000000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1} + ]}, + {"limit_s": 1, "steps": [ + {"at_ms": 1000, "beats": 0, "busy": true, "ticks": 3, "layers_since": 3}, + {"at_ms": 2000, "beats": 0, "busy": true, "ticks": 3, "layers_since": 3}, + {"at_ms": 3000, "beats": 1, "busy": true, "ticks": 3, "layers_since": -1}, + {"at_ms": 3999, "beats": 1, "busy": true, "ticks": 7, "layers_since": -1}, + {"at_ms": 4000, "beats": 1, "busy": true, "ticks": 7, "layers_since": 4} + ]}, + {"limit_s": 60, "steps": [ + {"at_ms": 59000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}, + {"at_ms": 59999, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}, + {"at_ms": 60000, "beats": 0, "busy": true, "ticks": 12, "layers_since": 12}, + {"at_ms": 61000, "beats": 5, "busy": false, "ticks": 12, "layers_since": -1}, + {"at_ms": 200000, "beats": 5, "busy": true, "ticks": 12, "layers_since": 0} + ]} + ] +} diff --git a/crates/serving-policy/tests/fixtures/reasoning.json b/crates/serving-policy/tests/fixtures/reasoning.json new file mode 100644 index 00000000..7e8152d7 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/reasoning.json @@ -0,0 +1,2476 @@ +{ + "source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real Detokenizer/OutputParser)", + "wrap_up": "\n\nI have thought about this long enough; time to give my answer.\n\n\n", + "cases": [ + { + "pieces_hex": [ + "61", + "62", + "20736f20", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "61", + "62" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c2f", + "61", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "c3", + "61", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "e6", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "ac", + "61" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "3c2f", + "2f7468696e6b3e", + "7468696e6b", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "e6", + "7468696e6b", + "61", + "20736f20", + "ac", + "62", + "78", + "20736f20", + "7468696e6b", + "0a", + "3c2f746869", + "61", + "61" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "68696e6b3e", + "3c74", + "97a5", + "3c74", + "e6", + "3c2f", + "20736f20", + "2f7468696e6b3e", + "7468696e6b", + "61", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c2f746869", + "20736f20", + "78", + "e282", + "e6", + "20736f20", + "3c74", + "78" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "68696e6b3e", + "3c", + "97a5", + "0a", + "6e6b3e", + "3c2f746869", + "68696e6b3e", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "78", + "61", + "ff", + "20736f20", + "61", + "2f", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "78", + "c3", + "2f7468696e6b3e", + "62", + "20736f20", + "ac", + "97a5", + "2f7468696e6b3e", + "20736f20", + "e282", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "78", + "3c", + "e6", + "62", + "a9", + "6e6b3e", + "78", + "62" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 4, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "6e6b3e", + "3c2f", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "62", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "97a5", + "2f", + "ac", + "e6", + "97a5", + "62" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "3c74", + "2f7468696e6b3e", + "e6", + "ff", + "e6", + "3c", + "6e6b3e", + "7468696e6b", + "2f7468696e6b3e", + "a9", + "a9", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "7468696e6b", + "97a5", + "c3", + "78", + "6e6b3e", + "68696e6b3e", + "3c2f7468696e6b3e", + "0a", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "ac", + "6e6b3e", + "3c2f", + "2f", + "e6", + "20736f20", + "20736f20", + "c3", + "3c2f7468696e6b3e", + "62", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "62", + "3c2f746869", + "ff", + "20736f20", + "2f", + "3c", + "e6", + "20736f20", + "ac", + "6e6b3e", + "20736f20", + "a9", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ff", + "3c2f746869", + "0a", + "3c2f7468696e6b3e", + "ff", + "a9", + "2f7468696e6b3e", + "ac", + "3c2f7468696e6b3e", + "3c", + "62" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c2f", + "97a5", + "e282", + "97a5", + "2f" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "62", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "e282", + "20736f20" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "2f7468696e6b3e", + "61", + "78", + "78", + "62", + "68696e6b3e", + "20736f20", + "3c2f", + "3c2f7468696e6b3e", + "62", + "a9" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "2f", + "3c2f7468696e6b3e", + "78", + "c3", + "6e6b3e", + "e282", + "68696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "2f", + "78", + "ac", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "6e6b3e", + "6e6b3e", + "a9", + "c3", + "ac", + "6e6b3e", + "ff", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "6e6b3e", + "3c2f7468696e6b3e", + "3c", + "ac", + "c3", + "62", + "0a", + "e6", + "3c2f746869", + "97a5", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "61", + "20736f20", + "97a5", + "c3", + "3c", + "a9" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 6, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "2f7468696e6b3e", + "c3", + "68696e6b3e", + "97a5", + "2f7468696e6b3e", + "3c", + "ac", + "0a", + "68696e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "2f7468696e6b3e", + "ff", + "ac", + "e6", + "78" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "61", + "e6", + "78", + "7468696e6b", + "61", + "0a", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "3c", + "3c", + "78", + "78", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "3c", + "ac", + "3c2f7468696e6b3e", + "ff", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "ff", + "2f", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e", + "20736f20", + "ff", + "ac", + "ac", + "e282", + "7468696e6b", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "3c2f", + "61", + "c3", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "62", + "3c2f7468696e6b3e", + "78", + "3c2f", + "2f", + "ff", + "0a", + "a9", + "ff", + "20736f20", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "ac", + "3c2f746869", + "0a", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "68696e6b3e", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "2f", + "ac", + "3c2f746869", + "2f7468696e6b3e", + "97a5", + "97a5", + "78", + "78", + "3c2f", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "20736f20", + "3c2f", + "e282", + "3c2f746869", + "2f7468696e6b3e", + "ff", + "ff", + "c3", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 5, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "e282", + "ac", + "e282" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "e6", + "62", + "0a", + "20736f20", + "0a", + "78", + "a9", + "62", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "2f", + "3c2f746869", + "3c74", + "3c2f7468696e6b3e", + "0a", + "ff", + "c3", + "ac", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "3c", + "a9", + "2f", + "3c2f", + "97a5", + "78", + "68696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "ac", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "20736f20", + "68696e6b3e", + "61", + "3c2f7468696e6b3e", + "3c2f7468696e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c2f", + "ff", + "3c2f", + "78", + "6e6b3e", + "68696e6b3e", + "62", + "3c74", + "e6" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "0a", + "3c", + "c3", + "a9", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 4, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "61", + "2f", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "e282", + "3c74", + "62", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "ac", + "0a", + "e282", + "2f7468696e6b3e", + "2f", + "3c", + "0a", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "68696e6b3e", + "2f7468696e6b3e", + "e6", + "2f7468696e6b3e", + "61", + "e282", + "a9", + "3c2f746869", + "3c2f7468696e6b3e", + "e6", + "6e6b3e", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "a9", + "ff", + "97a5", + "3c74", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "ff", + "e6", + "0a", + "3c74", + "7468696e6b", + "78", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "3c2f", + "7468696e6b", + "97a5", + "97a5", + "7468696e6b", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "6e6b3e", + "3c2f746869", + "20736f20", + "2f", + "c3", + "3c", + "ff", + "0a" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "e282", + "3c2f7468696e6b3e", + "3c74", + "97a5", + "78", + "78", + "e6" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ff", + "7468696e6b", + "e282", + "e6", + "20736f20" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "2f7468696e6b3e", + "c3", + "6e6b3e", + "3c2f7468696e6b3e", + "6e6b3e", + "61", + "2f7468696e6b3e", + "78", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "62", + "62", + "78", + "6e6b3e", + "a9", + "2f", + "2f", + "3c", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "78", + "2f7468696e6b3e", + "c3", + "c3", + "61", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "3c", + "2f", + "3c74", + "3c2f746869", + "3c2f", + "3c2f7468696e6b3e", + "3c74", + "e6", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "ff", + "2f", + "ff", + "6e6b3e", + "a9", + "c3", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "97a5", + "2f", + "3c2f746869", + "3c", + "2f7468696e6b3e", + "2f7468696e6b3e", + "a9", + "2f7468696e6b3e", + "62", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "0a", + "68696e6b3e", + "e282", + "3c2f7468696e6b3e", + "a9", + "e6", + "61", + "e282", + "c3" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "20736f20", + "20736f20", + "3c2f746869", + "68696e6b3e", + "c3", + "97a5", + "c3", + "3c2f746869", + "3c", + "ff", + "2f", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 10 + } + }, + { + "pieces_hex": [ + "e6", + "78", + "78", + "20736f20", + "3c", + "61", + "ff", + "2f7468696e6b3e", + "3c2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "a9", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "3c", + "7468696e6b", + "97a5", + "e282", + "2f", + "3c74", + "3c2f", + "6e6b3e" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 5, + "8": 8 + } + }, + { + "pieces_hex": [ + "a9", + "97a5", + "6e6b3e", + "2f", + "2f7468696e6b3e", + "20736f20", + "e6", + "3c2f746869", + "e6", + "3c2f746869", + "20736f20", + "6e6b3e", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 10 + } + }, + { + "pieces_hex": [ + "e282", + "6e6b3e", + "3c2f", + "c3", + "3c2f7468696e6b3e", + "3c2f7468696e6b3e", + "e282", + "ff", + "3c2f", + "3c2f7468696e6b3e", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "3c74", + "a9", + "78", + "61", + "ff", + "0a", + "3c2f7468696e6b3e", + "68696e6b3e", + "3c2f746869", + "e282", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f746869", + "78", + "61", + "a9", + "a9", + "97a5", + "a9", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "ff", + "3c2f746869", + "ac", + "ac", + "ac", + "97a5", + "3c", + "97a5", + "ac", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "7468696e6b", + "e6", + "ac", + "3c2f746869", + "c3", + "a9", + "3c2f7468696e6b3e", + "62", + "a9", + "c3", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 6, + "5": 6, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "2f7468696e6b3e", + "3c74", + "20736f20", + "0a", + "2f7468696e6b3e", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "ff", + "c3", + "62", + "3c2f", + "6e6b3e", + "78", + "ff", + "61", + "0a", + "ff", + "62", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "61", + "62", + "a9", + "97a5", + "61", + "3c", + "2f7468696e6b3e", + "3c2f746869", + "3c74", + "97a5", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "e6", + "2f7468696e6b3e", + "6e6b3e" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "68696e6b3e", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c", + "68696e6b3e", + "2f", + "68696e6b3e", + "3c74", + "3c2f7468696e6b3e", + "2f7468696e6b3e", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "68696e6b3e", + "3c74", + "97a5", + "61", + "a9", + "2f7468696e6b3e", + "a9", + "68696e6b3e", + "2f", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "7468696e6b", + "20736f20", + "ac", + "a9", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "3c74", + "62", + "78", + "a9", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "c3", + "7468696e6b", + "e282", + "ff", + "2f", + "68696e6b3e", + "ac", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "68696e6b3e", + "ff", + "7468696e6b", + "c3", + "20736f20", + "2f", + "ff", + "3c2f" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "68696e6b3e", + "68696e6b3e", + "2f", + "3c74", + "97a5", + "6e6b3e", + "20736f20", + "20736f20", + "3c74", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "61", + "0a", + "62", + "ac", + "3c74", + "3c2f7468696e6b3e", + "7468696e6b", + "78", + "e6", + "e282", + "2f7468696e6b3e", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "ac", + "c3", + "3c", + "ac", + "3c74", + "62", + "78", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 4, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "2f", + "e282", + "2f", + "3c2f7468696e6b3e", + "20736f20", + "ff", + "3c2f746869", + "7468696e6b", + "3c", + "61", + "20736f20" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "0a", + "3c74", + "78", + "68696e6b3e", + "a9", + "3c74", + "61", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "3c2f7468696e6b3e", + "20736f20", + "0a", + "68696e6b3e", + "2f", + "0a", + "c3" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "61", + "3c2f", + "3c2f", + "e6", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 5, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "7468696e6b", + "62", + "6e6b3e", + "ac", + "2f7468696e6b3e", + "62", + "3c74", + "2f", + "e282", + "3c74", + "97a5" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "ff", + "a9", + "78", + "0a", + "61", + "a9", + "2f", + "3c2f7468696e6b3e", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "ac", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "2f7468696e6b3e", + "68696e6b3e", + "a9", + "97a5", + "68696e6b3e", + "3c2f", + "c3", + "ff", + "78", + "97a5", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c", + "ac", + "6e6b3e", + "6e6b3e", + "3c2f", + "0a", + "3c2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "6e6b3e", + "3c74", + "3c", + "3c2f746869", + "3c", + "2f7468696e6b3e", + "3c2f", + "3c74", + "68696e6b3e", + "ac", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "62", + "0a", + "68696e6b3e", + "61", + "ff", + "62" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "3c", + "3c2f7468696e6b3e", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "c3", + "68696e6b3e", + "78", + "78", + "3c", + "2f", + "e282", + "c3", + "a9", + "6e6b3e", + "e6" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 8, + "8": 8 + } + }, + { + "pieces_hex": [ + "ff", + "62", + "3c74", + "68696e6b3e", + "3c74", + "2f", + "6e6b3e", + "3c2f7468696e6b3e", + "2f", + "7468696e6b", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "0a", + "a9", + "3c", + "c3", + "a9", + "78", + "3c", + "6e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": 8 + } + }, + { + "pieces_hex": [ + "e6", + "ac", + "0a" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "2f7468696e6b3e", + "62", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ac", + "68696e6b3e", + "3c2f", + "3c2f746869", + "c3", + "3c", + "0a", + "a9", + "3c74" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 7, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f746869", + "2f", + "e282", + "e6", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 4, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "68696e6b3e", + "2f7468696e6b3e", + "e282", + "6e6b3e", + "2f7468696e6b3e", + "c3", + "e6", + "6e6b3e", + "6e6b3e", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + } + ], + "parse": [ + { + "request": null, + "default": 0, + "ok": null + }, + { + "request": {}, + "default": 0, + "ok": null + }, + { + "request": { + "reasoning_budget_tokens": 20 + }, + "default": 0, + "ok": 20 + }, + { + "request": { + "reasoning_budget_tokens": 20.0 + }, + "default": 0, + "ok": 20 + }, + { + "request": { + "reasoning_budget_tokens": 0 + }, + "default": 50, + "ok": null + }, + { + "request": { + "reasoning_budget_tokens": -1 + }, + "default": 50, + "ok": null + }, + { + "request": {}, + "default": 50, + "ok": 50 + }, + { + "request": { + "reasoning_budget_tokens": null + }, + "default": 50, + "ok": 50 + }, + { + "request": { + "reasoning_budget_tokens": true + }, + "default": 0, + "error": "reasoning_budget_tokens=True: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": "5" + }, + "default": 0, + "error": "reasoning_budget_tokens='5': expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": 2.5 + }, + "default": 0, + "error": "reasoning_budget_tokens=2.5: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": [ + 1 + ] + }, + "default": 0, + "error": "reasoning_budget_tokens=[1]: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": 10000 + }, + "default": 0, + "ok": 10000 + } + ] +} diff --git a/crates/serving-policy/tests/fixtures/shared.json b/crates/serving-policy/tests/fixtures/shared.json new file mode 100644 index 00000000..a271e79b --- /dev/null +++ b/crates/serving-policy/tests/fixtures/shared.json @@ -0,0 +1,631 @@ +{ + "source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)", + "clean": [ + { + "input": null, + "ok": {} + }, + { + "input": {}, + "ok": {} + }, + { + "input": [], + "error": "defaults must be an object" + }, + { + "input": "x", + "error": "defaults must be an object" + }, + { + "input": 5, + "error": "defaults must be an object" + }, + { + "input": { + "temperature": 0.7 + }, + "ok": { + "temperature": 0.7 + } + }, + { + "input": { + "temperature": 1 + }, + "ok": { + "temperature": 1.0 + } + }, + { + "input": { + "temperature": 0 + }, + "ok": { + "temperature": 0.0 + } + }, + { + "input": { + "temperature": 2 + }, + "ok": { + "temperature": 2.0 + } + }, + { + "input": { + "temperature": 2.5 + }, + "error": "temperature: 0..2" + }, + { + "input": { + "temperature": -0.1 + }, + "error": "temperature: 0..2" + }, + { + "input": { + "temperature": true + }, + "error": "temperature: 0..2" + }, + { + "input": { + "temperature": "0.5" + }, + "error": "temperature: 0..2" + }, + { + "input": { + "top_p": 0.9 + }, + "ok": { + "top_p": 0.9 + } + }, + { + "input": { + "top_p": 1 + }, + "ok": { + "top_p": 1.0 + } + }, + { + "input": { + "top_p": 0 + }, + "error": "top_p: 0 < top_p <= 1" + }, + { + "input": { + "top_p": 1.5 + }, + "error": "top_p: 0 < top_p <= 1" + }, + { + "input": { + "top_p": false + }, + "error": "top_p: 0 < top_p <= 1" + }, + { + "input": { + "top_k": 40 + }, + "ok": { + "top_k": 40 + } + }, + { + "input": { + "top_k": 40.0 + }, + "ok": { + "top_k": 40 + } + }, + { + "input": { + "top_k": 40.5 + }, + "error": "top_k: an integer 1..64" + }, + { + "input": { + "top_k": 0 + }, + "error": "top_k: an integer 1..64" + }, + { + "input": { + "top_k": 64 + }, + "ok": { + "top_k": 64 + } + }, + { + "input": { + "top_k": 65 + }, + "error": "top_k: an integer 1..64" + }, + { + "input": { + "top_k": "40" + }, + "error": "top_k: an integer 1..64" + }, + { + "input": { + "seed": 7 + }, + "ok": { + "seed": 7 + } + }, + { + "input": { + "seed": 7.0 + }, + "ok": { + "seed": 7 + } + }, + { + "input": { + "seed": 0 + }, + "error": "seed: a positive integer" + }, + { + "input": { + "seed": -3 + }, + "error": "seed: a positive integer" + }, + { + "input": { + "seed": 1.5 + }, + "error": "seed: a positive integer" + }, + { + "input": { + "seed": 18446744073709551615 + }, + "ok": { + "seed": 18446744073709551615 + } + }, + { + "input": { + "max_tokens": 512 + }, + "ok": { + "max_tokens": 512 + } + }, + { + "input": { + "max_tokens": 0 + }, + "error": "max_tokens: a positive integer" + }, + { + "input": { + "max_tokens": "10" + }, + "error": "max_tokens: a positive integer" + }, + { + "input": { + "reasoning_effort": "none" + }, + "ok": { + "reasoning_effort": "none" + } + }, + { + "input": { + "reasoning_effort": "low" + }, + "ok": { + "reasoning_effort": "low" + } + }, + { + "input": { + "reasoning_effort": "medium" + }, + "ok": { + "reasoning_effort": "medium" + } + }, + { + "input": { + "reasoning_effort": "high" + }, + "ok": { + "reasoning_effort": "high" + } + }, + { + "input": { + "reasoning_effort": "xhigh" + }, + "error": "reasoning_effort: none, low, medium or high" + }, + { + "input": { + "reasoning_effort": 3 + }, + "error": "reasoning_effort: none, low, medium or high" + }, + { + "input": { + "experimental_speed_projection": true + }, + "ok": { + "experimental_speed_projection": true + } + }, + { + "input": { + "experimental_speed_projection": false + }, + "ok": { + "experimental_speed_projection": false + } + }, + { + "input": { + "experimental_speed_projection": 1 + }, + "error": "experimental_speed_projection: true or false" + }, + { + "input": { + "temperature": null, + "top_p": "", + "top_k": null + }, + "ok": {} + }, + { + "input": { + "unknown": 1 + }, + "error": "unknown setting 'unknown'" + }, + { + "input": { + "unknown": null + }, + "ok": {} + }, + { + "input": { + "min_p": 0.1 + }, + "error": "unknown setting 'min_p'" + }, + { + "input": { + "temperature": 0.7, + "top_p": 0.9, + "top_k": 20, + "seed": 11, + "max_tokens": 100, + "reasoning_effort": "medium", + "experimental_speed_projection": false + }, + "ok": { + "temperature": 0.7, + "top_p": 0.9, + "top_k": 20, + "seed": 11, + "max_tokens": 100, + "reasoning_effort": "medium", + "experimental_speed_projection": false + } + } + ], + "config": [ + { + "input": null, + "ok": {}, + "ignored": [] + }, + { + "input": {}, + "ok": {}, + "ignored": [] + }, + { + "input": { + "temperature": 0.7 + }, + "ok": { + "temperature": 0.7 + }, + "ignored": [] + }, + { + "input": { + "temperature": 0 + }, + "ok": { + "temperature": 0.0 + }, + "ignored": [] + }, + { + "input": { + "temperature": -1 + }, + "error": "[strata] config sampling.temperature=-1: expected a number >= 0 (0 = greedy)" + }, + { + "input": { + "temperature": true + }, + "error": "[strata] config sampling.temperature=True: expected a number >= 0 (0 = greedy)" + }, + { + "input": { + "top_p": 0.95 + }, + "ok": { + "top_p": 0.95 + }, + "ignored": [] + }, + { + "input": { + "top_p": 0 + }, + "error": "[strata] config sampling.top_p=0: expected 0 < top_p <= 1" + }, + { + "input": { + "top_p": 1.01 + }, + "error": "[strata] config sampling.top_p=1.01: expected 0 < top_p <= 1" + }, + { + "input": { + "min_p": 0.05 + }, + "ok": { + "min_p": 0.05 + }, + "ignored": [] + }, + { + "input": { + "min_p": 0 + }, + "ok": { + "min_p": 0.0 + }, + "ignored": [] + }, + { + "input": { + "min_p": 2 + }, + "error": "[strata] config sampling.min_p=2: expected 0 <= min_p <= 1" + }, + { + "input": { + "top_k": 40 + }, + "ok": { + "top_k": 40 + }, + "ignored": [] + }, + { + "input": { + "top_k": 0 + }, + "error": "[strata] config sampling.top_k=0: the sampled path takes an integer 1..64" + }, + { + "input": { + "top_k": 65 + }, + "error": "[strata] config sampling.top_k=65: the sampled path takes an integer 1..64" + }, + { + "input": { + "top_k": 20.0 + }, + "ok": { + "top_k": 20 + }, + "ignored": [] + }, + { + "input": { + "top_k": 1.5 + }, + "error": "[strata] config sampling.top_k=1.5: the sampled path takes an integer 1..64" + }, + { + "input": { + "presence_penalty": 0.5 + }, + "ok": { + "presence_penalty": 0.5 + }, + "ignored": [] + }, + { + "input": { + "presence_penalty": -0.5 + }, + "error": "[strata] config sampling.presence_penalty=-0.5: expected a number >= 0" + }, + { + "input": { + "frequency_penalty": 0.25 + }, + "ok": { + "frequency_penalty": 0.25 + }, + "ignored": [] + }, + { + "input": { + "frequency_penalty": -1 + }, + "error": "[strata] config sampling.frequency_penalty=-1: expected a number >= 0" + }, + { + "input": { + "repetition_penalty": 1.1 + }, + "ok": { + "repetition_penalty": 1.1 + }, + "ignored": [] + }, + { + "input": { + "repetition_penalty": 0 + }, + "error": "[strata] config sampling.repetition_penalty=0: expected a number > 0 (1 = off)" + }, + { + "input": { + "penalty_last_n": 128 + }, + "ok": { + "penalty_last_n": 128 + }, + "ignored": [] + }, + { + "input": { + "penalty_last_n": 0 + }, + "ok": { + "penalty_last_n": 0 + }, + "ignored": [] + }, + { + "input": { + "penalty_last_n": -2 + }, + "error": "[strata] config sampling.penalty_last_n=-2: expected a non-negative integer" + }, + { + "input": { + "penalty_last_n": 1.5 + }, + "error": "[strata] config sampling.penalty_last_n=1.5: expected a non-negative integer" + }, + { + "input": { + "seed": 5 + }, + "ok": { + "seed": 5 + }, + "ignored": [] + }, + { + "input": { + "seed": 0 + }, + "error": "[strata] config sampling.seed=0: expected a positive integer" + }, + { + "input": { + "seed": 5.5 + }, + "error": "[strata] config sampling.seed=5.5: expected a positive integer" + }, + { + "input": { + "seed": "5" + }, + "error": "[strata] config sampling.seed='5': expected a positive integer" + }, + { + "input": { + "experimental_speed_projection": true + }, + "ok": { + "experimental_speed_projection": true + }, + "ignored": [] + }, + { + "input": { + "experimental_speed_projection": "yes" + }, + "error": "[strata] config sampling.experimental_speed_projection='yes': expected true or false (the default for requests that leave it out, when the engine has the vector)" + }, + { + "input": { + "temperature": null, + "top_p": null + }, + "ok": {}, + "ignored": [] + }, + { + "input": { + "nonsense": 3 + }, + "ok": {}, + "ignored": [ + "[strata] config sampling.nonsense=3: unknown key, ignored" + ] + }, + { + "input": { + "temperature": 0.6, + "nonsense": 3 + }, + "ok": { + "temperature": 0.6 + }, + "ignored": [ + "[strata] config sampling.nonsense=3: unknown key, ignored" + ] + }, + { + "input": { + "temperature": 0.6, + "top_p": 0.9, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.1, + "frequency_penalty": 0.1, + "repetition_penalty": 1.05, + "penalty_last_n": 64, + "seed": 9 + }, + "ok": { + "temperature": 0.6, + "top_p": 0.9, + "top_k": 30, + "min_p": 0.02, + "presence_penalty": 0.1, + "frequency_penalty": 0.1, + "repetition_penalty": 1.05, + "penalty_last_n": 64, + "seed": 9 + }, + "ignored": [] + } + ] +} diff --git a/crates/serving-policy/tests/fixtures/timings.json b/crates/serving-policy/tests/fixtures/timings.json new file mode 100644 index 00000000..81b64862 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/timings.json @@ -0,0 +1,776 @@ +{ + "source": "serve/server.py request_timings + Service.set_aliases (real code)", + "timings": [ + { + "last": { + "prompt_ms": 250.0, + "decode_ms": 1000.0, + "generated": 50, + "reused": 60 + }, + "prompt_tokens": 300, + "generated": 50, + "timings": { + "cache_n": 60, + "prompt_n": 240, + "prompt_ms": 250.0, + "prompt_per_token_ms": 1.042, + "prompt_per_second": 960.0, + "predicted_n": 50, + "predicted_ms": 1000.0, + "predicted_per_token_ms": 20.0, + "predicted_per_second": 50.0 + } + }, + { + "last": { + "prompt_ms": 250.0, + "decode_ms": 1000.0, + "generated": 50, + "reused": 60 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 60, + "prompt_n": 0, + "prompt_ms": 250.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 10, + "predicted_ms": 1000.0, + "predicted_per_token_ms": 20.0, + "predicted_per_second": 50.0 + } + }, + { + "last": { + "prompt_ms": 250.0, + "decode_ms": 1000.0, + "generated": 50, + "reused": 60 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 60, + "prompt_n": 0, + "prompt_ms": 250.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 1000.0, + "predicted_per_token_ms": 20.0, + "predicted_per_second": 50.0 + } + }, + { + "last": { + "prompt_ms": 250.0, + "decode_ms": 1000.0, + "generated": 50, + "reused": 60 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 60, + "prompt_n": 0, + "prompt_ms": 250.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 7, + "predicted_ms": 1000.0, + "predicted_per_token_ms": 20.0, + "predicted_per_second": 50.0 + } + }, + { + "last": { + "prompt_ms": 0.0, + "decode_ms": 0.0, + "generated": 0, + "reused": 0 + }, + "prompt_tokens": 300, + "generated": 5, + "timings": { + "cache_n": 0, + "prompt_n": 300, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": null, + "predicted_n": 5, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": null + } + }, + { + "last": { + "prompt_ms": 0.0, + "decode_ms": 0.0, + "generated": 0, + "reused": 0 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 0, + "prompt_n": 10, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": null, + "predicted_n": 10, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": null + } + }, + { + "last": { + "prompt_ms": 0.0, + "decode_ms": 0.0, + "generated": 0, + "reused": 0 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 0, + "prompt_n": 0, + "prompt_ms": 0.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 0.0, + "predicted_per_token_ms": null, + "predicted_per_second": null + } + }, + { + "last": { + "prompt_ms": 0.0, + "decode_ms": 0.0, + "generated": 0, + "reused": 0 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 0, + "prompt_n": 50, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": null, + "predicted_n": 7, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": null + } + }, + { + "last": { + "prompt_ms": 12.34567, + "decode_ms": 98.7654, + "generated": 7, + "reused": null + }, + "prompt_tokens": 300, + "generated": 7, + "timings": { + "cache_n": 0, + "prompt_n": 300, + "prompt_ms": 12.3, + "prompt_per_token_ms": 0.041, + "prompt_per_second": 24300.0, + "predicted_n": 7, + "predicted_ms": 98.8, + "predicted_per_token_ms": 14.109, + "predicted_per_second": 70.9 + } + }, + { + "last": { + "prompt_ms": 12.34567, + "decode_ms": 98.7654, + "generated": 7, + "reused": null + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 0, + "prompt_n": 10, + "prompt_ms": 12.3, + "prompt_per_token_ms": 1.235, + "prompt_per_second": 810.0, + "predicted_n": 10, + "predicted_ms": 98.8, + "predicted_per_token_ms": 14.109, + "predicted_per_second": 70.9 + } + }, + { + "last": { + "prompt_ms": 12.34567, + "decode_ms": 98.7654, + "generated": 7, + "reused": null + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 0, + "prompt_n": 0, + "prompt_ms": 12.3, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 98.8, + "predicted_per_token_ms": 14.109, + "predicted_per_second": 70.9 + } + }, + { + "last": { + "prompt_ms": 12.34567, + "decode_ms": 98.7654, + "generated": 7, + "reused": null + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 0, + "prompt_n": 50, + "prompt_ms": 12.3, + "prompt_per_token_ms": 0.247, + "prompt_per_second": 4050.0, + "predicted_n": 7, + "predicted_ms": 98.8, + "predicted_per_token_ms": 14.109, + "predicted_per_second": 70.9 + } + }, + { + "last": { + "prompt_ms": 0.25, + "decode_ms": 0.05, + "generated": 3 + }, + "prompt_tokens": 300, + "generated": 3, + "timings": { + "cache_n": 0, + "prompt_n": 300, + "prompt_ms": 0.2, + "prompt_per_token_ms": 0.001, + "prompt_per_second": 1200000.0, + "predicted_n": 3, + "predicted_ms": 0.1, + "predicted_per_token_ms": 0.017, + "predicted_per_second": 60000.0 + } + }, + { + "last": { + "prompt_ms": 0.25, + "decode_ms": 0.05, + "generated": 3 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 0, + "prompt_n": 10, + "prompt_ms": 0.2, + "prompt_per_token_ms": 0.025, + "prompt_per_second": 40000.0, + "predicted_n": 10, + "predicted_ms": 0.1, + "predicted_per_token_ms": 0.017, + "predicted_per_second": 60000.0 + } + }, + { + "last": { + "prompt_ms": 0.25, + "decode_ms": 0.05, + "generated": 3 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 0, + "prompt_n": 0, + "prompt_ms": 0.2, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 0.1, + "predicted_per_token_ms": 0.017, + "predicted_per_second": 60000.0 + } + }, + { + "last": { + "prompt_ms": 0.25, + "decode_ms": 0.05, + "generated": 3 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 0, + "prompt_n": 50, + "prompt_ms": 0.2, + "prompt_per_token_ms": 0.005, + "prompt_per_second": 200000.0, + "predicted_n": 7, + "predicted_ms": 0.1, + "predicted_per_token_ms": 0.017, + "predicted_per_second": 60000.0 + } + }, + { + "last": { + "prompt_ms": 2.675, + "decode_ms": 1234.55, + "generated": 11, + "reused": 5, + "drafts_offered": 20, + "drafts_accepted": 15 + }, + "prompt_tokens": 300, + "generated": 11, + "timings": { + "cache_n": 5, + "prompt_n": 295, + "prompt_ms": 2.7, + "prompt_per_token_ms": 0.009, + "prompt_per_second": 110280.4, + "predicted_n": 11, + "predicted_ms": 1234.5, + "predicted_per_token_ms": 112.232, + "predicted_per_second": 8.9, + "draft_n": 20, + "draft_n_accepted": 15 + } + }, + { + "last": { + "prompt_ms": 2.675, + "decode_ms": 1234.55, + "generated": 11, + "reused": 5, + "drafts_offered": 20, + "drafts_accepted": 15 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 5, + "prompt_n": 5, + "prompt_ms": 2.7, + "prompt_per_token_ms": 0.535, + "prompt_per_second": 1869.2, + "predicted_n": 10, + "predicted_ms": 1234.5, + "predicted_per_token_ms": 112.232, + "predicted_per_second": 8.9, + "draft_n": 20, + "draft_n_accepted": 15 + } + }, + { + "last": { + "prompt_ms": 2.675, + "decode_ms": 1234.55, + "generated": 11, + "reused": 5, + "drafts_offered": 20, + "drafts_accepted": 15 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 5, + "prompt_n": 0, + "prompt_ms": 2.7, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 1234.5, + "predicted_per_token_ms": 112.232, + "predicted_per_second": 8.9, + "draft_n": 20, + "draft_n_accepted": 15 + } + }, + { + "last": { + "prompt_ms": 2.675, + "decode_ms": 1234.55, + "generated": 11, + "reused": 5, + "drafts_offered": 20, + "drafts_accepted": 15 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 5, + "prompt_n": 45, + "prompt_ms": 2.7, + "prompt_per_token_ms": 0.059, + "prompt_per_second": 16822.4, + "predicted_n": 7, + "predicted_ms": 1234.5, + "predicted_per_token_ms": 112.232, + "predicted_per_second": 8.9, + "draft_n": 20, + "draft_n_accepted": 15 + } + }, + { + "last": { + "prompt_ms": 100.0, + "decode_ms": 333.3333, + "generated": 0, + "reused": 200 + }, + "prompt_tokens": 300, + "generated": 5, + "timings": { + "cache_n": 200, + "prompt_n": 100, + "prompt_ms": 100.0, + "prompt_per_token_ms": 1.0, + "prompt_per_second": 1000.0, + "predicted_n": 5, + "predicted_ms": 333.3, + "predicted_per_token_ms": 66.667, + "predicted_per_second": 15.0 + } + }, + { + "last": { + "prompt_ms": 100.0, + "decode_ms": 333.3333, + "generated": 0, + "reused": 200 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 200, + "prompt_n": 0, + "prompt_ms": 100.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 10, + "predicted_ms": 333.3, + "predicted_per_token_ms": 33.333, + "predicted_per_second": 30.0 + } + }, + { + "last": { + "prompt_ms": 100.0, + "decode_ms": 333.3333, + "generated": 0, + "reused": 200 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 200, + "prompt_n": 0, + "prompt_ms": 100.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 333.3, + "predicted_per_token_ms": null, + "predicted_per_second": null + } + }, + { + "last": { + "prompt_ms": 100.0, + "decode_ms": 333.3333, + "generated": 0, + "reused": 200 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 200, + "prompt_n": 0, + "prompt_ms": 100.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 7, + "predicted_ms": 333.3, + "predicted_per_token_ms": 47.619, + "predicted_per_second": 21.0 + } + }, + { + "last": { + "prompt_ms": 1e-09, + "decode_ms": 5e-05, + "generated": 9, + "reused": 0, + "drafts_offered": 0, + "drafts_accepted": 0 + }, + "prompt_tokens": 300, + "generated": 9, + "timings": { + "cache_n": 0, + "prompt_n": 300, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": 300000000000000.0, + "predicted_n": 9, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": 180000000.0, + "draft_n": 0, + "draft_n_accepted": 0 + } + }, + { + "last": { + "prompt_ms": 1e-09, + "decode_ms": 5e-05, + "generated": 9, + "reused": 0, + "drafts_offered": 0, + "drafts_accepted": 0 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 0, + "prompt_n": 10, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": 10000000000000.0, + "predicted_n": 10, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": 180000000.0, + "draft_n": 0, + "draft_n_accepted": 0 + } + }, + { + "last": { + "prompt_ms": 1e-09, + "decode_ms": 5e-05, + "generated": 9, + "reused": 0, + "drafts_offered": 0, + "drafts_accepted": 0 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 0, + "prompt_n": 0, + "prompt_ms": 0.0, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": 180000000.0, + "draft_n": 0, + "draft_n_accepted": 0 + } + }, + { + "last": { + "prompt_ms": 1e-09, + "decode_ms": 5e-05, + "generated": 9, + "reused": 0, + "drafts_offered": 0, + "drafts_accepted": 0 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 0, + "prompt_n": 50, + "prompt_ms": 0.0, + "prompt_per_token_ms": 0.0, + "prompt_per_second": 50000000000000.0, + "predicted_n": 7, + "predicted_ms": 0.0, + "predicted_per_token_ms": 0.0, + "predicted_per_second": 180000000.0, + "draft_n": 0, + "draft_n_accepted": 0 + } + }, + { + "last": { + "prompt_ms": 12345.678, + "decode_ms": 87654.321, + "generated": 4096, + "reused": 1 + }, + "prompt_tokens": 300, + "generated": 4096, + "timings": { + "cache_n": 1, + "prompt_n": 299, + "prompt_ms": 12345.7, + "prompt_per_token_ms": 41.29, + "prompt_per_second": 24.2, + "predicted_n": 4096, + "predicted_ms": 87654.3, + "predicted_per_token_ms": 21.4, + "predicted_per_second": 46.7 + } + }, + { + "last": { + "prompt_ms": 12345.678, + "decode_ms": 87654.321, + "generated": 4096, + "reused": 1 + }, + "prompt_tokens": 10, + "generated": 10, + "timings": { + "cache_n": 1, + "prompt_n": 9, + "prompt_ms": 12345.7, + "prompt_per_token_ms": 1371.742, + "prompt_per_second": 0.7, + "predicted_n": 10, + "predicted_ms": 87654.3, + "predicted_per_token_ms": 21.4, + "predicted_per_second": 46.7 + } + }, + { + "last": { + "prompt_ms": 12345.678, + "decode_ms": 87654.321, + "generated": 4096, + "reused": 1 + }, + "prompt_tokens": 0, + "generated": 0, + "timings": { + "cache_n": 1, + "prompt_n": 0, + "prompt_ms": 12345.7, + "prompt_per_token_ms": null, + "prompt_per_second": null, + "predicted_n": 0, + "predicted_ms": 87654.3, + "predicted_per_token_ms": 21.4, + "predicted_per_second": 46.7 + } + }, + { + "last": { + "prompt_ms": 12345.678, + "decode_ms": 87654.321, + "generated": 4096, + "reused": 1 + }, + "prompt_tokens": 50, + "generated": 7, + "timings": { + "cache_n": 1, + "prompt_n": 49, + "prompt_ms": 12345.7, + "prompt_per_token_ms": 251.953, + "prompt_per_second": 4.0, + "predicted_n": 7, + "predicted_ms": 87654.3, + "predicted_per_token_ms": 21.4, + "predicted_per_second": 46.7 + } + }, + { + "last": {}, + "prompt_tokens": 5, + "generated": 5, + "timings": null + } + ], + "aliases": [ + { + "input": null, + "ok": [] + }, + { + "input": [], + "ok": [] + }, + { + "input": [ + "a" + ], + "ok": [ + "a" + ] + }, + { + "input": [ + " a ", + "a", + "", + "m", + "b" + ], + "ok": [ + "a", + "b" + ] + }, + { + "input": "a, b ,a,,m", + "ok": [ + "a", + "b" + ] + }, + { + "input": [ + "a", + 1 + ], + "error": "aliases=['a', 1]: expected a list of model names" + }, + { + "input": 5, + "error": "aliases=5: expected a list of model names" + }, + { + "input": { + "a": 1 + }, + "error": "aliases={'a': 1}: expected a list of model names" + }, + { + "input": "", + "ok": [] + }, + { + "input": [ + "" + ], + "ok": [] + } + ] +} diff --git a/crates/serving-policy/tests/fixtures/vision.json b/crates/serving-policy/tests/fixtures/vision.json new file mode 100644 index 00000000..32c32a1c --- /dev/null +++ b/crates/serving-policy/tests/fixtures/vision.json @@ -0,0 +1,4222 @@ +{ + "source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)", + "base64": [ + { + "text": "QQ==", + "ok": "41" + }, + { + "text": "QUI=", + "ok": "4142" + }, + { + "text": "QUJD", + "ok": "414243" + }, + { + "text": "QU\nJD", + "ok": "414243" + }, + { + "text": "", + "ok": "" + }, + { + "text": "QQ", + "error": "Error: Incorrect padding" + }, + { + "text": "Q", + "error": "Error: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4" + }, + { + "text": "QUJDRA==", + "ok": "41424344" + }, + { + "text": "QUJDRA=", + "error": "Error: Incorrect padding" + }, + { + "text": "QUJDRA", + "error": "Error: Incorrect padding" + }, + { + "text": "QU JD", + "ok": "414243" + }, + { + "text": "QQ==QQ==", + "ok": "41" + }, + { + "text": "Q=Q=", + "error": "Error: Incorrect padding" + }, + { + "text": "!!!!", + "ok": "" + }, + { + "text": "QUJD\n", + "ok": "414243" + }, + { + "text": "//8=", + "ok": "ffff" + }, + { + "text": "-_8=", + "error": "Error: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4" + }, + { + "text": "QUJD=", + "ok": "414243" + }, + { + "text": "====", + "ok": "" + }, + { + "text": "QUJDREVG", + "ok": "414243444546" + }, + { + "text": "QUJDREVGRw", + "error": "Error: Incorrect padding" + }, + { + "text": "QUJDREVGRw==", + "ok": "41424344454647" + } + ], + "sources": [ + { + "part": { + "type": "image_url", + "image_url": { + "url": "https://x/y.png" + } + }, + "source": "https://x/y.png" + }, + { + "part": { + "type": "image_url", + "image_url": "data:abc" + }, + "source": "data:abc" + }, + { + "part": { + "type": "input_image", + "image_url": "file:///a.png" + }, + "source": "file:///a.png" + }, + { + "part": { + "type": "image_url" + }, + "source": "" + }, + { + "part": { + "type": "image_url", + "image_url": {} + }, + "source": "" + }, + { + "part": { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/jpeg", + "data": "QQ==" + } + }, + "source": "data:image/jpeg;base64,QQ==" + }, + { + "part": { + "type": "image", + "source": { + "type": "base64", + "data": "QQ==" + } + }, + "source": "data:image/png;base64,QQ==" + }, + { + "part": { + "type": "image", + "source": { + "type": "url", + "url": "http://u" + } + }, + "source": "http://u" + }, + { + "part": { + "type": "image", + "source": { + "path": "/p.png" + } + }, + "source": "/p.png" + }, + { + "part": { + "type": "image", + "source": { + "url": "", + "path": "/q.png" + } + }, + "source": "/q.png" + }, + { + "part": { + "type": "image" + }, + "source": "" + }, + { + "part": { + "type": "image", + "source": null + }, + "source": "" + } + ], + "prepare": [ + { + "messages": [ + { + "role": "user", + "content": "hello" + } + ], + "counts": {}, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 104, + 101, + 108, + 108, + 111, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 104, + 101, + 108, + 108, + 111, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": null + }, + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "look" + }, + { + "type": "image_url", + "image_url": { + "url": "A" + } + } + ] + } + ], + "counts": { + "A": 3 + }, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 108, + 111, + 111, + 107, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [ + "A" + ], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 108, + 111, + 111, + 107, + 259, + 260, + 260, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": "41" + }, + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "A" + } + }, + { + "type": "image_url", + "image_url": { + "url": "B" + } + }, + { + "type": "text", + "text": "compare" + } + ] + } + ], + "counts": { + "A": 2, + "B": 5 + }, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 261, + 259, + 260, + 261, + 99, + 111, + 109, + 112, + 97, + 114, + 101, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [ + "A", + "B" + ], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 260, + 261, + 259, + 260, + 260, + 260, + 260, + 260, + 261, + 99, + 111, + 109, + 112, + 97, + 114, + 101, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": "4142" + }, + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "A" + } + } + ] + }, + { + "role": "assistant", + "content": "ok" + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "again" + }, + { + "type": "image_url", + "image_url": { + "url": "C" + } + } + ] + } + ], + "counts": { + "A": 1, + "C": 4 + }, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10, + 10, + 60, + 47, + 116, + 104, + 105, + 110, + 107, + 62, + 10, + 10, + 111, + 107, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 97, + 103, + 97, + 105, + 110, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [ + "A", + "C" + ], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10, + 10, + 60, + 47, + 116, + 104, + 105, + 110, + 107, + 62, + 10, + 10, + 111, + 107, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 97, + 103, + 97, + 105, + 110, + 259, + 260, + 260, + 260, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": "4143" + }, + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "literal <|image_pad|> in text" + }, + { + "type": "image_url", + "image_url": { + "url": "A" + } + } + ] + } + ], + "counts": { + "A": 2 + }, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 108, + 105, + 116, + 101, + 114, + 97, + 108, + 32, + 260, + 32, + 105, + 110, + 32, + 116, + 101, + 120, + 116, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [ + "A" + ], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 108, + 105, + 116, + 101, + 114, + 97, + 108, + 32, + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62, + 32, + 105, + 110, + 32, + 116, + 101, + 120, + 116, + 259, + 260, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": "41" + }, + { + "messages": [ + { + "role": "user", + "content": "just text <|image_pad|> again" + } + ], + "counts": {}, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 106, + 117, + 115, + 116, + 32, + 116, + 101, + 120, + 116, + 32, + 260, + 32, + 97, + 103, + 97, + 105, + 110, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 106, + 117, + 115, + 116, + 32, + 116, + 101, + 120, + 116, + 32, + 260, + 32, + 97, + 103, + 97, + 105, + 110, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": null + }, + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "<|vision_start|><|image_pad|> fake" + }, + { + "type": "image_url", + "image_url": { + "url": "A" + } + } + ] + } + ], + "counts": { + "A": 2 + }, + "ids_before": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 32, + 102, + 97, + 107, + 101, + 259, + 260, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "images": [ + "A" + ], + "pad": 260, + "start": 259, + "literal": [ + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62 + ], + "ids_after": [ + 256, + 115, + 121, + 115, + 116, + 101, + 109, + 10, + 82, + 101, + 97, + 115, + 111, + 110, + 105, + 110, + 103, + 32, + 101, + 102, + 102, + 111, + 114, + 116, + 32, + 105, + 115, + 32, + 115, + 101, + 116, + 32, + 116, + 111, + 32, + 120, + 104, + 105, + 103, + 104, + 46, + 32, + 80, + 108, + 101, + 97, + 115, + 101, + 32, + 116, + 104, + 105, + 110, + 107, + 32, + 99, + 97, + 114, + 101, + 102, + 117, + 108, + 108, + 121, + 32, + 116, + 104, + 114, + 111, + 117, + 103, + 104, + 32, + 116, + 104, + 101, + 32, + 116, + 97, + 115, + 107, + 44, + 32, + 118, + 97, + 108, + 105, + 100, + 97, + 116, + 101, + 32, + 107, + 101, + 121, + 32, + 97, + 115, + 115, + 117, + 109, + 112, + 116, + 105, + 111, + 110, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 100, + 101, + 114, + 32, + 112, + 108, + 97, + 117, + 115, + 105, + 98, + 108, + 101, + 32, + 97, + 108, + 116, + 101, + 114, + 110, + 97, + 116, + 105, + 118, + 101, + 115, + 44, + 32, + 97, + 110, + 100, + 32, + 112, + 114, + 105, + 111, + 114, + 105, + 116, + 105, + 122, + 101, + 32, + 99, + 111, + 114, + 114, + 101, + 99, + 116, + 110, + 101, + 115, + 115, + 44, + 32, + 99, + 111, + 110, + 115, + 105, + 115, + 116, + 101, + 110, + 99, + 121, + 44, + 32, + 97, + 110, + 100, + 32, + 99, + 108, + 97, + 114, + 105, + 116, + 121, + 32, + 105, + 110, + 32, + 116, + 104, + 101, + 32, + 102, + 105, + 110, + 97, + 108, + 32, + 97, + 110, + 115, + 119, + 101, + 114, + 46, + 257, + 10, + 256, + 117, + 115, + 101, + 114, + 10, + 259, + 260, + 260, + 32, + 102, + 97, + 107, + 101, + 259, + 60, + 124, + 105, + 109, + 97, + 103, + 101, + 95, + 112, + 97, + 100, + 124, + 62, + 261, + 257, + 10, + 256, + 97, + 115, + 115, + 105, + 115, + 116, + 97, + 110, + 116, + 10, + 60, + 116, + 104, + 105, + 110, + 107, + 62, + 10 + ], + "combined_hex": "41" + } + ] +} diff --git a/crates/serving-policy/tests/fixtures/vision_oracle.json b/crates/serving-policy/tests/fixtures/vision_oracle.json new file mode 100644 index 00000000..9f95deb5 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/vision_oracle.json @@ -0,0 +1,26 @@ +{ + "source": "src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)", + "cases": [ + {"name": "text identity after an image request", "geni": false, "mrope_identity": false, "n_embd": 4, "cells": 32, "file_hex": "", "ids": [5,6,7], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "text only with no file", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "", "ids": [5,6,7,8], "ve": "cannot open /nonexistent/embeddings.sve", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1], "imgs": []}, + {"name": "one 1x1 image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,2,248056,3,4], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,0,-1,-1], "imgs": [[2,"3ccab5f5c275a7f2"]]}, + {"name": "one 3x2 image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,248056,248056,248056,248056,9,10], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36], "row_offset": [-1,0,4,8,12,16,20,-1,-1], "imgs": [[1,"b98ae886c8b44c94"]]}, + {"name": "one 2x4 image (tall: ny > nx)", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "53564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [7,248056,248056,248056,248056,248056,248056,248056,248056,8], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,2,1,1,2,2,1,3,1,1,3,2,1,4,1,1,4,2,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35], "row_offset": [-1,0,4,8,12,16,20,24,28,-1], "imgs": [[1,"cbe485118dfba78d"]]}, + {"name": "two images in order", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 64, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac4153564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [1,248056,248056,248056,248056,248056,248056,2,248056,248056,248056,248056,248056,248056,248056,248056,3], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,4,4,4,5,5,5,5,5,6,5,6,5,5,6,6,5,7,5,5,7,6,5,8,5,5,8,6,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36,37,37,37,38,38,38,39,39,39,40,40,40,41,41,41,42,42,42,43,43,43,44,44,44,45,45,45,46,46,46,47,47,47,48,48,48,49,49,49,50,50,50,51,51,51,52,52,52,53,53,53,54,54,54,55,55,55,56,56,56], "row_offset": [-1,0,4,8,12,16,20,-1,24,28,32,36,40,44,48,52,-1], "imgs": [[1,"b98ae886c8b44c94"],[8,"cbe485118dfba78d"]]}, + {"name": "5x5 image then text", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 64, "file_hex": "53564531190000000500000005000000040000000000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42000010420000124200001442000016420000184200001a4200001c4200001e42000020420000224200002442000026420000284200002a4200002c4200002e42000030420000324200003442000036420000384200003a4200003c4200003e42000040420000424200004442000046420000484200004a4200004c4200004e42000050420000524200005442000056420000584200005a4200005c4200005e42000060420000624200006442000066420000684200006a4200006c4200006e42000070420000724200007442000076420000784200007a4200007c4200007e420000804200008142000082420000834200008442000085420000864200008742000088420000894200008a4200008b4200008c4200008d4200008e4200008f420000904200009142000092420000934200009442000095420000964200009742000098420000994200009a4200009b4200009c4200009d4200009e4200009f42", "ids": [1,2,3,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,4,5], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,3,3,4,3,3,5,3,3,6,3,3,7,3,4,3,3,4,4,3,4,5,3,4,6,3,4,7,3,5,3,3,5,4,3,5,5,3,5,6,3,5,7,3,6,3,3,6,4,3,6,5,3,6,6,3,6,7,3,7,3,3,7,4,3,7,5,3,7,6,3,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36,37,37,37,38,38,38,39,39,39,40,40,40,41,41,41,42,42,42,43,43,43], "row_offset": [-1,-1,-1,0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,-1,-1], "imgs": [[3,"2c0ab68485332f9a"]]}, + {"name": "adjacent images", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac4153564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,1], "ve": "", "table": [0,0,0,0,0,1,0,0,2,0,1,0,0,1,1,0,1,2,3,3,3,3,3,4,3,4,3,3,4,4,3,5,3,3,5,4,3,6,3,3,6,4,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32], "row_offset": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,-1], "imgs": [[0,"b98ae886c8b44c94"],[6,"cbe485118dfba78d"]]}, + {"name": "image at the start", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 16, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [248056,4], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15], "row_offset": [0,-1], "imgs": [[0,"3ccab5f5c275a7f2"]]}, + {"name": "identity request after (not geni, not identity)", "geni": false, "mrope_identity": false, "n_embd": 4, "cells": 16, "file_hex": "", "ids": [1,2], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15], "row_offset": [-1,-1], "imgs": []}, + {"name": "prompt ends in an image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,248056,248056,248056,248056], "ve": "the prompt cannot end in an image", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,4,8,12,16,20], "imgs": [[1,"b98ae886c8b44c94"]]}, + {"name": "more images in the prompt than the file", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2,248056,3], "ve": "the prompt has more images than the embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,-1,-1,-1], "imgs": [[1,"3ccab5f5c275a7f2"]]}, + {"name": "more images in the file than the prompt", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f000000400000204053564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2,3], "ve": "the embeddings file has more images than the prompt", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,-1,-1], "imgs": [[1,"3ccab5f5c275a7f2"]]}, + {"name": "fewer image_pad tokens than rows", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,2,3,4,5,6,7], "ve": "image 1 has 6 rows but fewer <|image_pad|> tokens", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1,-1,-1,-1,-1,-1], "imgs": [[1,"b98ae886c8b44c94"]]}, + {"name": "bad magic", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "78563412010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "wrong width", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000080000000000803f0000c03f000000400000204000004040000060400000804000009040", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "grid does not multiply", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531060000000300000003000000040000000000803f0000c03f0000004000002040000040400000604000008040000090400000a0400000b0400000c0400000d0400000e0400000f04000000041000008410000104100001841000020410000284100003041000038410000404100004841", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "zero rows", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "5356453100000000000000000000000004000000", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "short header", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310100000001000000", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "short data", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000", "ids": [1,248056,2], "ve": "short embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []}, + {"name": "second record truncated", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f000000400000204053564531010000000100000001000000040000000000803f00", "ids": [1,248056,2,248056,3], "ve": "short embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1,-1], "imgs": []} + ] +} diff --git a/crates/serving-policy/tests/golden_cvec.rs b/crates/serving-policy/tests/golden_cvec.rs new file mode 100644 index 00000000..ec9afcf4 --- /dev/null +++ b/crates/serving-policy/tests/golden_cvec.rs @@ -0,0 +1,89 @@ +//! The control-vector loader against the Original's `load_control_vectors` compiled verbatim on the host +//! (fixture from `oracle/build_oracle.sh`): same tables bit for bit, same error text. + +use leleka_serving_policy::cvec::{Mode, Options, build_tables, parse_gguf}; +use serde_json::Value; + +fn unhex(text: &str) -> Vec { + (0..text.len() / 2) + .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn tables_and_errors_equal_the_engines_loader() { + let fixture: Value = serde_json::from_str(include_str!("fixtures/cvec_oracle.json")).unwrap(); + let layers = fixture["n_layers"].as_u64().unwrap() as usize; + let width = fixture["n_embd"].as_u64().unwrap() as usize; + let blobs: Vec> = fixture["blobs"] + .as_array() + .unwrap() + .iter() + .map(|b| unhex(b.as_str().unwrap())) + .collect(); + let (mut loaded, mut refused) = (0, 0); + for case in fixture["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let mut files = Vec::new(); + for entry in case["files"].as_array().unwrap() { + let blob = entry[0].as_u64().unwrap() as usize; + let scale = f32::from_bits(entry[1].as_u64().unwrap() as u32); + files.push(( + format!("FILE{blob}"), + parse_gguf(&blobs[blob]).unwrap_or_else(|e| panic!("{name}: {e}")), + scale, + )); + } + let options = Options { + first: case["first"].as_i64().unwrap() as i32, + last: case["last"].as_i64().unwrap() as i32, + mode: if case["mode"] == "project" { + Mode::Project + } else { + Mode::Add + }, + single: case["single"].as_i64().unwrap() as i32, + }; + let got = build_tables(&files, layers, width, options); + if case["ok"].as_bool().unwrap() { + let tables = got.unwrap_or_else(|e| panic!("{name}: unexpected error {e}")); + let bits = |values: &[f32]| -> Vec { + values.iter().map(|v| u64::from(v.to_bits())).collect() + }; + let want = |key: &str| -> Vec { + case["up"][key] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap()) + .collect() + }; + assert_eq!(bits(&tables.dir), want("dir_bits"), "{name}: dir"); + assert_eq!(bits(&tables.s), want("s_bits"), "{name}: s"); + assert_eq!( + tables.first as i64, + case["up"]["first"].as_i64().unwrap(), + "{name}" + ); + assert_eq!( + tables.last as i64, + case["up"]["last"].as_i64().unwrap(), + "{name}" + ); + assert_eq!( + tables.mode == Mode::Project, + case["up"]["mode"].as_i64().unwrap() == 0, + "{name}" + ); + assert_eq!(tables.summary, case["summary"].as_str().unwrap(), "{name}"); + loaded += 1; + } else { + assert_eq!(got.unwrap_err(), case["err"].as_str().unwrap(), "{name}"); + refused += 1; + } + } + assert!( + loaded >= 14 && refused >= 8, + "{loaded} loaded, {refused} refused" + ); +} diff --git a/crates/serving-policy/tests/golden_host.rs b/crates/serving-policy/tests/golden_host.rs new file mode 100644 index 00000000..6e4bcc08 --- /dev/null +++ b/crates/serving-policy/tests/golden_host.rs @@ -0,0 +1,73 @@ +//! Stride selection and the stall watchdog against the Original's C++ host build +//! (fixture from `oracle/build_oracle.sh`: `logits_selection.hpp` unmodified, the watchdog loop driven +//! by an injected clock). + +use leleka_serving_policy::stride::{parse_stride, row_count, selected}; +use leleka_serving_policy::watchdog::{Counters, StallWatchdog, Verdict}; +use serde_json::Value; + +fn fixture() -> Value { + serde_json::from_str(include_str!("fixtures/host_oracle.json")).unwrap() +} + +#[test] +fn stride_parsing_equals_the_header() { + for case in fixture()["parse"].as_array().unwrap() { + let text = case["text"].as_str().unwrap(); + let got = parse_stride(text); + if case["ok"].as_bool().unwrap() { + assert_eq!(got, case["value"].as_i64(), "{text:?}"); + } else { + assert_eq!(got, None, "{text:?}"); + } + } +} + +#[test] +fn stride_selection_and_row_counts_equal_the_header() { + let fixture = fixture(); + let cases = fixture["selected"].as_array().unwrap(); + assert_eq!(cases.len(), 100); + for case in cases { + let total = case["total"].as_i64().unwrap(); + let stride = case["stride"].as_i64().unwrap(); + assert_eq!(row_count(total, stride), case["rows"].as_i64().unwrap()); + let want: Vec = case["kept"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(); + let got: Vec = (-2..total + 2) + .filter(|p| selected(*p, total, stride)) + .collect(); + assert_eq!(got, want, "total {total} stride {stride}"); + } +} + +#[test] +fn watchdog_scenarios_equal_the_engine_loop() { + let fixture = fixture(); + let mut fired = 0; + for scenario in fixture["watchdog"].as_array().unwrap() { + let limit = scenario["limit_s"].as_i64().unwrap(); + let mut dog = StallWatchdog::new(limit, 0, Counters::default()); + for step in scenario["steps"].as_array().unwrap() { + let counters = Counters { + beats: step["beats"].as_u64().unwrap(), + busy: step["busy"].as_bool().unwrap(), + ticks: step["ticks"].as_u64().unwrap(), + }; + let verdict = dog.poll(step["at_ms"].as_u64().unwrap(), counters); + let want = step["layers_since"].as_i64().unwrap(); + match verdict { + Verdict::Healthy => assert_eq!(want, -1, "limit {limit} step {step}"), + Verdict::Stalled { layers_since, .. } => { + assert_eq!(layers_since as i64, want, "limit {limit} step {step}"); + fired += 1; + } + } + } + } + assert!(fired >= 6, "{fired}"); +} diff --git a/crates/serving-policy/tests/golden_reasoning.rs b/crates/serving-policy/tests/golden_reasoning.rs new file mode 100644 index 00000000..5a611b0d --- /dev/null +++ b/crates/serving-policy/tests/golden_reasoning.rs @@ -0,0 +1,75 @@ +//! `BudgetTracker` and `parse_budget` against the Original's real `Detokenizer` + `OutputParser` loop and +//! `Service.reasoning_budget` (fixture from `control-plane/tests/golden/gen_goldens.py reasoning`). + +use leleka_serving_policy::reasoning::{BudgetTracker, Verdict, WRAP_UP, parse_budget}; +use serde_json::Value; + +fn fixture() -> Value { + serde_json::from_str(include_str!("fixtures/reasoning.json")).unwrap() +} + +fn unhex(text: &str) -> Vec { + (0..text.len() / 2) + .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn wrap_up_text_is_the_originals() { + assert_eq!(fixture()["wrap_up"].as_str().unwrap(), WRAP_UP); +} + +#[test] +fn wrap_up_points_equal_python_for_every_sequence_and_budget() { + let fixture = fixture(); + let mut wrapped = 0; + let mut unwrapped = 0; + for case in fixture["cases"].as_array().unwrap() { + let pieces: Vec> = case["pieces_hex"] + .as_array() + .unwrap() + .iter() + .map(|v| unhex(v.as_str().unwrap())) + .collect(); + for (budget, want) in case["wrap_at"].as_object().unwrap() { + let mut tracker = BudgetTracker::new(budget.parse().unwrap()); + let mut got = None; + for (index, piece) in pieces.iter().enumerate() { + if tracker.push(piece) == Verdict::WrapUp { + got = Some(index as u64); + break; + } + } + assert_eq!( + got, + want.as_u64(), + "budget {budget} pieces {:?}", + case["pieces_hex"] + ); + if got.is_some() { + wrapped += 1; + } else { + unwrapped += 1; + } + } + } + assert!(wrapped > 100 && unwrapped > 50, "{wrapped} {unwrapped}"); +} + +#[test] +fn budget_parsing_equals_python() { + for case in fixture()["parse"].as_array().unwrap() { + let request = case["request"].get("reasoning_budget_tokens"); + let default = case["default"].clone(); + let got = parse_budget(request, Some(&default)); + match (case.get("ok"), case.get("error")) { + (Some(ok), None) => assert_eq!( + got.unwrap().map(Value::from).unwrap_or(Value::Null), + *ok, + "{case}" + ), + (None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{case}"), + _ => unreachable!(), + } + } +} diff --git a/crates/serving-policy/tests/golden_shared.rs b/crates/serving-policy/tests/golden_shared.rs new file mode 100644 index 00000000..929c7c8c --- /dev/null +++ b/crates/serving-policy/tests/golden_shared.rs @@ -0,0 +1,79 @@ +//! `clean_shared_defaults` / `sampling_defaults_from_config` against the Original's real Python output +//! (fixture from `control-plane/tests/golden/gen_goldens.py shared`). + +use leleka_serving_policy::shared::{clean_shared_defaults, sampling_defaults_from_config}; +use serde_json::{Value, json}; + +fn fixture() -> Value { + serde_json::from_str(include_str!("fixtures/shared.json")).unwrap() +} + +#[test] +fn settings_cleaning_equals_python() { + let fixture = fixture(); + let mut agreed_errors = 0; + for case in fixture["clean"].as_array().unwrap() { + let input = &case["input"]; + let got = clean_shared_defaults(input); + match (case.get("ok"), case.get("error")) { + (Some(ok), None) => { + let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}")); + assert_eq!(&got.to_json(), ok, "{input}"); + } + (None, Some(error)) => { + assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}"); + agreed_errors += 1; + } + _ => unreachable!(), + } + } + assert!(agreed_errors >= 20); +} + +#[test] +fn config_sampling_block_equals_python() { + let fixture = fixture(); + let mut agreed_errors = 0; + for case in fixture["config"].as_array().unwrap() { + let input = case["input"].clone(); + let got = sampling_defaults_from_config(&input); + match (case.get("ok"), case.get("error")) { + (Some(ok), None) => { + let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}")); + // Python returns the dict of accepted keys: compare through the same names. + let s = &got.sampling; + let mut mine = serde_json::Map::new(); + let mut put = |k: &str, v: Option| { + if let Some(v) = v { + mine.insert(k.into(), v); + } + }; + put("temperature", s.temperature.map(|v| json!(v))); + put("top_p", s.top_p.map(|v| json!(v))); + put("min_p", s.min_p.map(|v| json!(v))); + put("top_k", s.top_k.map(|v| json!(v))); + put("presence_penalty", s.presence_penalty.map(|v| json!(v))); + put("frequency_penalty", s.frequency_penalty.map(|v| json!(v))); + put("repetition_penalty", s.repetition_penalty.map(|v| json!(v))); + put("penalty_last_n", s.penalty_last_n.map(|v| json!(v))); + put("seed", s.seed.map(|v| json!(v))); + put( + "experimental_speed_projection", + got.experimental_speed_projection.map(|v| json!(v)), + ); + assert_eq!(&Value::Object(mine), ok, "{input}"); + assert_eq!( + got.ignored.len(), + case["ignored"].as_array().unwrap().len(), + "{input}" + ); + } + (None, Some(error)) => { + assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}"); + agreed_errors += 1; + } + _ => unreachable!(), + } + } + assert!(agreed_errors >= 14); +} diff --git a/crates/serving-policy/tests/golden_timings.rs b/crates/serving-policy/tests/golden_timings.rs new file mode 100644 index 00000000..34abcef1 --- /dev/null +++ b/crates/serving-policy/tests/golden_timings.rs @@ -0,0 +1,50 @@ +//! `request_timings` and `Service.set_aliases` against the Original's real Python +//! (fixture from `control-plane/tests/golden/gen_goldens.py timings`). + +use leleka_serving_policy::shared::normalize_aliases; +use leleka_serving_policy::timings::{Last, request_timings}; +use serde_json::Value; + +fn fixture() -> Value { + serde_json::from_str(include_str!("fixtures/timings.json")).unwrap() +} + +#[test] +fn timings_equal_python() { + let fixture = fixture(); + let cases = fixture["timings"].as_array().unwrap(); + assert!(cases.len() > 30); + for case in cases { + let last = &case["last"]; + let prompt_tokens = case["prompt_tokens"].as_u64().unwrap(); + let generated = case["generated"].as_u64().unwrap(); + if last.as_object().is_some_and(|o| o.is_empty()) { + continue; // MockEngine keeps no clock: Python answers None and the caller shows null + } + let got = request_timings( + &Last { + prompt_tokens, + generated: last["generated"].as_u64().unwrap_or(0), + prompt_ms: last["prompt_ms"].as_f64().unwrap(), + decode_ms: last["decode_ms"].as_f64().unwrap_or(0.0), + reused: last["reused"].as_u64(), + drafts_offered: last["drafts_offered"].as_u64(), + drafts_accepted: last["drafts_accepted"].as_u64(), + }, + generated, + ); + assert_eq!(got, case["timings"], "{case}"); + } +} + +#[test] +fn aliases_equal_python() { + for case in fixture()["aliases"].as_array().unwrap() { + let got = normalize_aliases(&case["input"], "m"); + match (case.get("ok"), case.get("error")) { + (Some(ok), None) => assert_eq!(serde_json::json!(got.unwrap()), *ok, "{case}"), + (None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{case}"), + _ => unreachable!(), + } + } +} diff --git a/crates/serving-policy/tests/golden_vision.rs b/crates/serving-policy/tests/golden_vision.rs new file mode 100644 index 00000000..9c73dd72 --- /dev/null +++ b/crates/serving-policy/tests/golden_vision.rs @@ -0,0 +1,169 @@ +//! The image path against the Original: the SVE1 reader and M-RoPE table against the verbatim C++ block +//! (`oracle/build_oracle.sh`), image sources, base64 and the pad expansion against the real Python +//! (`control-plane/tests/golden/gen_goldens.py vision`). + +use leleka_serving_policy::vision::{ + IMAGE_PAD_ID, ImageKey, b64decode, build_positions, expand_image_pads, identity_table, + image_source, parse_embeddings, +}; +use serde_json::Value; + +fn unhex(text: &str) -> Vec { + (0..text.len() / 2) + .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn embeddings_and_positions_equal_the_engine_block() { + let fixture: Value = serde_json::from_str(include_str!("fixtures/vision_oracle.json")).unwrap(); + let cases = fixture["cases"].as_array().unwrap(); + assert!(cases.len() >= 20); + let (mut errors, mut ok) = (0, 0); + for case in cases { + let name = case["name"].as_str().unwrap(); + let n_embd = case["n_embd"].as_i64().unwrap(); + let cells = case["cells"].as_u64().unwrap() as usize; + let geni = case["geni"].as_bool().unwrap(); + let identity = case["mrope_identity"].as_bool().unwrap(); + let ids: Vec = case["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(); + let file = unhex(case["file_hex"].as_str().unwrap()); + let want_error = case["ve"].as_str().unwrap(); + let want_table: Vec<[i32; 3]> = case["table"] + .as_array() + .unwrap() + .chunks(3) + .map(|c| [0, 1, 2].map(|i| c[i].as_i64().unwrap() as i32)) + .collect(); + + // A text request (or a leftover identity) runs the block only to reset the table. + if !geni { + assert_eq!(want_table, identity_table(cells), "{name}"); + assert_eq!(want_error, "", "{name}"); + let _ = identity; + ok += 1; + continue; + } + let result = if file.is_empty() { + // The engine could not open the file at all. + Err("cannot open /nonexistent/embeddings.sve".to_owned()) + } else { + parse_embeddings(&file, n_embd).and_then(|embeddings| { + build_positions(&ids, cells, &embeddings, n_embd, IMAGE_PAD_ID) + .map(|positions| (embeddings, positions)) + }) + }; + match result { + Err(message) => { + assert_eq!(message, want_error, "{name}"); + errors += 1; + } + Ok((_, positions)) => { + assert_eq!(want_error, "", "{name}"); + assert_eq!(positions.table, want_table, "{name}"); + let want_rows: Vec> = case["row_offset"] + .as_array() + .unwrap() + .iter() + .map(|v| usize::try_from(v.as_i64().unwrap()).ok()) + .collect(); + assert_eq!(positions.row_offset, want_rows, "{name}"); + let want_keys: Vec = case["imgs"] + .as_array() + .unwrap() + .iter() + .map(|v| ImageKey { + start: v[0].as_i64().unwrap(), + hash: u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap(), + }) + .collect(); + assert_eq!(positions.images, want_keys, "{name}"); + ok += 1; + } + } + } + assert!(ok >= 9 && errors >= 10, "ok {ok}, errors {errors}"); +} + +fn python() -> Value { + serde_json::from_str(include_str!("fixtures/vision.json")).unwrap() +} + +#[test] +fn base64_equals_pythons_decoder() { + for case in python()["base64"].as_array().unwrap() { + let text = case["text"].as_str().unwrap(); + match (case.get("ok"), case.get("error")) { + (Some(ok), None) => assert_eq!( + b64decode(text).unwrap_or_else(|e| panic!("{text:?}: {e}")), + unhex(ok.as_str().unwrap()), + "{text:?}" + ), + (None, Some(error)) => { + let want = error.as_str().unwrap().trim_start_matches("Error: "); + assert_eq!(b64decode(text).unwrap_err(), want, "{text:?}"); + } + _ => unreachable!(), + } + } +} + +#[test] +fn image_sources_equal_the_frontend() { + for case in python()["sources"].as_array().unwrap() { + assert_eq!( + image_source(&case["part"]), + case["source"].as_str().unwrap(), + "{}", + case["part"] + ); + } +} + +#[test] +fn pad_expansion_equals_service_prepare() { + let fixture = python(); + let mut expanded = 0; + for case in fixture["prepare"].as_array().unwrap() { + let to_u32 = |v: &Value| -> Vec { + v.as_array() + .unwrap() + .iter() + .map(|x| x.as_u64().unwrap() as u32) + .collect() + }; + let ids = to_u32(&case["ids_before"]); + if case["images"].as_array().unwrap().is_empty() { + // No images: `prepare` leaves the prompt alone (a literal marker stays a special token). + assert_eq!(to_u32(&case["ids_after"]), ids); + continue; + } + let counts: Vec = case["images"] + .as_array() + .unwrap() + .iter() + .map(|source| case["counts"][source.as_str().unwrap()].as_u64().unwrap() as usize) + .collect(); + let got = expand_image_pads( + &ids, + case["pad"].as_u64().unwrap() as u32, + case["start"].as_u64().unwrap() as u32, + &to_u32(&case["literal"]), + &counts, + ); + match (case.get("ids_after"), case.get("error")) { + (Some(after), _) => { + assert_eq!(got.unwrap(), to_u32(after), "{}", case["messages"]); + expanded += 1; + } + (None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap()), + _ => unreachable!(), + } + } + assert!(expanded >= 5); +} diff --git a/desktop-core/Cargo.toml b/desktop-core/Cargo.toml index ef31825b..08f93c36 100644 --- a/desktop-core/Cargo.toml +++ b/desktop-core/Cargo.toml @@ -11,6 +11,8 @@ path = "src/main.rs" [dependencies] leleka-backend-api = { path = "../crates/backend-api" } leleka-runtime = { path = "../crates/leleka-runtime" } +leleka-sampler-ref = { path = "../crates/sampler-ref" } +leleka-serving-policy = { path = "../crates/serving-policy" } serde = { version = "1", features = ["derive"] } serde_json = "1" sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } diff --git a/desktop-core/proto/runtime.proto b/desktop-core/proto/runtime.proto index 9dfe58cc..71bd1209 100644 --- a/desktop-core/proto/runtime.proto +++ b/desktop-core/proto/runtime.proto @@ -67,6 +67,17 @@ message OperationResult { message GenerateRequest { string request_id = 1; string expected_epoch = 2; string handle = 3; string prompt = 4; uint32 max_output_tokens = 5; uint32 temperature_milli = 6; + // Remaining Original sampling controls (fixed point; an absent field keeps the Original's default). + // top_p/min_p/repetition_penalty are millionths, frequency/presence penalties signed millionths; + // top_k 0 or above 64 selects the widest list; seed absent or 0 draws a fresh seed per request. + optional uint32 top_p_micro = 7; + optional uint32 top_k = 8; + optional uint32 min_p_micro = 9; + optional uint32 repetition_penalty_micro = 10; + optional sint32 frequency_penalty_micro = 11; + optional sint32 presence_penalty_micro = 12; + optional uint32 penalty_last_n = 13; + optional uint64 seed = 14; } message CancelRequest { string request_id = 1; string expected_epoch = 2; } message CancelAck { string request_id = 1; string epoch = 2; bool acknowledged = 3; } diff --git a/desktop-core/src/lib.rs b/desktop-core/src/lib.rs index 5fbc3ca1..ab6c5a30 100644 --- a/desktop-core/src/lib.rs +++ b/desktop-core/src/lib.rs @@ -11,6 +11,7 @@ pub mod remote; pub mod runtime_client; pub mod runtime_gateway; pub mod runtime_rpc; +mod runtime_sampling; pub mod runtime_tool_response; pub mod runtime_tools; // Reuse the verified pure Rust template; no control-plane crate/C bridge link. diff --git a/desktop-core/src/runtime_client.rs b/desktop-core/src/runtime_client.rs index 102587e9..bf122477 100644 --- a/desktop-core/src/runtime_client.rs +++ b/desktop-core/src/runtime_client.rs @@ -522,6 +522,7 @@ mod tests { prompt: String::new(), max_output_tokens: 1, temperature_milli: 0, + ..Default::default() }) .await .unwrap(); diff --git a/desktop-core/src/runtime_gateway.rs b/desktop-core/src/runtime_gateway.rs index da9823e1..3dd11610 100644 --- a/desktop-core/src/runtime_gateway.rs +++ b/desktop-core/src/runtime_gateway.rs @@ -13,6 +13,7 @@ use axum::{ response::{IntoResponse, Response}, routing::{get, post}, }; +use leleka_sampler_ref::params::FixedPoint; use serde::Deserialize; use serde_json::{Value, json}; use std::{collections::HashSet, net::SocketAddr, sync::Arc, time::Duration}; @@ -418,12 +419,12 @@ async fn status(State(r): State, h: HeaderMap) -> Response { } Json(json!({"schema_version":1,"runtimes":states})).into_response() } -fn render(v: &Value) -> Result<(String, u32), &'static str> { +fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> { let o = v.as_object().ok_or("invalid_json")?; for (key, value) in o { match key.as_str() { "model" | "input" | "instructions" | "stream" | "max_output_tokens" => {} - "temperature" if value.as_f64() == Some(0.0) => {} + key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {} "store" if value == &Value::Bool(false) => {} "tools" if value.as_array().is_some_and(Vec::is_empty) => {} "text" if value == &json!({"format":{"type":"text"}}) => {} @@ -433,6 +434,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> { if o.get("stream").is_some_and(|v| !v.is_boolean()) { return Err("invalid_stream"); } + let sampling = crate::runtime_sampling::from_json(o)?; let cap = o .get("max_output_tokens") .map(|v| v.as_u64().ok_or("invalid_output_limit")) @@ -507,7 +509,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> { if prompt.len() > 1024 * 1024 { return Err("prompt_limit"); } - Ok((prompt, cap as u32)) + Ok((prompt, cap as u32, sampling)) } fn response_value(id: &str, model: &str, text: &str, status: &str, usage: &proto::Usage) -> Value { json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}}) @@ -638,7 +640,7 @@ async fn responses(State(r): State, h: HeaderMap, body: Bytes) -> Resp if r.0.experimental_native_tools && needs_tool_adapter(&v) { return tool_responses(r, index, v).await; } - let (prompt, cap) = match render(&v) { + let (prompt, cap, sampling) = match render(&v) { Ok(v) => v, Err(e) => return error(StatusCode::BAD_REQUEST, e), }; @@ -649,19 +651,16 @@ async fn responses(State(r): State, h: HeaderMap, body: Bytes) -> Resp return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); }; let request_id = uuid::Uuid::new_v4().to_string(); - let stream = match accepted( - &mut client, - proto::GenerateRequest { - request_id: request_id.clone(), - expected_epoch: snapshot.epoch, - handle: loaded.handle, - prompt, - max_output_tokens: cap, - temperature_milli: 0, - }, - ) - .await - { + let mut generate = proto::GenerateRequest { + request_id: request_id.clone(), + expected_epoch: snapshot.epoch, + handle: loaded.handle, + prompt, + max_output_tokens: cap, + ..Default::default() + }; + crate::runtime_sampling::apply(&mut generate, &sampling); + let stream = match accepted(&mut client, generate).await { Ok(s) => s, Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), }; @@ -869,14 +868,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); }; let request_id = uuid::Uuid::new_v4().to_string(); - let request = proto::GenerateRequest { + let mut request = proto::GenerateRequest { request_id: request_id.clone(), expected_epoch: snapshot.epoch, handle: loaded.handle, prompt: plan.prompt.clone(), max_output_tokens: plan.max_output_tokens, - temperature_milli: 0, + ..Default::default() }; + crate::runtime_sampling::apply(&mut request, &plan.sampling); let stream = match accepted(&mut client, request.clone()).await { Ok(stream) => stream, Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), @@ -943,9 +943,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo mod tests { use super::*; #[test] - fn runtime_gateway_refuses_silent_sampling_tools_and_state() { + fn runtime_gateway_refuses_tools_state_and_out_of_contract_sampling() { for extra in [ - json!({"temperature":0.5}), + json!({"temperature":2.5}), + json!({"temperature":0.1234}), + json!({"top_p":1.5}), + json!({"top_k":1.5}), + json!({"seed":-1}), + json!({"repetition_penalty":0}), + json!({"stop":["x"]}), json!({"tools":[{"type":"function","name":"run"}]}), json!({"previous_response_id":"resp_x"}), json!({"store":true}), @@ -958,12 +964,38 @@ mod tests { .extend(extra.as_object().unwrap().clone()); assert!(render(&value).is_err()); } - let (prompt, limit) = + let (prompt, limit, greedy) = render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false})) .unwrap(); assert_eq!(limit, 2); + assert_eq!(greedy, FixedPoint::default()); assert!(prompt.ends_with("<|im_start|>assistant\n\n\n\n\n")); } + #[test] + fn runtime_gateway_forwards_the_full_sampling_contract_to_the_runtime_request() { + let (_, _, fixed) = render(&json!({ + "model":"native","input":"hello","temperature":0.7,"top_p":0.9,"top_k":40,"min_p":0.05, + "repetition_penalty":1.1,"frequency_penalty":0.25,"presence_penalty":-0.5, + "penalty_last_n":128,"seed":42 + })) + .unwrap(); + let mut request = proto::GenerateRequest::default(); + crate::runtime_sampling::apply(&mut request, &fixed); + assert_eq!(request.temperature_milli, 700); + assert_eq!(request.top_p_micro, Some(900_000)); + assert_eq!(request.top_k, Some(40)); + assert_eq!(request.min_p_micro, Some(50_000)); + assert_eq!(request.repetition_penalty_micro, Some(1_100_000)); + assert_eq!(request.frequency_penalty_micro, Some(250_000)); + assert_eq!(request.presence_penalty_micro, Some(-500_000)); + assert_eq!(request.penalty_last_n, Some(128)); + assert_eq!(request.seed, Some(42)); + let backend = crate::runtime_sampling::to_backend(&request).unwrap(); + assert_eq!(backend.top_p_micro, Some(900_000)); + assert_eq!(backend.seed, Some(42)); + request.top_p_micro = Some(1_000_001); + assert!(crate::runtime_sampling::to_backend(&request).is_err()); + } fn trace() -> Trace { Trace { id: "resp_test".into(), diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 8868a534..b01712be 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -545,15 +545,20 @@ impl proto::runtime_server::Runtime for RuntimeServer { if command.prompt.len() > 1024 * 1024 || command.max_output_tokens == 0 || command.max_output_tokens > 4096 - // Sampling is validated and served by the backend (Original sampler chain); - // only the documented range is enforced at this boundary. - || command.temperature_milli > 2000 { return Err(refusal( tonic::Code::InvalidArgument, "unsupported_generation_request", )); } + // Sampling is served by the backend (Original sampler chain); the Original's documented + // ranges are enforced here too, so an out-of-contract request never reaches a worker. + let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| { + refusal( + tonic::Code::InvalidArgument, + "unsupported_generation_request", + ) + })?; let loaded = { let mut state = lock(&self.inner.state)?; fence(&state, &command.expected_epoch)?; @@ -594,7 +599,7 @@ impl proto::runtime_server::Runtime for RuntimeServer { prompt: command.prompt, max_output_tokens: command.max_output_tokens, temperature_milli: command.temperature_milli, - sampling: Default::default(), + sampling, }; let mut acceptance_guard = AcceptanceGuard { inner: self.inner.clone(), @@ -1308,6 +1313,7 @@ mod tests { prompt: prompt.into(), max_output_tokens: 2, temperature_milli: 0, + ..Default::default() } } #[tokio::test(flavor = "current_thread")] diff --git a/desktop-core/src/runtime_sampling.rs b/desktop-core/src/runtime_sampling.rs new file mode 100644 index 00000000..5fba8bea --- /dev/null +++ b/desktop-core/src/runtime_sampling.rs @@ -0,0 +1,60 @@ +//! Sampling controls on the runtime gRPC contract: JSON request fields <-> fixed point <-> +//! `runtime.proto` `GenerateRequest` <-> `backend-api` `SamplingOptions`. The arithmetic and the +//! Original's ranges live in `leleka-serving-policy` (tested on every host); this file is the thin +//! field-by-field mapping. + +use leleka_backend_api::SamplingOptions; +use leleka_sampler_ref::params::FixedPoint; +use leleka_serving_policy::fixed::{error_code, sampling_from_object, to_fixed_point}; +use serde_json::{Map, Value}; + +use crate::runtime_rpc::proto; + +/// Read and validate the sampling fields of a Responses request object. +pub(crate) fn from_json(object: &Map) -> Result { + let sampling = sampling_from_object(object).map_err(|e| error_code(&e))?; + to_fixed_point(&sampling).map_err(|e| error_code(&e)) +} + +/// Put the sampling controls on a runtime request. +pub(crate) fn apply(request: &mut proto::GenerateRequest, fixed: &FixedPoint) { + request.temperature_milli = fixed.temperature_milli; + request.top_p_micro = fixed.top_p_micro; + request.top_k = fixed.top_k; + request.min_p_micro = fixed.min_p_micro; + request.repetition_penalty_micro = fixed.repetition_penalty_micro; + request.frequency_penalty_micro = fixed.frequency_penalty_micro; + request.presence_penalty_micro = fixed.presence_penalty_micro; + request.penalty_last_n = fixed.penalty_last_n; + request.seed = fixed.seed; +} + +/// Validate a received request's controls at the RPC boundary (the backend validates again) and +/// convert them for the backend. +pub(crate) fn to_backend(command: &proto::GenerateRequest) -> Result { + let fixed = FixedPoint { + temperature_milli: command.temperature_milli, + top_p_micro: command.top_p_micro, + top_k: command.top_k, + min_p_micro: command.min_p_micro, + repetition_penalty_micro: command.repetition_penalty_micro, + frequency_penalty_micro: command.frequency_penalty_micro, + presence_penalty_micro: command.presence_penalty_micro, + penalty_last_n: command.penalty_last_n, + seed: command.seed, + }; + // The same contract as the HTTP boundary: the ranges of `RequestSampling::validate`. + leleka_sampler_ref::RequestSampling::from_fixed_point(&fixed) + .validate() + .map_err(|_| ())?; + Ok(SamplingOptions { + top_p_micro: fixed.top_p_micro, + top_k: fixed.top_k, + min_p_micro: fixed.min_p_micro, + repetition_penalty_micro: fixed.repetition_penalty_micro, + frequency_penalty_micro: fixed.frequency_penalty_micro, + presence_penalty_micro: fixed.presence_penalty_micro, + penalty_last_n: fixed.penalty_last_n, + seed: fixed.seed, + }) +} diff --git a/desktop-core/src/runtime_tools.rs b/desktop-core/src/runtime_tools.rs index f9b1c3a7..0a46168c 100644 --- a/desktop-core/src/runtime_tools.rs +++ b/desktop-core/src/runtime_tools.rs @@ -18,6 +18,7 @@ pub struct ToolPlan { pub prompt: String, pub max_output_tokens: u32, pub policy: ToolPolicy, + pub sampling: leleka_sampler_ref::params::FixedPoint, } pub enum ValidatedSegment { @@ -400,6 +401,14 @@ pub fn prepare(request: &Value) -> Result { "stream", "max_output_tokens", "temperature", + "top_p", + "top_k", + "min_p", + "repetition_penalty", + "frequency_penalty", + "presence_penalty", + "penalty_last_n", + "seed", "store", "tools", "tool_choice", @@ -414,14 +423,12 @@ pub fn prepare(request: &Value) -> Result { return Err("invalid_stream"); } if object - .get("temperature") - .is_some_and(|v| v.as_f64() != Some(0.0)) - || object - .get("store") - .is_some_and(|v| v != &Value::Bool(false)) + .get("store") + .is_some_and(|v| v != &Value::Bool(false)) { return Err("unsupported_sampling_or_store"); } + let sampling = crate::runtime_sampling::from_json(object)?; if object .get("text") .is_some_and(|v| v != &json!({"format":{"type":"text"}})) @@ -493,6 +500,7 @@ pub fn prepare(request: &Value) -> Result { prompt, max_output_tokens: cap as u32, policy, + sampling, }) } diff --git a/docs/api-contract.md b/docs/api-contract.md index 0954d604..cde97280 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -29,7 +29,9 @@ Supported inputs: - assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and tool `tool_call_id`/text; complete returned assistant messages can be reused; - function tools, `auto`/`none`/`required` or a forced function name, - `parallel_tool_calls`, temperature and top_p; + `parallel_tool_calls`, temperature and top_p, and the sampling controls listed under + "Sampling controls" below (`frequency_penalty`, `presence_penalty`, `seed`, `top_k`, `min_p`, + `repetition_penalty`, `penalty_last_n`); - `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`; - `response_format` text, json_object, or json_schema containing name/schema/strict under `json_schema`; the same native schema subset and final validation apply. @@ -40,7 +42,7 @@ Supported inputs: This first subset always uses `reasoning_effort: none` (also the default here) and `store: false`; no hidden reasoning is requested or returned. Other efforts, storage, multiple choices, multimodal input/output, custom/namespace tools, -custom stop sequences, log probabilities, nonzero presence/frequency penalties, +custom stop sequences, log probabilities, schema descriptions, non-null refusal text and unknown fields are rejected before worker generation. It does not implement the full upstream API or stored Chat retrieval. Omitted optional values use existing Responses defaults, including its @@ -74,7 +76,7 @@ Claude model or an Anthropic cloud service. Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks, user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice` (`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`, -temperature (0..1) and top_p. Text parts join with newlines; consecutive turns of +temperature (0..1), top_p and top_k (plus the extension controls under "Sampling controls"). Text parts join with newlines; consecutive turns of the same role combine. This initial subset requires first and last user messages; assistant prefill is rejected. Assistant `tool_use` carries an object `input` and ID; user `tool_result` returns the same `tool_use_id` and text or text blocks. @@ -90,7 +92,7 @@ Tool names, arguments, results and choice policies reuse native validation. Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless. Thinking/redacted signatures, images/documents, cache_control, nonempty -stop_sequences, server tools, top_k, metadata, structured-output options, +stop_sequences, server tools, metadata, structured-output options, beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent. `POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens) @@ -138,6 +140,80 @@ Unicode, system/combined turns, tools/continuation, usage, headers/errors, admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth regressions run alongside it; real-model/harness/GPU qualification remains open. +## Sampling controls + +Every route that generates (Responses, Chat Completions, Messages) takes the Original server's +sampling fields at the top level of the request body, with the Original's defaults (an absent field +keeps the engine's greedy default) and ranges, and fails closed on a value outside them +(`crates/sampler-ref` `RequestSampling`, `docs/sampler-reference.md`): + +| Field | Range | Notes | +| --- | --- | --- | +| `temperature` | 0..2 | `0` is greedy (Messages: 0..1) | +| `top_p` | 0..1 | `1` disables nucleus filtering | +| `top_k` | integer >= 0 | the sampler keeps at most 64: `0` and values above 64 use 64 | +| `min_p` | 0..1 | | +| `repetition_penalty` | > 0 | `1` is off | +| `frequency_penalty`, `presence_penalty` | -2..2 | | +| `penalty_last_n` | 0..2147483647 | a penalty without a window uses the last 64 tokens; the kernel caps the history at 4096 | +| `seed` | unsigned integer | `0` or absent draws a fresh clock seed per request | +| `strata_tune` | `{pcie_frac, spec_min_p}` in 0..1 | engine settings for this request only | +| `experimental_speed_projection` | boolean | switches a loaded control vector for this request (`cvec=0|1`) | +| `reasoning_budget_tokens` | whole number, `0` = none | see "Reasoning budget" | + +The worker `GEN` line is built by the same code the Python server's `StrataEngine.sampling_keys` +is checked against (`control-plane/tests/fixtures/golden/gen_lines.json`, produced by running that +code). The Chat route no longer refuses nonzero presence/frequency penalties. + +Server-wide defaults fill what a request leaves out: the config `sampling` block, then the Chat +settings shared through `POST /settings`; the request always wins and an explicit `temperature: 0` +stays greedy. A shared `max_tokens` and `reasoning_effort` apply to Responses requests that carry none +(Chat and Messages fix their own effort). + +### Reasoning budget + +With thinking on, a request's `reasoning_budget_tokens` (else the config's) caps how long the model +may think. At the budget, on a clean token boundary (no `` prefix held back, no UTF-8 +character split), the worker stops the pass, appends the Original's wrap-up text +(`"I have thought about this long enough; time to give my answer.\n\n\n"`) to the output +and continues from `prompt + generated + wrap-up`, so the engine keeps its cached prefix. If the +wrap-up leaves no room to answer the request ends as `length`. The client sees one token stream and +one `DONE`: `generated` counts delivered tokens, `prompt_tokens`/`reused` are the first pass's, +timings are summed. + +## Operational surface + +Ported from `engine/strata/serve/server.py` and replayed against the real Python handlers in +`control-plane/tests/http_surface.rs`: + +- `GET /props` (llama-server compatible: default generation settings from the config and shared + settings, chat template, `models_autoload`, `is_sleeping`), `GET /slots`, `GET /v1/status`, + `GET /api/health` (the Python `/health` body; `/health` keeps the minimal liveness body); +- `GET|POST /settings` (shared Chat settings, persisted next to the config; JSON from the server's + own page or a `trusted_origins` origin only); +- `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload` (own page, JSON object, `409 + model_busy` while a request runs or waits), lazy start (`engine.lazy_load`), idle unload + (`engine.idle_unload_s`), reload gates (`engine.before_load`, `engine.min_free_vram_mib`); the next + request after an unload loads the engine again; +- CORS for `/v1/*` (`cors_origins`, `"*"` allowed) with the preflight answered before + authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`; +- engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request + ends the engine, fails the request with a clear error and uses the restart budget. +- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in + `control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file` + and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are + validated at start; stdio and Streamable HTTP servers start in the background, tools are listed + (all pages) and namespaced `__`, a server that stopped is started again by its next + call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call + sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools + (`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop + (`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return + tool calls to the client, so no endpoint executes MCP tools on a client's behalf. + +Differences from the Python server: authentication is Bearer on every path except `/health` and +`/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and +error bodies of the Rust authentication layer are its own. + ## Model discovery `GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or diff --git a/docs/sampler-reference.md b/docs/sampler-reference.md index caaa72e3..9bde931b 100644 --- a/docs/sampler-reference.md +++ b/docs/sampler-reference.md @@ -50,9 +50,10 @@ Requests without a seed take a clock seed (the Original's `seed = 0`). have never run. The serving path therefore samples on the host from the Q6 head's full logits. Switching it to the GPU sampler is a later step once the asset is pinned; the token contract is the same. * Sampling with MTP is refused (`sampling is unavailable with MTP`): coupled draft sampling is not wired into the actor. -* The desktop gRPC protocol still carries only `temperature_milli`; top_p/top_k/min_p/penalties/seed need a proto bump. - The control plane's C++ worker wire (`wire.rs`) still forwards only temperature and top_p; `RequestSampling::gen_keys` - is the tested replacement. +* ~~The desktop gRPC protocol still carries only `temperature_milli`~~ -- done: `runtime.proto` `GenerateRequest` carries + top_p/top_k/min_p/penalties/penalty_last_n/seed (fixed point), `desktop-core` validates and forwards them, the + gateway no longer refuses `temperature != 0`; the control plane's `wire.rs` builds `GEN`/`GENI` lines with + `RequestSampling::gen_keys` (golden-tested against the Python server). See `docs/api-contract.md`. * Float caveat: `exp`/`ln` use the platform libm. Device `exp` (f64) and `logf` can differ by 1 ulp from the host and nvcc `--fmad=true` may contract `count*freq + flag*present`; these can change a pick only on cumulative-boundary or threshold ties. Compare GPU output with the fixtures and report disagreements; do not treat them as noise.