STRA-338 S7: split worker, vision, prometheus, service_install and config by responsibility; name the modules after what they hold

* worker.rs (1271 lines, 1120 of them tests) is 149 lines; the supervisor tests are worker/tests.rs (shared fixtures) and
  worker/tests/{deadlines,handshake,generation,restart,lifecycle,reasoning}.rs. The test names are unchanged; their path
  gains the topic module (worker::tests::restart::..., see scripts/dev/test-outcomes.py compare: 23 MOVED, outcomes equal).
* vision.rs 402 -> 120 lines (tests are vision/tests.rs, same test ids); prometheus.rs 441 -> 50 (the series table is
  prometheus/series.rs); service_install.rs 436 -> 30 (the unix half is service_install/unix.rs and unix/tests.rs, same ids).
* config: Config::load_with_path (430 lines in one function) hands its limits, engine-worker and MCP sections to
  config/methods/load_sections.rs; the same checks run in the same order with the same messages.
* mcp, request_log, vision, worker, config: impl_*/note_*/check_* file names are now hub.rs, server.rs, stdio_transport.rs,
  http_transport.rs, parse_config.rs, obs_handle.rs, engine_counters.rs, encoder.rs, cleanup.rs, generation_result.rs, ...
  Public paths are unchanged (the modules re-export with glob as before).

Architecture gate: five oversize entries leave the baseline (worker.rs, vision.rs, prometheus.rs, service_install.rs,
config impl_config_2_2.rs); no number rose.
This commit is contained in:
Pavlo Ratushnyi
2026-11-05 20:33:04 +01:00
parent 3530208024
commit 5dc28316ab
40 changed files with 2552 additions and 2441 deletions
+1 -6
View File
@@ -6,15 +6,10 @@
],
"oversize": {
"control-plane/examples/cp_replay.rs": 953,
"control-plane/src/config/impl_config/impl_config_2_2.rs": 434,
"control-plane/src/ggml_bridge/tests.rs": 1286,
"control-plane/src/gguf_f32_stream/tests.rs": 909,
"control-plane/src/prepare_preview/tests.rs": 808,
"control-plane/src/prometheus.rs": 441,
"control-plane/src/responses/tests.rs": 2972,
"control-plane/src/service_install.rs": 436,
"control-plane/src/vision.rs": 402,
"control-plane/src/worker.rs": 1271,
"control-plane/tests/backend_worker_http.rs": 1846,
"control-plane/tests/mcp_hub.rs": 447,
"control-plane/tests/memory_gate_http.rs": 471,
@@ -183,7 +178,7 @@
"instant-now:leleka-native-cpu-expert": 30,
"instant-now:leleka-npu-service": 5,
"instant-now:leleka-runtime": 79,
"instant-now:strata-control": 37,
"instant-now:strata-control": 34,
"instant-now:strata-desktop-core": 15,
"path-include:leleka-cuda-driver": 115,
"path-include:leleka-model-format": 12,
+4 -4
View File
@@ -162,12 +162,12 @@ struct ControlVectorFile {
#[cfg(test)]
mod tests;
mod impl_controlvector;
mod control_vector;
#[allow(unused_imports)]
pub use impl_controlvector::*;
mod impl_config;
pub use control_vector::*;
mod methods;
#[allow(unused_imports)]
pub use impl_config::*;
pub use methods::*;
mod optional_env;
#[allow(unused_imports)]
pub use optional_env::*;
-8
View File
@@ -1,8 +0,0 @@
//! Moved out of the parent module by STRA-338: impl Config.
#[allow(unused_imports)]
use super::*;
mod impl_config_2;
mod impl_config_2_2;
mod impl_config_3;
+9
View File
@@ -0,0 +1,9 @@
//! The methods of `Config`: loading the file and environment, provisioning assets, host checks.
#[allow(unused_imports)]
use super::*;
mod load;
mod load_sections;
mod load_with_path;
mod provision;
@@ -0,0 +1,243 @@
//! The sections of `Config::load_with_path` that stand alone: limits, the engine worker pool, the MCP servers.
//! Each reads the parsed file and the environment, checks its own ranges, and fails with the same messages and in the
//! same order as when it was one function.
#[allow(unused_imports)]
use super::*;
pub(super) struct Limits {
pub(super) bind: SocketAddr,
pub(super) max_in_flight_requests: usize,
pub(super) prompt_date: crate::responses::PromptDate,
pub(super) queue_timeout_s: Option<u64>,
pub(super) shutdown_grace_s: u64,
}
pub(super) struct EngineSection {
pub(super) worker: Option<WorkerConfig>,
pub(super) extra_workers: Vec<WorkerConfig>,
pub(super) idle_unload_s: Option<f64>,
}
pub(super) type Mcp = (
std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
crate::mcp::Settings,
);
impl Config {
pub(super) fn read_limits(file: &FileConfig) -> Result<Limits, crate::BoxError> {
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind.clone())
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date.clone())
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
Ok(Limits {
bind,
max_in_flight_requests,
prompt_date,
queue_timeout_s,
shutdown_grace_s,
})
}
pub(super) fn read_engine(file: &FileConfig) -> Result<EngineSection, crate::BoxError> {
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
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,
cuda_memory: None,
args,
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),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
Ok(EngineSection {
worker,
extra_workers,
idle_unload_s,
})
}
/// The four MCP entries of the file: `mcp_servers`, `mcpServers`, `mcp_config_file` and the `mcp` settings block.
pub(super) fn read_mcp(
servers: Option<&serde_json::Value>,
desktop: Option<&serde_json::Value>,
config_file: Option<&Path>,
settings: Option<&serde_json::Value>,
) -> Result<Mcp, crate::BoxError> {
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
servers.unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
desktop.unwrap_or(&null),
"config mcpServers",
)?);
if let Some(path) = 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(settings.unwrap_or(&null))?;
Ok((mcp_servers, mcp_settings))
}
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl Config (2).
//! `Config::load_with_path`: the file, the environment, and the cross-checks between the sections.
use super::load_sections::{EngineSection, Limits};
#[allow(unused_imports)]
use super::*;
@@ -19,166 +20,18 @@ impl Config {
if let Some(native) = &file.native_model {
native.validate(&file.assets)?;
}
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind)
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date)
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
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,
cuda_memory: None,
args,
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),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
let Limits {
bind,
max_in_flight_requests,
prompt_date,
queue_timeout_s,
shutdown_grace_s,
} = Self::read_limits(&file)?;
let EngineSection {
worker,
extra_workers,
idle_unload_s,
} = Self::read_engine(&file)?;
let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
@@ -349,32 +202,12 @@ impl Config {
.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))?;
let (mcp_servers, mcp_settings) = Self::read_mcp(
file.mcp_servers.as_ref(),
file.mcp_servers_desktop.as_ref(),
file.mcp_config_file.as_deref(),
file.mcp.as_ref(),
)?;
if let Some(vision) = &file.vision {
vision.validate()?;
if worker.is_none() {
+14 -14
View File
@@ -142,30 +142,30 @@ pub struct Hub {
#[cfg(test)]
mod tests;
mod impl_default_for_settings;
mod settings_default;
#[allow(unused_imports)]
pub use impl_default_for_settings::*;
mod impl_stdiotransport;
pub use settings_default::*;
mod stdio_transport;
#[allow(unused_imports)]
pub use impl_stdiotransport::*;
pub use stdio_transport::*;
mod dispatch;
#[allow(unused_imports)]
pub use dispatch::*;
mod impl_http;
mod http_transport;
#[allow(unused_imports)]
pub use impl_http::*;
mod impl_transport;
pub use http_transport::*;
mod transport;
#[allow(unused_imports)]
pub use impl_transport::*;
mod impl_server;
pub use transport::*;
mod server;
#[allow(unused_imports)]
pub use impl_server::*;
pub use server::*;
mod result_text;
#[allow(unused_imports)]
pub use result_text::*;
mod impl_hub;
mod hub;
#[allow(unused_imports)]
pub use impl_hub::*;
mod check_server;
pub use hub::*;
mod parse_config;
#[allow(unused_imports)]
pub use check_server::*;
pub use parse_config::*;
@@ -1,9 +1,9 @@
//! Moved out of the parent module by STRA-338: fn check_server, fn servers_from, fn settings_from.
//! Moved out of the parent module by STRA-338: fn parse_config, fn servers_from, fn settings_from.
#[allow(unused_imports)]
use super::*;
pub(super) fn check_server(
pub(super) fn parse_config(
name: &str,
config: &Value,
location: &str,
@@ -73,7 +73,7 @@ pub fn servers_from(
if config.get("disabled") == Some(&json!(true)) {
continue;
}
out.insert(name.clone(), check_server(name, config, location)?);
out.insert(name.clone(), parse_config(name, config, location)?);
}
}
_ => {
+2 -393
View File
@@ -28,399 +28,6 @@ struct Series {
label: Option<(&'static str, &'static str)>,
}
const SERIES: &[Series] = &[
counter(
"leleka_generations_started_total",
"Generations admitted to the engine.",
"/generation/started",
1.0,
),
counter(
"leleka_generations_completed_total",
"Generations that ended with a DONE other than cancel.",
"/generation/completed",
1.0,
),
counter(
"leleka_generations_cancelled_total",
"Generations cancelled or abandoned by the client.",
"/generation/cancelled",
1.0,
),
counter(
"leleka_generations_failed_total",
"Admitted generations that ended without a DONE.",
"/generation/failed_or_interrupted",
1.0,
),
counter(
"leleka_prompt_tokens_total",
"Prompt tokens of settled generations.",
"/totals/prompt_tokens",
1.0,
),
counter(
"leleka_prompt_tokens_reused_total",
"Prompt tokens served from a cache.",
"/totals/reused",
1.0,
),
counter(
"leleka_generated_tokens_total",
"Tokens generated by settled generations.",
"/totals/output_tokens",
1.0,
),
counter(
"leleka_prefill_seconds_total",
"Engine time spent reading prompts.",
"/totals/prompt_ms",
1e-3,
),
counter(
"leleka_decode_seconds_total",
"Engine time spent generating tokens.",
"/totals/decode_ms",
1e-3,
),
counter(
"leleka_draft_tokens_offered_total",
"Speculative draft tokens offered.",
"/totals/drafts_offered",
1.0,
),
counter(
"leleka_draft_tokens_accepted_total",
"Speculative draft tokens accepted.",
"/totals/drafts_accepted",
1.0,
),
counter(
"leleka_memory_gate_rejections_total",
"Requests refused up front for host memory pressure.",
"/memory/gate_rejections",
1.0,
),
gauge(
"leleka_up",
"1 when the engine is loaded and accepting generations.",
"/up",
1.0,
),
gauge(
"leleka_generation_active",
"1 while a generation runs.",
"/live/active",
1.0,
),
gauge(
"leleka_generation_elapsed_seconds",
"Seconds the running generation has been active.",
"/live/elapsed_s",
1.0,
),
gauge(
"leleka_requests_queued",
"Generations waiting for the engine.",
"/live/queued",
1.0,
),
gauge(
"leleka_queue_used",
"Commands in the bounded generation channel.",
"/queue_used",
1.0,
),
gauge(
"leleka_queue_capacity",
"Capacity of the generation channel.",
"/queue_capacity",
1.0,
),
gauge(
"leleka_context_max_tokens",
"Context window the engine serves, in tokens.",
"/engine/max_context",
1.0,
),
gauge(
"leleka_context_live_tokens",
"Tokens in the session context (prompt plus output).",
"/telemetry/context/live_tokens",
1.0,
),
gauge(
"leleka_context_used_percent",
"Share of the context window in use.",
"/telemetry/context/used_pct",
1.0,
),
gauge(
"leleka_gpu_utilization_percent",
"Share of the last sample period in which a kernel ran.",
"/hardware/gpu_util",
1.0,
),
gauge(
"leleka_gpu_memory_utilization_percent",
"Share of the period the memory interface was busy.",
"/hardware/gpu_mem_util",
1.0,
),
gauge(
"leleka_gpu_memory_used_bytes",
"Device memory in use.",
"/hardware/gpu_mem_used",
1.0,
),
gauge(
"leleka_gpu_memory_total_bytes",
"Device memory installed.",
"/hardware/gpu_mem_total",
1.0,
),
gauge(
"leleka_gpu_temperature_celsius",
"GPU core temperature.",
"/hardware/gpu_temp",
1.0,
),
gauge(
"leleka_gpu_power_watts",
"GPU board power draw.",
"/hardware/gpu_power",
1.0,
),
gauge(
"leleka_gpu_sm_clock_megahertz",
"GPU SM clock.",
"/hardware/gpu_sm_clock_mhz",
1.0,
),
gauge(
"leleka_host_memory_used_bytes",
"Host RAM in use (total minus available).",
"/hardware/ram_used",
1.0,
),
gauge(
"leleka_host_memory_total_bytes",
"Host RAM installed.",
"/hardware/ram_total",
1.0,
),
gauge(
"leleka_host_swap_used_bytes",
"Swap in use.",
"/hardware/swap_used",
1.0,
),
gauge(
"leleka_engine_resident_bytes",
"Resident set of the engine process.",
"/hardware/ram_process_rss",
1.0,
),
gauge(
"leleka_engine_pinned_bytes",
"Page-locked memory of the engine process.",
"/hardware/ram_process_pinned",
1.0,
),
gauge(
"leleka_host_cpu_busy_percent",
"Busy share of all CPUs.",
"/hardware/cpu",
1.0,
),
gauge(
"leleka_engine_cpu_busy_cores",
"CPU cores worth of time the engine used.",
"/hardware/cpu_process_cores",
1.0,
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s",
("window", "live"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_last",
("window", "last"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s_mean",
("window", "average"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_lifetime",
("window", "lifetime"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_last",
("window", "last"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/hardware/prefill_tok_s_mean",
("window", "average"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_lifetime",
("window", "lifetime"),
),
gauge(
"leleka_gpu_memory_clock_megahertz",
"GPU memory clock.",
"/telemetry/gpu/mem_clock_mhz",
1.0,
),
gauge(
"leleka_gpu_pcie_receive_bytes_per_second",
"PCIe traffic into the GPU over the last sampling window.",
"/telemetry/gpu/pcie_rx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_pcie_transmit_bytes_per_second",
"PCIe traffic out of the GPU over the last sampling window.",
"/telemetry/gpu/pcie_tx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_throttle_reasons",
"NVML clocks-throttle-reasons bit mask (0: the clocks are not held down).",
"/telemetry/gpu/throttle_reasons",
1.0,
),
gauge(
"leleka_engine_uptime_seconds",
"Seconds since the engine process started.",
"/telemetry/uptime_s",
1.0,
),
gauge(
"leleka_api_uptime_seconds",
"Seconds since this API process started.",
"/api_uptime_s",
1.0,
),
gauge(
"leleka_service_uptime_seconds",
"Seconds since the supervisor started.",
"/supervisor/uptime_s",
1.0,
),
counter(
"leleka_engine_restarts_total",
"Engine restarts by the supervisor since the service started (crash, hang, failed restart).",
"/supervisor/restarts_total",
1.0,
),
counter(
"leleka_spec_rounds_total",
"Speculative verify rounds the engine ran.",
"/telemetry/spec/rounds",
1.0,
),
counter(
"leleka_spec_tokens_total",
"Tokens those rounds committed.",
"/telemetry/spec/tokens",
1.0,
),
gauge(
"leleka_spec_tokens_per_round",
"Committed tokens per verify round, lifetime (1 means drafting gains nothing).",
"/telemetry/spec/tokens_per_round",
1.0,
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/vram_entries",
("tier", "vram"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/pcie_entries",
("tier", "pcie"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/cpu_entries",
("tier", "cpu"),
),
gauge(
"leleka_expert_tier_vram_ratio",
"Share of expert entries served from the VRAM tier (the tier's hit rate).",
"/telemetry/expert_tier/vram_ratio",
1.0,
),
counter(
"leleka_expert_tier_swaps_total",
"Experts swapped in or out of the VRAM tier by adaptation.",
"/telemetry/expert_tier/swaps",
1.0,
),
counter(
"leleka_nan_guard_healed_total",
"Non-finite verify windows that a retry fixed.",
"/telemetry/nan_guard/healed_windows",
1.0,
),
counter(
"leleka_nan_guard_unhealed_total",
"Non-finite verify windows given up on.",
"/telemetry/nan_guard/unhealed_windows",
1.0,
),
gauge(
"leleka_prefix_cache_requests",
"Requests the prefix cache has seen.",
"/telemetry/cache/requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_requests",
"Requests that reused a checkpoint.",
"/telemetry/cache/hit_requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_ratio",
"Share of requests that reused a checkpoint.",
"/telemetry/cache/hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_token_hit_ratio",
"Share of prompt tokens served from a checkpoint.",
"/telemetry/cache/token_hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_reused_tokens",
"Prompt tokens reused since the engine started.",
"/telemetry/cache/reused_tokens",
1.0,
),
];
/// The phase the engine reports, as a one-hot gauge (`idle`, `prefill`, `decode`).
const PHASES: [&str; 3] = ["idle", "prefill", "decode"];
@@ -436,6 +43,8 @@ const THROTTLE_REASONS: [(u64, &str); 5] = [
#[cfg(test)]
mod tests;
mod series;
use series::SERIES;
mod counter;
#[allow(unused_imports)]
pub use counter::*;
+396
View File
@@ -0,0 +1,396 @@
//! The series table: every Prometheus metric the control plane exposes and where its value comes from.
use super::*;
pub(super) const SERIES: &[Series] = &[
counter(
"leleka_generations_started_total",
"Generations admitted to the engine.",
"/generation/started",
1.0,
),
counter(
"leleka_generations_completed_total",
"Generations that ended with a DONE other than cancel.",
"/generation/completed",
1.0,
),
counter(
"leleka_generations_cancelled_total",
"Generations cancelled or abandoned by the client.",
"/generation/cancelled",
1.0,
),
counter(
"leleka_generations_failed_total",
"Admitted generations that ended without a DONE.",
"/generation/failed_or_interrupted",
1.0,
),
counter(
"leleka_prompt_tokens_total",
"Prompt tokens of settled generations.",
"/totals/prompt_tokens",
1.0,
),
counter(
"leleka_prompt_tokens_reused_total",
"Prompt tokens served from a cache.",
"/totals/reused",
1.0,
),
counter(
"leleka_generated_tokens_total",
"Tokens generated by settled generations.",
"/totals/output_tokens",
1.0,
),
counter(
"leleka_prefill_seconds_total",
"Engine time spent reading prompts.",
"/totals/prompt_ms",
1e-3,
),
counter(
"leleka_decode_seconds_total",
"Engine time spent generating tokens.",
"/totals/decode_ms",
1e-3,
),
counter(
"leleka_draft_tokens_offered_total",
"Speculative draft tokens offered.",
"/totals/drafts_offered",
1.0,
),
counter(
"leleka_draft_tokens_accepted_total",
"Speculative draft tokens accepted.",
"/totals/drafts_accepted",
1.0,
),
counter(
"leleka_memory_gate_rejections_total",
"Requests refused up front for host memory pressure.",
"/memory/gate_rejections",
1.0,
),
gauge(
"leleka_up",
"1 when the engine is loaded and accepting generations.",
"/up",
1.0,
),
gauge(
"leleka_generation_active",
"1 while a generation runs.",
"/live/active",
1.0,
),
gauge(
"leleka_generation_elapsed_seconds",
"Seconds the running generation has been active.",
"/live/elapsed_s",
1.0,
),
gauge(
"leleka_requests_queued",
"Generations waiting for the engine.",
"/live/queued",
1.0,
),
gauge(
"leleka_queue_used",
"Commands in the bounded generation channel.",
"/queue_used",
1.0,
),
gauge(
"leleka_queue_capacity",
"Capacity of the generation channel.",
"/queue_capacity",
1.0,
),
gauge(
"leleka_context_max_tokens",
"Context window the engine serves, in tokens.",
"/engine/max_context",
1.0,
),
gauge(
"leleka_context_live_tokens",
"Tokens in the session context (prompt plus output).",
"/telemetry/context/live_tokens",
1.0,
),
gauge(
"leleka_context_used_percent",
"Share of the context window in use.",
"/telemetry/context/used_pct",
1.0,
),
gauge(
"leleka_gpu_utilization_percent",
"Share of the last sample period in which a kernel ran.",
"/hardware/gpu_util",
1.0,
),
gauge(
"leleka_gpu_memory_utilization_percent",
"Share of the period the memory interface was busy.",
"/hardware/gpu_mem_util",
1.0,
),
gauge(
"leleka_gpu_memory_used_bytes",
"Device memory in use.",
"/hardware/gpu_mem_used",
1.0,
),
gauge(
"leleka_gpu_memory_total_bytes",
"Device memory installed.",
"/hardware/gpu_mem_total",
1.0,
),
gauge(
"leleka_gpu_temperature_celsius",
"GPU core temperature.",
"/hardware/gpu_temp",
1.0,
),
gauge(
"leleka_gpu_power_watts",
"GPU board power draw.",
"/hardware/gpu_power",
1.0,
),
gauge(
"leleka_gpu_sm_clock_megahertz",
"GPU SM clock.",
"/hardware/gpu_sm_clock_mhz",
1.0,
),
gauge(
"leleka_host_memory_used_bytes",
"Host RAM in use (total minus available).",
"/hardware/ram_used",
1.0,
),
gauge(
"leleka_host_memory_total_bytes",
"Host RAM installed.",
"/hardware/ram_total",
1.0,
),
gauge(
"leleka_host_swap_used_bytes",
"Swap in use.",
"/hardware/swap_used",
1.0,
),
gauge(
"leleka_engine_resident_bytes",
"Resident set of the engine process.",
"/hardware/ram_process_rss",
1.0,
),
gauge(
"leleka_engine_pinned_bytes",
"Page-locked memory of the engine process.",
"/hardware/ram_process_pinned",
1.0,
),
gauge(
"leleka_host_cpu_busy_percent",
"Busy share of all CPUs.",
"/hardware/cpu",
1.0,
),
gauge(
"leleka_engine_cpu_busy_cores",
"CPU cores worth of time the engine used.",
"/hardware/cpu_process_cores",
1.0,
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s",
("window", "live"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_last",
("window", "last"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s_mean",
("window", "average"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_lifetime",
("window", "lifetime"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_last",
("window", "last"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/hardware/prefill_tok_s_mean",
("window", "average"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_lifetime",
("window", "lifetime"),
),
gauge(
"leleka_gpu_memory_clock_megahertz",
"GPU memory clock.",
"/telemetry/gpu/mem_clock_mhz",
1.0,
),
gauge(
"leleka_gpu_pcie_receive_bytes_per_second",
"PCIe traffic into the GPU over the last sampling window.",
"/telemetry/gpu/pcie_rx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_pcie_transmit_bytes_per_second",
"PCIe traffic out of the GPU over the last sampling window.",
"/telemetry/gpu/pcie_tx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_throttle_reasons",
"NVML clocks-throttle-reasons bit mask (0: the clocks are not held down).",
"/telemetry/gpu/throttle_reasons",
1.0,
),
gauge(
"leleka_engine_uptime_seconds",
"Seconds since the engine process started.",
"/telemetry/uptime_s",
1.0,
),
gauge(
"leleka_api_uptime_seconds",
"Seconds since this API process started.",
"/api_uptime_s",
1.0,
),
gauge(
"leleka_service_uptime_seconds",
"Seconds since the supervisor started.",
"/supervisor/uptime_s",
1.0,
),
counter(
"leleka_engine_restarts_total",
"Engine restarts by the supervisor since the service started (crash, hang, failed restart).",
"/supervisor/restarts_total",
1.0,
),
counter(
"leleka_spec_rounds_total",
"Speculative verify rounds the engine ran.",
"/telemetry/spec/rounds",
1.0,
),
counter(
"leleka_spec_tokens_total",
"Tokens those rounds committed.",
"/telemetry/spec/tokens",
1.0,
),
gauge(
"leleka_spec_tokens_per_round",
"Committed tokens per verify round, lifetime (1 means drafting gains nothing).",
"/telemetry/spec/tokens_per_round",
1.0,
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/vram_entries",
("tier", "vram"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/pcie_entries",
("tier", "pcie"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/cpu_entries",
("tier", "cpu"),
),
gauge(
"leleka_expert_tier_vram_ratio",
"Share of expert entries served from the VRAM tier (the tier's hit rate).",
"/telemetry/expert_tier/vram_ratio",
1.0,
),
counter(
"leleka_expert_tier_swaps_total",
"Experts swapped in or out of the VRAM tier by adaptation.",
"/telemetry/expert_tier/swaps",
1.0,
),
counter(
"leleka_nan_guard_healed_total",
"Non-finite verify windows that a retry fixed.",
"/telemetry/nan_guard/healed_windows",
1.0,
),
counter(
"leleka_nan_guard_unhealed_total",
"Non-finite verify windows given up on.",
"/telemetry/nan_guard/unhealed_windows",
1.0,
),
gauge(
"leleka_prefix_cache_requests",
"Requests the prefix cache has seen.",
"/telemetry/cache/requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_requests",
"Requests that reused a checkpoint.",
"/telemetry/cache/hit_requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_ratio",
"Share of requests that reused a checkpoint.",
"/telemetry/cache/hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_token_hit_ratio",
"Share of prompt tokens served from a checkpoint.",
"/telemetry/cache/token_hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_reused_tokens",
"Prompt tokens reused since the engine started.",
"/telemetry/cache/reused_tokens",
1.0,
),
];
+4 -4
View File
@@ -185,9 +185,9 @@ mod tests;
mod endpoint_index;
#[allow(unused_imports)]
pub use endpoint_index::*;
mod impl_obshandle;
mod obs_handle;
#[allow(unused_imports)]
pub use impl_obshandle::*;
mod note_engine_attached;
pub use obs_handle::*;
mod engine_counters;
#[allow(unused_imports)]
pub use note_engine_attached::*;
pub use engine_counters::*;
+1 -407
View File
@@ -17,413 +17,7 @@ struct Options {
const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]";
#[cfg(unix)]
mod unix {
use super::*;
use std::{
fs::{self, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
process::Stdio,
time::Duration,
};
pub(super) fn publish(directory: &Path, name: &str, content: &[u8]) -> Result<bool, String> {
validate_name(name)?;
let mut builder = fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder
.create(directory)
.map_err(|e| format!("create user unit directory: {e}"))?;
check_directory(directory)?;
let path = directory.join(name);
match same_file(&path, content) {
Ok(()) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(e) => return Err(format!("refusing existing unit {}: {e}", path.display())),
}
let temp = directory.join(format!(
".strata-unit-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_nanos()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&temp)
.map_err(|e| e.to_string())?;
let result = (|| {
file.write_all(content)?;
file.sync_all()?;
let created = match fs::hard_link(&temp, &path) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
same_file(&path, content)?;
false
}
Err(e) => return Err(e),
};
fs::File::open(directory)?.sync_all()?;
Ok(created)
})();
let cleanup = fs::remove_file(&temp);
result
.map_err(|e: std::io::Error| format!("publish unit: {e}"))
.and_then(|created| {
cleanup.map_err(|e| format!("remove unit staging file: {e}"))?;
Ok(created)
})
}
pub(super) fn check_directory(directory: &Path) -> Result<(), String> {
let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?;
if !metadata.is_dir()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o022 != 0
{
return Err(
"user unit directory must be an owned directory, not writable by other users"
.into(),
);
}
Ok(())
}
pub(super) fn same_file(path: &Path, content: &[u8]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o077 != 0
|| metadata.len() != content.len() as u64
{
return Err(std::io::Error::other(
"requires an owned private regular file with identical content",
));
}
let mut actual = Vec::new();
(&mut file)
.take(content.len() as u64 + 1)
.read_to_end(&mut actual)?;
if actual != content {
return Err(std::io::Error::other(
"different unit content; choose a new unit name",
));
}
Ok(())
}
// Never replace/remove a conflicting activation link even for a valid unit.
pub(super) fn check_activation_link(path: &Path) -> Result<(), String> {
let directory = path
.parent()
.ok_or("unit parent absent")?
.join("default.target.wants");
match fs::symlink_metadata(&directory) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(meta) if meta.is_dir() && meta.uid() == unsafe { libc::geteuid() }
&& meta.mode() & 0o022 == 0 => (),
_ => return Err("activation directory must be an owned real directory without group/other write access".into()),
}
let link = directory.join(path.file_name().ok_or("unit name absent")?);
match fs::symlink_metadata(&link) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Ok(meta)
if meta.file_type().is_symlink()
&& link.canonicalize().ok()
== Some(path.canonicalize().map_err(|e| e.to_string())?) =>
{
Ok(())
}
_ => Err(
"conflicting activation link; reconcile it explicitly before enable/disable".into(),
),
}
}
// The manager may have different XDG paths or higher-priority runtime units.
// Refuse to start a different service or a unit modified by existing drop-ins.
pub(super) async fn verify_loaded_unit(unit: &str, path: &Path) -> Result<(), String> {
let output = show(unit, &["FragmentPath", "DropInPaths", "NeedDaemonReload"]).await?;
let fragment = output
.lines()
.find_map(|s| s.strip_prefix("FragmentPath="))
.ok_or("manager has no unit fragment")?;
let drop_ins = output
.lines()
.find_map(|s| s.strip_prefix("DropInPaths="))
.ok_or("manager did not report drop-ins")?;
let reload = output
.lines()
.find_map(|s| s.strip_prefix("NeedDaemonReload="));
if reload != Some("no") {
return Err("systemd unit is stale or reload state is unknown; reconcile the unit and run daemon-reload explicitly before control".into());
}
if !drop_ins.is_empty()
|| Path::new(fragment).canonicalize().ok()
!= Some(path.canonicalize().map_err(|e| e.to_string())?)
{
return Err("systemd resolves a different unit or existing drop-ins; use the manager's config directory and a new unit name".into());
}
Ok(())
}
async fn show(unit: &str, properties: &[&str]) -> Result<String, String> {
use tokio::io::AsyncReadExt;
let mut child = tokio::process::Command::new("systemctl")
.args(["--user", "--no-pager", "show"])
.args(properties.iter().map(|p| format!("--property={p}")))
.args(["--", unit])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("verify loaded unit: {e}"))?;
let mut stdout = child
.stdout
.take()
.ok_or("missing systemctl output pipe")?
.take(16385);
let mut bytes = Vec::new();
let result = tokio::time::timeout(Duration::from_secs(30), async {
stdout.read_to_end(&mut bytes).await?;
if bytes.len() > 16384 {
return Err(std::io::Error::other("systemctl output exceeded limit"));
}
let status = child.wait().await?;
if !status.success() {
return Err(std::io::Error::other("systemctl show failed"));
}
Ok(())
})
.await;
if !matches!(result, Ok(Ok(()))) {
let _ = child.kill().await;
return Err(format!("verify loaded unit failed: {result:?}"));
}
String::from_utf8(bytes).map_err(|_| "invalid systemctl output".into())
}
pub(super) async fn status(unit: &str) -> Result<serde_json::Value, String> {
parse_status(
&show(
unit,
&["ActiveState", "SubState", "MainPID", "UnitFileState"],
)
.await?,
)
}
fn parse_status(output: &str) -> Result<serde_json::Value, String> {
let mut values = std::collections::BTreeMap::new();
for line in output.lines() {
let (key, value) = line.split_once('=').ok_or("malformed manager status")?;
if !matches!(
key,
"ActiveState" | "SubState" | "MainPID" | "UnitFileState"
) || values.insert(key, value).is_some()
{
return Err("unexpected or duplicate manager status property".into());
}
}
let state = |key| -> Result<&str, String> {
let value = *values.get(key).ok_or("incomplete manager status")?;
if value.is_empty()
|| value.len() > 64
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b"-_".contains(&b))
{
return Err("invalid manager state".into());
}
Ok(value)
};
let pid = *values.get("MainPID").ok_or("manager PID absent")?;
if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) {
return Err("invalid manager PID".into());
}
let pid = pid.parse::<u32>().map_err(|_| "invalid manager PID")?;
Ok(
serde_json::json!({"active_state":state("ActiveState")?,"sub_state":state("SubState")?,"main_pid":pid,"unit_file_state":state("UnitFileState")?}),
)
}
pub(super) async fn systemctl(
action: &str,
unit: &str,
timeout: Duration,
) -> Result<(), String> {
let mut command = tokio::process::Command::new("systemctl");
command.args(["--user", "--no-pager", action]);
match action {
"daemon-reload" => (),
"start" | "stop" | "restart" | "enable" | "disable" => {
command.args(["--", unit]);
}
_ => return Err("unsupported systemctl action".into()),
}
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
bounded(&mut command, timeout)
.await
.map_err(|e| format!("systemctl --user {action}: {e}"))
}
async fn bounded(
command: &mut tokio::process::Command,
timeout: Duration,
) -> Result<(), String> {
let mut child = command.spawn().map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, child.wait()).await {
Ok(Ok(status)) if status.success() => Ok(()),
Ok(result) => Err(format!("command failed: {result:?}")),
Err(_) => {
child
.kill()
.await
.map_err(|e| format!("timed out; kill/reap failed: {e}"))?;
Err("timed out; client killed and reaped (manager job may still be pending)".into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn atomic_reuse_and_conflicts_preserve_bytes() {
let root = std::env::temp_dir().join(format!(
"strata-unit-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-test.service";
assert!(publish(&root, name, b"one").unwrap());
let path = root.join(name);
let inode = fs::metadata(&path).unwrap().ino();
assert!(!publish(&root, name, b"one").unwrap());
assert!(publish(&root, name, b"two").is_err());
assert_eq!(fs::read(&path).unwrap(), b"one");
assert_eq!(fs::metadata(&path).unwrap().ino(), inode);
assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
fs::remove_file(&path).unwrap();
symlink(root.join("missing"), &path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_dir(&path).unwrap();
assert!(publish(&root, name, b"one").unwrap());
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
assert!(publish(&root, name, b"one").is_err());
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn manager_status_is_limited_and_strict() {
let good =
"ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n";
let value = parse_status(good).unwrap();
assert_eq!(value["main_pid"], 123);
assert_eq!(value["active_state"], "active");
assert_eq!(value["unit_file_state"], "disabled");
assert_eq!(
parse_status(
"MainPID=0\nSubState=dead\nActiveState=inactive\nUnitFileState=enabled\n"
)
.unwrap()["main_pid"],
0
);
for bad in [
"",
"MainPID=1\n",
"ActiveState=active\nSubState=running\nMainPID=-1\n",
"ActiveState=active\nSubState=running\nMainPID=4294967296\n",
"ActiveState=active\nSubState=running\nMainPID=+1\n",
"ActiveState=active\nSubState=secret text\nMainPID=1\n",
] {
assert!(parse_status(bad).is_err());
}
assert!(parse_status(&format!("{good}MainPID=2\n")).is_err());
assert!(parse_status(&format!("{good}Environment=secret\n")).is_err());
assert!(parse_status(&good.replace("disabled", "")).is_err());
assert!(parse_status(&format!("{good}UnitFileState=enabled\n")).is_err());
}
#[test]
fn activation_link_conflicts_are_preserved() {
let root = std::env::temp_dir().join(format!(
"strata-activation-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-activation.service";
publish(&root, name, b"owned unit").unwrap();
let path = root.join(name);
assert!(check_activation_link(&path).is_ok());
let wants = root.join("default.target.wants");
fs::create_dir(&wants).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o755)).unwrap();
let link = wants.join(name);
symlink(Path::new("..").join(name), &link).unwrap();
assert!(check_activation_link(&path).is_ok());
fs::remove_file(&link).unwrap();
symlink(root.join("foreign"), &link).unwrap();
let inode = fs::symlink_metadata(&link).unwrap().ino();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::symlink_metadata(&link).unwrap().ino(), inode);
fs::remove_file(&link).unwrap();
fs::write(&link, "foreign bytes").unwrap();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::read(&link).unwrap(), b"foreign bytes");
fs::remove_file(&link).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o777)).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_dir(&wants).unwrap();
symlink(&root, &wants).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_file(&wants).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn failed_and_timed_out_clients_are_reported_and_reaped() {
assert!(
bounded(
tokio::process::Command::new("false").kill_on_drop(true),
Duration::from_secs(1)
)
.await
.is_err()
);
let mut command = tokio::process::Command::new("sleep");
command.arg("30").kill_on_drop(true);
let start = std::time::Instant::now();
let error = bounded(&mut command, Duration::from_millis(20))
.await
.unwrap_err();
assert!(error.contains("killed and reaped"));
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
mod unix;
#[cfg(test)]
mod tests;
+280
View File
@@ -0,0 +1,280 @@
//! Unix side of the unit installer: private publication of the unit file and the `systemctl --user` calls.
use super::*;
use std::{
fs::{self, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
process::Stdio,
time::Duration,
};
pub(super) fn publish(directory: &Path, name: &str, content: &[u8]) -> Result<bool, String> {
validate_name(name)?;
let mut builder = fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder
.create(directory)
.map_err(|e| format!("create user unit directory: {e}"))?;
check_directory(directory)?;
let path = directory.join(name);
match same_file(&path, content) {
Ok(()) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(e) => return Err(format!("refusing existing unit {}: {e}", path.display())),
}
let temp = directory.join(format!(
".strata-unit-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_nanos()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&temp)
.map_err(|e| e.to_string())?;
let result = (|| {
file.write_all(content)?;
file.sync_all()?;
let created = match fs::hard_link(&temp, &path) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
same_file(&path, content)?;
false
}
Err(e) => return Err(e),
};
fs::File::open(directory)?.sync_all()?;
Ok(created)
})();
let cleanup = fs::remove_file(&temp);
result
.map_err(|e: std::io::Error| format!("publish unit: {e}"))
.and_then(|created| {
cleanup.map_err(|e| format!("remove unit staging file: {e}"))?;
Ok(created)
})
}
pub(super) fn check_directory(directory: &Path) -> Result<(), String> {
let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?;
if !metadata.is_dir()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o022 != 0
{
return Err(
"user unit directory must be an owned directory, not writable by other users".into(),
);
}
Ok(())
}
pub(super) fn same_file(path: &Path, content: &[u8]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o077 != 0
|| metadata.len() != content.len() as u64
{
return Err(std::io::Error::other(
"requires an owned private regular file with identical content",
));
}
let mut actual = Vec::new();
(&mut file)
.take(content.len() as u64 + 1)
.read_to_end(&mut actual)?;
if actual != content {
return Err(std::io::Error::other(
"different unit content; choose a new unit name",
));
}
Ok(())
}
// Never replace/remove a conflicting activation link even for a valid unit.
pub(super) fn check_activation_link(path: &Path) -> Result<(), String> {
let directory = path
.parent()
.ok_or("unit parent absent")?
.join("default.target.wants");
match fs::symlink_metadata(&directory) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(meta)
if meta.is_dir()
&& meta.uid() == unsafe { libc::geteuid() }
&& meta.mode() & 0o022 == 0 => {}
_ => return Err(
"activation directory must be an owned real directory without group/other write access"
.into(),
),
}
let link = directory.join(path.file_name().ok_or("unit name absent")?);
match fs::symlink_metadata(&link) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Ok(meta)
if meta.file_type().is_symlink()
&& link.canonicalize().ok()
== Some(path.canonicalize().map_err(|e| e.to_string())?) =>
{
Ok(())
}
_ => {
Err("conflicting activation link; reconcile it explicitly before enable/disable".into())
}
}
}
// The manager may have different XDG paths or higher-priority runtime units.
// Refuse to start a different service or a unit modified by existing drop-ins.
pub(super) async fn verify_loaded_unit(unit: &str, path: &Path) -> Result<(), String> {
let output = show(unit, &["FragmentPath", "DropInPaths", "NeedDaemonReload"]).await?;
let fragment = output
.lines()
.find_map(|s| s.strip_prefix("FragmentPath="))
.ok_or("manager has no unit fragment")?;
let drop_ins = output
.lines()
.find_map(|s| s.strip_prefix("DropInPaths="))
.ok_or("manager did not report drop-ins")?;
let reload = output
.lines()
.find_map(|s| s.strip_prefix("NeedDaemonReload="));
if reload != Some("no") {
return Err("systemd unit is stale or reload state is unknown; reconcile the unit and run daemon-reload explicitly before control".into());
}
if !drop_ins.is_empty()
|| Path::new(fragment).canonicalize().ok()
!= Some(path.canonicalize().map_err(|e| e.to_string())?)
{
return Err("systemd resolves a different unit or existing drop-ins; use the manager's config directory and a new unit name".into());
}
Ok(())
}
async fn show(unit: &str, properties: &[&str]) -> Result<String, String> {
use tokio::io::AsyncReadExt;
let mut child = tokio::process::Command::new("systemctl")
.args(["--user", "--no-pager", "show"])
.args(properties.iter().map(|p| format!("--property={p}")))
.args(["--", unit])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("verify loaded unit: {e}"))?;
let mut stdout = child
.stdout
.take()
.ok_or("missing systemctl output pipe")?
.take(16385);
let mut bytes = Vec::new();
let result = tokio::time::timeout(Duration::from_secs(30), async {
stdout.read_to_end(&mut bytes).await?;
if bytes.len() > 16384 {
return Err(std::io::Error::other("systemctl output exceeded limit"));
}
let status = child.wait().await?;
if !status.success() {
return Err(std::io::Error::other("systemctl show failed"));
}
Ok(())
})
.await;
if !matches!(result, Ok(Ok(()))) {
let _ = child.kill().await;
return Err(format!("verify loaded unit failed: {result:?}"));
}
String::from_utf8(bytes).map_err(|_| "invalid systemctl output".into())
}
pub(super) async fn status(unit: &str) -> Result<serde_json::Value, String> {
parse_status(
&show(
unit,
&["ActiveState", "SubState", "MainPID", "UnitFileState"],
)
.await?,
)
}
fn parse_status(output: &str) -> Result<serde_json::Value, String> {
let mut values = std::collections::BTreeMap::new();
for line in output.lines() {
let (key, value) = line.split_once('=').ok_or("malformed manager status")?;
if !matches!(
key,
"ActiveState" | "SubState" | "MainPID" | "UnitFileState"
) || values.insert(key, value).is_some()
{
return Err("unexpected or duplicate manager status property".into());
}
}
let state = |key| -> Result<&str, String> {
let value = *values.get(key).ok_or("incomplete manager status")?;
if value.is_empty()
|| value.len() > 64
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b"-_".contains(&b))
{
return Err("invalid manager state".into());
}
Ok(value)
};
let pid = *values.get("MainPID").ok_or("manager PID absent")?;
if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) {
return Err("invalid manager PID".into());
}
let pid = pid.parse::<u32>().map_err(|_| "invalid manager PID")?;
Ok(
serde_json::json!({"active_state":state("ActiveState")?,"sub_state":state("SubState")?,"main_pid":pid,"unit_file_state":state("UnitFileState")?}),
)
}
pub(super) async fn systemctl(action: &str, unit: &str, timeout: Duration) -> Result<(), String> {
let mut command = tokio::process::Command::new("systemctl");
command.args(["--user", "--no-pager", action]);
match action {
"daemon-reload" => (),
"start" | "stop" | "restart" | "enable" | "disable" => {
command.args(["--", unit]);
}
_ => return Err("unsupported systemctl action".into()),
}
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
bounded(&mut command, timeout)
.await
.map_err(|e| format!("systemctl --user {action}: {e}"))
}
async fn bounded(command: &mut tokio::process::Command, timeout: Duration) -> Result<(), String> {
let mut child = command.spawn().map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, child.wait()).await {
Ok(Ok(status)) if status.success() => Ok(()),
Ok(result) => Err(format!("command failed: {result:?}")),
Err(_) => {
child
.kill()
.await
.map_err(|e| format!("timed out; kill/reap failed: {e}"))?;
Err("timed out; client killed and reaped (manager job may still be pending)".into())
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,122 @@
//! Tests of the unit publication and the `systemctl` wrapper (moved out of service_install.rs, STRA-338 S7).
use super::*;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn atomic_reuse_and_conflicts_preserve_bytes() {
let root = std::env::temp_dir().join(format!(
"strata-unit-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-test.service";
assert!(publish(&root, name, b"one").unwrap());
let path = root.join(name);
let inode = fs::metadata(&path).unwrap().ino();
assert!(!publish(&root, name, b"one").unwrap());
assert!(publish(&root, name, b"two").is_err());
assert_eq!(fs::read(&path).unwrap(), b"one");
assert_eq!(fs::metadata(&path).unwrap().ino(), inode);
assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
fs::remove_file(&path).unwrap();
symlink(root.join("missing"), &path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_dir(&path).unwrap();
assert!(publish(&root, name, b"one").unwrap());
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
assert!(publish(&root, name, b"one").is_err());
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn manager_status_is_limited_and_strict() {
let good = "ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n";
let value = parse_status(good).unwrap();
assert_eq!(value["main_pid"], 123);
assert_eq!(value["active_state"], "active");
assert_eq!(value["unit_file_state"], "disabled");
assert_eq!(
parse_status("MainPID=0\nSubState=dead\nActiveState=inactive\nUnitFileState=enabled\n")
.unwrap()["main_pid"],
0
);
for bad in [
"",
"MainPID=1\n",
"ActiveState=active\nSubState=running\nMainPID=-1\n",
"ActiveState=active\nSubState=running\nMainPID=4294967296\n",
"ActiveState=active\nSubState=running\nMainPID=+1\n",
"ActiveState=active\nSubState=secret text\nMainPID=1\n",
] {
assert!(parse_status(bad).is_err());
}
assert!(parse_status(&format!("{good}MainPID=2\n")).is_err());
assert!(parse_status(&format!("{good}Environment=secret\n")).is_err());
assert!(parse_status(&good.replace("disabled", "")).is_err());
assert!(parse_status(&format!("{good}UnitFileState=enabled\n")).is_err());
}
#[test]
fn activation_link_conflicts_are_preserved() {
let root = std::env::temp_dir().join(format!(
"strata-activation-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-activation.service";
publish(&root, name, b"owned unit").unwrap();
let path = root.join(name);
assert!(check_activation_link(&path).is_ok());
let wants = root.join("default.target.wants");
fs::create_dir(&wants).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o755)).unwrap();
let link = wants.join(name);
symlink(Path::new("..").join(name), &link).unwrap();
assert!(check_activation_link(&path).is_ok());
fs::remove_file(&link).unwrap();
symlink(root.join("foreign"), &link).unwrap();
let inode = fs::symlink_metadata(&link).unwrap().ino();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::symlink_metadata(&link).unwrap().ino(), inode);
fs::remove_file(&link).unwrap();
fs::write(&link, "foreign bytes").unwrap();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::read(&link).unwrap(), b"foreign bytes");
fs::remove_file(&link).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o777)).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_dir(&wants).unwrap();
symlink(&root, &wants).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_file(&wants).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn failed_and_timed_out_clients_are_reported_and_reaped() {
assert!(
bounded(
tokio::process::Command::new("false").kill_on_drop(true),
Duration::from_secs(1)
)
.await
.is_err()
);
let mut command = tokio::process::Command::new("sleep");
command.arg("30").kill_on_drop(true);
let start = std::time::Instant::now();
let error = bounded(&mut command, Duration::from_millis(20))
.await
.unwrap_err();
assert!(error.contains("killed and reaped"));
assert!(start.elapsed() < Duration::from_secs(2));
}
+7 -289
View File
@@ -107,296 +107,14 @@ pub struct Vision {
static NEXT_DIR: AtomicU64 = AtomicU64::new(0);
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
mod tests;
fn fake(dir: &Path, mode: &str) -> VisionConfig {
let exe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fake_vision.sh");
let wrapper = dir.join(format!("vision-{mode}.sh"));
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n",
exe.display(),
dir.display()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
VisionConfig {
exe: wrapper,
mmproj: "/m/mmproj.gguf".into(),
model: "/m/model.gguf".into(),
gpu: false,
threads: None,
max_tokens: None,
cuda_device: None,
}
}
fn scratch(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("strata-vision-test-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn png(tag: u8) -> Vec<u8> {
let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
data.push(tag);
data
}
fn data_url(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::from("data:image/png;base64,");
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[test]
fn arguments_and_environment_follow_the_python_server() {
let mut config = VisionConfig {
exe: "/bin/strata-vision".into(),
mmproj: "/m/p.gguf".into(),
model: "/m/t.gguf".into(),
gpu: true,
threads: Some(6),
max_tokens: Some(1024),
cuda_device: Some(2),
};
assert_eq!(
config.args(),
[
"--mmproj",
"/m/p.gguf",
"--model",
"/m/t.gguf",
"--gpu",
"--threads",
"6",
"--max-tokens",
"1024"
]
);
assert_eq!(
config.env(),
vec![
("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()),
("CUDA_VISIBLE_DEVICES", "2".to_owned())
]
);
config.gpu = false;
config.threads = Some(0);
config.max_tokens = None;
config.cuda_device = None;
assert_eq!(
config.args(),
["--mmproj", "/m/p.gguf", "--model", "/m/t.gguf"]
);
assert!(config.env().is_empty());
assert!(
serde_json::from_str::<VisionConfig>(r#"{"exe":"a","mmproj":"b","model":"c","x":1}"#)
.is_err()
);
}
#[tokio::test]
async fn sources_load_like_the_python_server() {
let dir = scratch("load");
let file = dir.join("a.png");
std::fs::write(&file, png(1)).unwrap();
assert_eq!(Vision::load(file.to_str().unwrap()).await.unwrap(), png(1));
assert_eq!(
Vision::load(&format!("file://{}", file.display()))
.await
.unwrap(),
png(1)
);
assert_eq!(Vision::load(&data_url(&png(2))).await.unwrap(), png(2));
let nothing = "an image must be a data: URL, an http(s) URL or a local file path";
for source in ["", "nope.png", dir.to_str().unwrap()] {
assert_eq!(
Vision::load(source).await.unwrap_err(),
VisionError::Invalid(nothing.into())
);
}
assert_eq!(
Vision::load("data:image/png;base64,QQ").await.unwrap_err(),
VisionError::Invalid("Incorrect padding".into())
);
assert!(matches!(
Vision::load("data:image/png").await,
Err(VisionError::Invalid(_))
));
assert!(Vision::normalize(b"RIFF....WEBP".to_vec()).is_err());
assert_eq!(Vision::normalize(png(3)).unwrap(), png(3));
}
#[tokio::test]
async fn http_images_are_fetched_with_the_strata_agent() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/pic.png", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let mut agents = Vec::new();
for status in ["200 OK", "404 Not Found"] {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = vec![0u8; 4096];
let n = socket.read(&mut buffer).await.unwrap();
agents.push(
String::from_utf8_lossy(&buffer[..n])
.lines()
.find(|l| l.to_ascii_lowercase().starts_with("user-agent"))
.unwrap_or("")
.to_owned(),
);
let body = png(9);
let head = format!(
"HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
body.len()
);
socket.write_all(head.as_bytes()).await.unwrap();
socket.write_all(&body).await.unwrap();
}
agents
});
assert_eq!(Vision::load(&url).await.unwrap(), png(9));
assert!(
matches!(Vision::load(&url).await, Err(VisionError::Invalid(m)) if m.contains("404"))
);
assert!(server.await.unwrap().iter().all(|a| a.ends_with("strata")));
}
#[tokio::test]
async fn encoding_caches_by_content_and_combines_in_prompt_order() {
let dir = scratch("encode");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
assert!(vision.alive().await);
let a = vision.encode(&data_url(&png(1))).await.unwrap();
let b = vision.encode(&data_url(&png(2))).await.unwrap();
let again = vision.encode(&data_url(&png(1))).await.unwrap();
assert_eq!((a.tokens, b.tokens), (6, 6));
assert_eq!(a, again, "the same picture is encoded once");
assert_ne!(a.path, b.path);
let log = std::fs::read_to_string(dir.join("enc.log")).unwrap();
assert_eq!(log.lines().count(), 2);
// The fake writes one SVE1 record whose first float carries the image's first byte count.
let (combined, keep) = vision
.combine(&[a.clone(), b.clone(), a.clone()])
.await
.unwrap();
let one = std::fs::read(&a.path).unwrap();
let two = std::fs::read(&b.path).unwrap();
let mut want = one.clone();
want.extend(&two);
want.extend(&one);
assert_eq!(std::fs::read(&combined).unwrap(), want);
let parsed = policy::parse_embeddings(&want, 4).unwrap();
assert_eq!(parsed.images.len(), 3);
assert_eq!((parsed.images[0].nx, parsed.images[0].ny), (3, 2));
drop(keep);
assert!(
!combined.exists(),
"the per-request file goes with the request"
);
// The temporary image is gone once its reply arrived.
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
let name = e.unwrap().file_name().into_string().unwrap();
!name.ends_with(".img")
}));
vision.close().await;
assert!(!vision.alive().await);
}
#[tokio::test]
async fn encoder_errors_and_death_are_reported_like_the_python_server() {
let dir = scratch("err");
let vision = Vision::start(fake(&dir, "err")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: cannot read the image".into())
);
vision.close().await;
let dir = scratch("die");
let vision = Vision::start(fake(&dir, "die")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: the vision encoder stopped".into())
);
assert!(!vision.alive().await, "the process ended");
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
!e.unwrap()
.file_name()
.into_string()
.unwrap()
.ends_with(".img")
}));
let dir = scratch("bad");
match Vision::start(fake(&dir, "badready")).await {
Err(VisionError::Failed(m)) => assert_eq!(m, "the vision encoder did not start: NOPE"),
other => panic!("{:?}", other.map(|_| ())),
}
}
#[tokio::test]
async fn unload_keeps_the_cache_and_restart_starts_the_encoder_again() {
let dir = scratch("unload");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let first = vision.encode(&data_url(&png(5))).await.unwrap();
vision.unload().await;
assert!(!vision.alive().await);
// cached images need no process
assert_eq!(vision.encode(&data_url(&png(5))).await.unwrap(), first);
vision.ensure_running().await.unwrap();
assert!(vision.alive().await);
vision.ensure_running().await.unwrap();
vision.encode(&data_url(&png(6))).await.unwrap();
assert_eq!(
std::fs::read_to_string(dir.join("starts.log"))
.unwrap()
.lines()
.count(),
2
);
vision.close().await;
}
#[tokio::test]
async fn the_cache_evicts_the_oldest_image_and_its_file() {
let dir = scratch("evict");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let mut first = None;
for tag in 0..=CACHE_LIMIT as u8 {
let encoded = vision.encode(&data_url(&png(tag))).await.unwrap();
first.get_or_insert(encoded);
}
assert!(!first.unwrap().path.exists());
assert_eq!(vision.inner.lock().await.cache.len(), CACHE_LIMIT);
vision.close().await;
}
}
mod impl_visionconfig;
mod config;
#[allow(unused_imports)]
pub use impl_visionconfig::*;
mod impl_vision;
pub use config::*;
mod encoder;
#[allow(unused_imports)]
pub use impl_vision::*;
mod impl_drop_for_vision;
pub use encoder::*;
mod cleanup;
#[allow(unused_imports)]
pub use impl_drop_for_vision::*;
pub use cleanup::*;
+281
View File
@@ -0,0 +1,281 @@
//! Tests of the encoder client against the fake `strata-vision` script (moved out of vision.rs, STRA-338 S7).
use super::*;
use std::os::unix::fs::PermissionsExt;
fn fake(dir: &Path, mode: &str) -> VisionConfig {
let exe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fake_vision.sh");
let wrapper = dir.join(format!("vision-{mode}.sh"));
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n",
exe.display(),
dir.display()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
VisionConfig {
exe: wrapper,
mmproj: "/m/mmproj.gguf".into(),
model: "/m/model.gguf".into(),
gpu: false,
threads: None,
max_tokens: None,
cuda_device: None,
}
}
fn scratch(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("strata-vision-test-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn png(tag: u8) -> Vec<u8> {
let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
data.push(tag);
data
}
fn data_url(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::from("data:image/png;base64,");
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[test]
fn arguments_and_environment_follow_the_python_server() {
let mut config = VisionConfig {
exe: "/bin/strata-vision".into(),
mmproj: "/m/p.gguf".into(),
model: "/m/t.gguf".into(),
gpu: true,
threads: Some(6),
max_tokens: Some(1024),
cuda_device: Some(2),
};
assert_eq!(
config.args(),
[
"--mmproj",
"/m/p.gguf",
"--model",
"/m/t.gguf",
"--gpu",
"--threads",
"6",
"--max-tokens",
"1024"
]
);
assert_eq!(
config.env(),
vec![
("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()),
("CUDA_VISIBLE_DEVICES", "2".to_owned())
]
);
config.gpu = false;
config.threads = Some(0);
config.max_tokens = None;
config.cuda_device = None;
assert_eq!(
config.args(),
["--mmproj", "/m/p.gguf", "--model", "/m/t.gguf"]
);
assert!(config.env().is_empty());
assert!(
serde_json::from_str::<VisionConfig>(r#"{"exe":"a","mmproj":"b","model":"c","x":1}"#)
.is_err()
);
}
#[tokio::test]
async fn sources_load_like_the_python_server() {
let dir = scratch("load");
let file = dir.join("a.png");
std::fs::write(&file, png(1)).unwrap();
assert_eq!(Vision::load(file.to_str().unwrap()).await.unwrap(), png(1));
assert_eq!(
Vision::load(&format!("file://{}", file.display()))
.await
.unwrap(),
png(1)
);
assert_eq!(Vision::load(&data_url(&png(2))).await.unwrap(), png(2));
let nothing = "an image must be a data: URL, an http(s) URL or a local file path";
for source in ["", "nope.png", dir.to_str().unwrap()] {
assert_eq!(
Vision::load(source).await.unwrap_err(),
VisionError::Invalid(nothing.into())
);
}
assert_eq!(
Vision::load("data:image/png;base64,QQ").await.unwrap_err(),
VisionError::Invalid("Incorrect padding".into())
);
assert!(matches!(
Vision::load("data:image/png").await,
Err(VisionError::Invalid(_))
));
assert!(Vision::normalize(b"RIFF....WEBP".to_vec()).is_err());
assert_eq!(Vision::normalize(png(3)).unwrap(), png(3));
}
#[tokio::test]
async fn http_images_are_fetched_with_the_strata_agent() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/pic.png", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let mut agents = Vec::new();
for status in ["200 OK", "404 Not Found"] {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = vec![0u8; 4096];
let n = socket.read(&mut buffer).await.unwrap();
agents.push(
String::from_utf8_lossy(&buffer[..n])
.lines()
.find(|l| l.to_ascii_lowercase().starts_with("user-agent"))
.unwrap_or("")
.to_owned(),
);
let body = png(9);
let head = format!(
"HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
body.len()
);
socket.write_all(head.as_bytes()).await.unwrap();
socket.write_all(&body).await.unwrap();
}
agents
});
assert_eq!(Vision::load(&url).await.unwrap(), png(9));
assert!(matches!(Vision::load(&url).await, Err(VisionError::Invalid(m)) if m.contains("404")));
assert!(server.await.unwrap().iter().all(|a| a.ends_with("strata")));
}
#[tokio::test]
async fn encoding_caches_by_content_and_combines_in_prompt_order() {
let dir = scratch("encode");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
assert!(vision.alive().await);
let a = vision.encode(&data_url(&png(1))).await.unwrap();
let b = vision.encode(&data_url(&png(2))).await.unwrap();
let again = vision.encode(&data_url(&png(1))).await.unwrap();
assert_eq!((a.tokens, b.tokens), (6, 6));
assert_eq!(a, again, "the same picture is encoded once");
assert_ne!(a.path, b.path);
let log = std::fs::read_to_string(dir.join("enc.log")).unwrap();
assert_eq!(log.lines().count(), 2);
// The fake writes one SVE1 record whose first float carries the image's first byte count.
let (combined, keep) = vision
.combine(&[a.clone(), b.clone(), a.clone()])
.await
.unwrap();
let one = std::fs::read(&a.path).unwrap();
let two = std::fs::read(&b.path).unwrap();
let mut want = one.clone();
want.extend(&two);
want.extend(&one);
assert_eq!(std::fs::read(&combined).unwrap(), want);
let parsed = policy::parse_embeddings(&want, 4).unwrap();
assert_eq!(parsed.images.len(), 3);
assert_eq!((parsed.images[0].nx, parsed.images[0].ny), (3, 2));
drop(keep);
assert!(
!combined.exists(),
"the per-request file goes with the request"
);
// The temporary image is gone once its reply arrived.
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
let name = e.unwrap().file_name().into_string().unwrap();
!name.ends_with(".img")
}));
vision.close().await;
assert!(!vision.alive().await);
}
#[tokio::test]
async fn encoder_errors_and_death_are_reported_like_the_python_server() {
let dir = scratch("err");
let vision = Vision::start(fake(&dir, "err")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: cannot read the image".into())
);
vision.close().await;
let dir = scratch("die");
let vision = Vision::start(fake(&dir, "die")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: the vision encoder stopped".into())
);
assert!(!vision.alive().await, "the process ended");
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
!e.unwrap()
.file_name()
.into_string()
.unwrap()
.ends_with(".img")
}));
let dir = scratch("bad");
match Vision::start(fake(&dir, "badready")).await {
Err(VisionError::Failed(m)) => assert_eq!(m, "the vision encoder did not start: NOPE"),
other => panic!("{:?}", other.map(|_| ())),
}
}
#[tokio::test]
async fn unload_keeps_the_cache_and_restart_starts_the_encoder_again() {
let dir = scratch("unload");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let first = vision.encode(&data_url(&png(5))).await.unwrap();
vision.unload().await;
assert!(!vision.alive().await);
// cached images need no process
assert_eq!(vision.encode(&data_url(&png(5))).await.unwrap(), first);
vision.ensure_running().await.unwrap();
assert!(vision.alive().await);
vision.ensure_running().await.unwrap();
vision.encode(&data_url(&png(6))).await.unwrap();
assert_eq!(
std::fs::read_to_string(dir.join("starts.log"))
.unwrap()
.lines()
.count(),
2
);
vision.close().await;
}
#[tokio::test]
async fn the_cache_evicts_the_oldest_image_and_its_file() {
let dir = scratch("evict");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let mut first = None;
for tag in 0..=CACHE_LIMIT as u8 {
let encoded = vision.encode(&data_url(&png(tag))).await.unwrap();
first.get_or_insert(encoded);
}
assert!(!first.unwrap().path.exists());
assert_eq!(vision.inner.lock().await.cache.len(), CACHE_LIMIT);
vision.close().await;
}
File diff suppressed because it is too large Load Diff
+193
View File
@@ -0,0 +1,193 @@
//! Supervisor tests against the mock engine script. Shared fixtures are here; the tests are grouped by topic
//! in the child modules (moved out of worker.rs, STRA-338 S7).
use super::*;
use std::path::Path;
fn fixture_config(mode: &str, timeout_s: u64) -> WorkerConfig {
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/mock_engine.sh")
.into_os_string();
WorkerConfig {
cuda_memory: None,
executable: script,
args: vec![mode.to_owned()],
startup_timeout: Duration::from_secs(timeout_s),
generation_timeout: None,
max_restarts: 0,
..Default::default()
}
}
async fn wait_for(status: &RwLock<WorkerStatus>, wanted: WorkerState) {
timeout(Duration::from_secs(5), async {
loop {
if status.read().await.state == wanted {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker state transition");
}
fn restart_fixture(
mode: &str,
label: &str,
max_restarts: u32,
) -> (WorkerConfig, std::path::PathBuf) {
let root = std::env::temp_dir().join(format!("strata-restart-{label}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir(&root).unwrap();
let mut config = fixture_config(mode, 5);
config.max_restarts = max_restarts;
config.args.push(root.display().to_string());
(config, root)
}
fn command(
token_ids: Vec<u32>,
max_new: u32,
) -> (
GenerationCommand,
oneshot::Receiver<Result<Vec<Event>, String>>,
) {
let (sender, receiver) = oneshot::channel();
(
GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids,
max_new,
..Default::default()
},
result: GenerationResult::Buffered(sender),
},
receiver,
)
}
// ---- 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<RwLock<WorkerStatus>>,
requests: mpsc::Sender<GenerationCommand>,
control: mpsc::Sender<Control>,
stop: watch::Sender<bool>,
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<Duration>) -> 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<Vec<Event>, 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()
}
}
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()
}
}
mod deadlines;
mod generation;
mod handshake;
mod lifecycle;
mod reasoning;
mod restart;
+121
View File
@@ -0,0 +1,121 @@
//! Execution deadline, startup timeout and the stall watchdog.
use super::*;
#[tokio::test]
async fn execution_deadline_covers_blocked_engine_stdin() {
let mut config = fixture_config("blocked-input", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result, received) = oneshot::channel();
requests
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10000; 200000],
max_new: 1,
..Default::default()
},
result: GenerationResult::Buffered(result),
})
.await
.unwrap();
let error = timeout(Duration::from_secs(5), received)
.await
.unwrap()
.unwrap()
.unwrap_err();
assert_eq!(error, "generation exceeded configured execution deadline");
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
}
#[tokio::test]
async fn execution_deadline_covers_full_stream_channel_and_releases_activity() {
let mut config = fixture_config("flood", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(2);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let lifecycle = crate::lifecycle::Lifecycle::default();
let (events, mut received) = mpsc::channel(1);
requests
.send(GenerationCommand {
queue: None,
activity: Some(lifecycle.generation()),
request: Generate {
token_ids: vec![10],
max_new: 100,
..Default::default()
},
result: GenerationResult::Streaming(events),
})
.await
.unwrap();
// Do not read until the worker exits: channel backpressure must not mask timeout.
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
assert_eq!(status.read().await.metrics.completed, 0);
assert_eq!(lifecycle.snapshot().generation_jobs, 0);
assert!(matches!(received.recv().await, Some(Ok(Event::Token(31)))));
assert!(received.recv().await.is_none());
}
#[tokio::test]
async fn startup_timeout_never_sets_ready() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
run(fixture_config("slow", 1), status.clone(), stop_rx).await;
assert_eq!(status.read().await.state, WorkerState::Failed);
}
#[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;
}
@@ -0,0 +1,374 @@
//! One generation through the supervisor: exchange, cancellation, shutdown and stop.
use super::*;
#[tokio::test]
async fn supervisor_exchanges_one_generation_and_stays_ready() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
fixture_config("exchange", 5),
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
sampling: leleka_sampler_ref::RequestSampling {
temperature: Some(0.5),
top_p: Some(0.9),
..Default::default()
},
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events.len(), 4);
assert_eq!(events[1], Event::Token(31));
assert_eq!(events[2], Event::Token(32));
assert!(matches!(events[3], Event::Done(_)));
let metrics = status.read().await.metrics;
assert_eq!(metrics.started, 1);
assert_eq!(metrics.completed, 1);
assert_eq!(metrics.done_generated_tokens, 2);
assert_eq!(metrics.done_prompt_tokens, 2);
assert_eq!(
metrics.last_done.unwrap().decode_tokens_per_second,
Some(1000.0)
);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 300_000,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
assert!(
result_rx
.await
.unwrap()
.unwrap_err()
.contains("exceed context")
);
assert_eq!(status.read().await.metrics.started, 1);
let (invalid, result) = command(vec![99], 1);
commands_tx.send(invalid).await.unwrap();
assert_eq!(result.await.unwrap().unwrap_err(), "unexpected request");
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn dropped_generation_receiver_sends_stop_and_preserves_worker() {
let marker = std::env::temp_dir().join(format!("strata-cancel-drop-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert!(status.read().await.metrics.active_since.is_some());
drop(result_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn dropped_stream_receiver_stops_generation_and_preserves_worker() {
let marker = std::env::temp_dir().join(format!("strata-stream-cancel-{}", std::process::id()));
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (events_tx, mut events_rx) = mpsc::channel(2);
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(
timeout(Duration::from_secs(5), events_rx.recv())
.await
.unwrap()
.unwrap()
.unwrap(),
Event::Token(31)
);
drop(events_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
let next = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(next[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn shutdown_interrupts_active_generation() {
let marker =
std::env::temp_dir().join(format!("strata-cancel-shutdown-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert!(result_rx.await.is_err());
let metrics = status.read().await.metrics;
assert_eq!(metrics.failed_or_interrupted, 1);
assert!(metrics.active_since.is_none());
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn uncooperative_stop_revokes_readiness_and_releases_queued_request() {
let marker = std::env::temp_dir().join(format!("strata-stalled-cancel-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel-stall", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (events_tx, mut events_rx) = mpsc::channel(1);
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(
timeout(Duration::from_secs(5), events_rx.recv())
.await
.unwrap()
.unwrap()
.unwrap(),
Event::Token(31)
);
let cancel_at = tokio::time::Instant::now();
drop(events_rx);
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
timeout(STOP_DRAIN_TIMEOUT + Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert!(cancel_at.elapsed() >= STOP_DRAIN_TIMEOUT);
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
assert!(
result_rx.await.is_err(),
"must not reuse the unaligned worker"
);
assert!(commands_tx.is_closed());
drop(stop_tx);
std::fs::remove_file(marker).unwrap();
}
@@ -0,0 +1,34 @@
//! The READY handshake, shutdown and readiness revocation.
use super::*;
#[tokio::test]
async fn ready_requires_handshake_and_shutdown_sends_quit() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let task = tokio::spawn(run(fixture_config("ready", 5), status.clone(), stop_rx));
wait_for(&status, WorkerState::Ready).await;
assert_eq!(status.read().await.max_context, Some(262144));
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
}
#[tokio::test]
async fn worker_exit_revokes_readiness() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
run(fixture_config("crash", 5), status.clone(), stop_rx).await;
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
}
#[test]
fn ready_line_requires_positive_context() {
assert_eq!(parse_ready("READY 262144 stop"), Some(262144));
assert_eq!(parse_ready("READY 0 stop"), None);
assert_eq!(parse_ready("READY nope stop"), None);
}
+106
View File
@@ -0,0 +1,106 @@
//! Load and unload: unload, lazy start, idle unload, the before-load command.
use super::*;
#[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();
}
@@ -0,0 +1,91 @@
//! Reasoning-budget wrap-up through the supervisor.
use super::*;
#[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<u32> = 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<u32> = 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();
}
+226
View File
@@ -0,0 +1,226 @@
//! Crash handling: restart budget, backoff, startup failure, drain guard.
use super::*;
#[tokio::test]
async fn crash_restarts_worker_without_replaying_active_or_queued_requests() {
let (config, root) = restart_fixture("restart-once", "once", 1);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (first, failed) = command(vec![10, 20], 3);
commands_tx.send(first).await.unwrap();
timeout(Duration::from_secs(5), async {
while !root.join("active").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let (queued, rejected) = command(vec![99], 1);
commands_tx.send(queued).await.unwrap();
std::fs::write(root.join("release"), "").unwrap();
assert!(
timeout(Duration::from_secs(5), failed)
.await
.unwrap()
.is_err()
);
assert!(
timeout(Duration::from_secs(5), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("not replayed")
);
wait_for(&status, WorkerState::Restarting).await;
let (during_backoff, rejected) = command(vec![99], 1);
commands_tx.send(during_backoff).await.unwrap();
assert!(
timeout(Duration::from_secs(1), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("restarting")
);
wait_for(&status, WorkerState::Starting).await;
assert_eq!(status.read().await.max_context, None);
let (during_startup, rejected) = command(vec![99], 1);
commands_tx.send(during_startup).await.unwrap();
assert!(
timeout(Duration::from_secs(1), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("starting")
);
wait_for(&status, WorkerState::Ready).await;
let (fresh, result) = command(vec![99], 1);
commands_tx.send(fresh).await.unwrap();
let events = timeout(Duration::from_secs(5), result)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert_eq!(metrics.cancelled, 0);
assert!(metrics.active_since.is_none());
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
2
);
assert_eq!(
std::fs::read_to_string(root.join("requests")).unwrap(),
"GEN 3 10,20\nGEN 1 99\n"
);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn cancelled_command_keeps_drain_guard_until_stop_terminal() {
let (config, root) = restart_fixture("cancel-drain", "drain", 0);
let lifecycle = crate::lifecycle::Lifecycle::default();
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (events_tx, mut events_rx) = mpsc::channel(2);
commands_tx
.send(GenerationCommand {
queue: None,
activity: Some(lifecycle.generation()),
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(events_rx.recv().await.unwrap().unwrap(), Event::Token(31));
lifecycle.set_draining(true);
drop(events_rx);
timeout(Duration::from_secs(5), async {
while !root.join("stopped").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert_eq!(lifecycle.snapshot().generation_jobs, 1);
assert!(status.read().await.metrics.active_since.is_some());
std::fs::write(root.join("release"), "").unwrap();
timeout(Duration::from_secs(5), async {
while lifecycle.snapshot().generation_jobs != 0 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert_eq!(status.read().await.metrics.cancelled, 1);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn repeated_crashes_exhaust_lifetime_restart_budget() {
let (config, root) = restart_fixture("restart-loop", "loop", 2);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
timeout(
Duration::from_secs(10),
run(config, status.clone(), stop_rx),
)
.await
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
3
);
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn shutdown_during_backoff_prevents_respawn() {
let (config, root) = restart_fixture("restart-loop", "shutdown", 3);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let task = tokio::spawn(run(config, status.clone(), stop_rx));
wait_for(&status, WorkerState::Restarting).await;
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(1), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
1
);
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn startup_failure_is_not_restarted() {
let (config, root) = restart_fixture("restart-bad", "startup", 3);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
timeout(Duration::from_secs(5), run(config, status.clone(), stop_rx))
.await
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
1
);
std::fs::remove_dir_all(root).unwrap();
}
+17 -1
View File
@@ -28,7 +28,7 @@ def extract(path):
if doc:
binary = "doc:" + doc.group(1)
continue
result = re.match(r"test (.+?) \.\.\. (ok|FAILED|ignored)", line)
result = re.search(r"(?:^|\s)test (\S+) \.\.\. (ok|FAILED|ignored)", line)
if result:
outcomes[(binary, result.group(1))] = result.group(2)
continue
@@ -57,6 +57,22 @@ def main(argv):
changed = [(k, before[k], after[k]) for k in before if k in after and before[k] != after[k]]
only_before = sorted(set(before) - set(after))
only_after = sorted(set(after) - set(before))
# A test moved into a child module keeps its function name: pair such tests by (binary, last segment) when the
# pairing is unique on both sides, and compare their outcomes.
moved = []
for key in list(only_before):
tail = key[1].split("::")[-1]
old_same = [k for k in only_before if k[0] == key[0] and k[1].split("::")[-1] == tail]
new_same = [k for k in only_after if k[0] == key[0] and k[1].split("::")[-1] == tail]
if len(old_same) == 1 and len(new_same) == 1:
moved.append((key, new_same[0]))
only_before.remove(key)
only_after.remove(new_same[0])
for old_key, new_key in moved:
if before[old_key] != after[new_key]:
changed.append((old_key, before[old_key], after[new_key]))
else:
print(f"MOVED {old_key[0]} :: {old_key[1]} -> {new_key[1]} ({after[new_key]})")
for key, was, now in changed:
print(f"CHANGED {key[0]} :: {key[1]}: {was} -> {now}")
for key in only_before: