diff --git a/architecture-baseline.json b/architecture-baseline.json index f0ff2496..4339002b 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -20,21 +20,6 @@ "crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs": 415, "crates/cuda-driver/src/sm86_table.rs": 934, "crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs": 455, - "crates/deploy/src/app.rs": 1490, - "crates/deploy/src/bin/fake_runtime.rs": 426, - "crates/deploy/src/cli/tests.rs": 407, - "crates/deploy/src/config.rs": 793, - "crates/deploy/src/expert_profile/tests.rs": 484, - "crates/deploy/src/facts.rs": 430, - "crates/deploy/src/plan.rs": 1483, - "crates/deploy/src/preflight/evaluate_fn.rs": 670, - "crates/deploy/src/preflight/tests.rs": 475, - "crates/deploy/src/profile.rs": 1035, - "crates/deploy/src/reconfigure/tests.rs": 599, - "crates/deploy/src/resources.rs": 964, - "crates/deploy/src/sealed.rs": 592, - "crates/deploy/src/supervisor.rs": 1863, - "crates/deploy/tests/e2e.rs": 2118, "crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs": 472, "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 993, "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 484, diff --git a/crates/deploy/Cargo.toml b/crates/deploy/Cargo.toml index d09f466e..fa3d25d9 100644 --- a/crates/deploy/Cargo.toml +++ b/crates/deploy/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" # Test double for the runtime programs; built only for the integration tests (`--features test-fakes`). [[bin]] name = "leleka-fake-runtime" -path = "src/bin/fake_runtime.rs" +path = "src/bin/fake_runtime/main.rs" required-features = ["test-fakes"] [features] diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 33446735..affd8177 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -10,695 +10,6 @@ use crate::{ use serde_json::{Value, json}; use std::path::PathBuf; -pub fn env_var(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) -} - -/// What `leleka version` prints: the first line stays `leleka VERSION` (scripts parse it); the rest is the build identity embedded by -/// `build.rs` (docs/release/5090-v0.1-checklist.md, section 3). -pub fn version_text() -> String { - format!( - "leleka {} -commit {} ({}) -strata pin {} (upstream commit of docs/upstream.md at build time) -built for {}, {} profile", - env!("CARGO_PKG_VERSION"), - env!("LELEKA_BUILD_COMMIT"), - env!("LELEKA_BUILD_TREE"), - env!("LELEKA_BUILD_STRATA_PIN"), - env!("LELEKA_BUILD_TARGET"), - env!("LELEKA_BUILD_PROFILE"), - ) -} - -fn is_root() -> bool { - #[cfg(target_os = "linux")] - { - rustix::process::geteuid().is_root() - } - #[cfg(not(target_os = "linux"))] - { - false - } -} - -/// The command line of `leleka`. On Windows the WSL2 route (`winfront`) takes the deployment commands first. -pub async fn main_with(args: Vec) -> i32 { - #[cfg(windows)] - if let Some(code) = crate::winfront::dispatch(&args).await { - return code; - } - main_native(args).await -} - -fn home_dir() -> Option { - #[cfg(windows)] - { - std::env::var_os("USERPROFILE").map(PathBuf::from) - } - #[cfg(not(windows))] - { - std::env::var_os("HOME").map(PathBuf::from) - } -} - -/// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`). -pub async fn main_native(mut args: Vec) -> i32 { - // `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it). - if let Some(index) = args.iter().position(|a| a == "--hidden") { - args.remove(index); - crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed); - #[cfg(windows)] - crate::winsys::hide_console(); - } - let var = env_var; - let environment = Environment { - root: is_root(), - home: home_dir(), - var: &var, - }; - let command = match parse(&args, &environment) { - Ok(command) => command, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } - }; - match command { - Command::Help => { - print!("{USAGE}"); - 0 - } - Command::Version => { - println!("{}", version_text()); - 0 - } - Command::Profiles(None) => { - for (name, _) in BUILTIN { - let profile = Profile::builtin(name).expect("built-in"); - println!("{name}\n {}", profile.description); - } - 0 - } - Command::Profiles(Some(name)) => match Profile::builtin(&name) { - Some(profile) => { - print!("{}", crate::config::to_file_text(&profile)); - 0 - } - None => { - eprintln!("leleka: unknown profile {name:?}"); - 2 - } - }, - Command::Preflight(opts) => preflight(opts).await, - Command::Up(opts) => up(opts).await, - Command::Status(opts) => status(opts).await, - Command::Down(opts) => down(opts).await, - Command::Reconfigure(opts, args) => reconfigure(opts, args).await, - Command::Verify(opts) => verify(opts).await, - Command::Logs(opts, args) => crate::logview::run_logs(&opts, &args), - Command::Report(opts, args) => crate::logview::run_report(&opts, &args), - Command::Service(action, opts) => crate::winservice::run_native(action, opts).await, - Command::Run { config, kar_fd } => { - supervisor::run(supervisor::Options { config, kar_fd }).await - } - Command::SealProbe(file) => seal_probe(&file), - Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { - Ok(never) => match never {}, - Err(message) => { - eprintln!("leleka exec-inherit: {message}"); - 2 - } - }, - Command::SealExec(rest) => match crate::sealed::seal_exec(&rest) { - Ok(never) => match never {}, - Err(message) => { - eprintln!("leleka seal-exec: {message}"); - 2 - } - }, - } -} - -/// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the file. -#[cfg(unix)] -fn seal_probe(file: &std::path::Path) -> i32 { - use sha2::{Digest, Sha256}; - use std::os::unix::fs::FileExt; - let started = std::time::Instant::now(); - let (memfd, _identity, report) = - match crate::sealed::seal_file_report(file, None, &mut |done, total| { - eprintln!( - "sealing: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - ); - }) { - Ok(done) => done, - Err(message) => { - eprintln!("leleka seal-probe: {message}"); - return 1; - } - }; - let sealed_s = started.elapsed().as_secs_f64(); - let length = memfd.metadata().map_or(0, |m| m.len()); - let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new()); - let source = match std::fs::File::open(file) { - Ok(f) => f, - Err(error) => { - eprintln!("leleka seal-probe: {error}"); - return 1; - } - }; - let mut block = vec![0u8; 8 << 20]; - let mut other = vec![0u8; 8 << 20]; - let mut offset = 0u64; - while offset < length { - let n = (length - offset).min(block.len() as u64) as usize; - if memfd.read_exact_at(&mut block[..n], offset).is_err() - || source.read_exact_at(&mut other[..n], offset).is_err() - { - eprintln!("leleka seal-probe: read failed at {offset}"); - return 1; - } - from_memfd.update(&block[..n]); - from_file.update(&other[..n]); - offset += n as u64; - } - let (a, b) = ( - hex::encode(from_memfd.finalize()), - hex::encode(from_file.finalize()), - ); - println!( - "seal-probe {} bytes {} read={} sealed in {:.1} s ({:.0} MB/s) sha256(memfd)={} sha256(file)={} {}", - file.display(), - length, - report.strategy.as_str(), - sealed_s, - length as f64 / sealed_s.max(1e-9) / 1e6, - a, - b, - if a == b { "IDENTICAL" } else { "DIFFERENT" } - ); - i32::from(a != b) -} - -#[cfg(not(unix))] -fn seal_probe(_file: &std::path::Path) -> i32 { - eprintln!("leleka seal-probe needs Linux"); - 2 -} - -fn print_report(report: &Report) { - eprint!("{}", report.render()); -} - -fn json_plan(ctx: &Context, steps: &[Step]) -> Value { - json!({ - "mode": ctx.mode, - "profile": ctx.config.as_ref().map(|c| c.profile.name.clone()), - "preflight": ctx.report, - "steps": steps, - "engine_command": ctx.config.as_ref().map(|c| { - let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()]; - args.extend(c.engine_args(c.kar_arg())); - args - }), - }) -} - -async fn preflight(opts: UpOptions) -> i32 { - let ctx = gather(&opts, &env_var); - match (&ctx.profile, &ctx.report) { - (Err(message), _) => { - eprintln!("leleka: {message}"); - 1 - } - (Ok(_), Some(report)) => { - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(report).expect("serializable") - ); - } else { - print_report(report); - } - i32::from(report.failed()) - } - _ => 1, - } -} - -pub async fn up(opts: UpOptions) -> i32 { - let ctx = gather(&opts, &env_var); - if let Err(message) = &ctx.profile { - eprintln!("leleka: {message}"); - return 1; - } - let report = ctx - .report - .as_ref() - .expect("report exists when the profile does"); - print_report(report); - if let Some(resources) = &ctx.needs.resources { - eprint!("{}", resources.render(&ctx.facts)); - } - let fs = gather_fs(&ctx).await; - let steps = plan_steps(&ctx, &fs); - let blocked = steps - .iter() - .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight"); - if opts.dry_run { - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable") - ); - } else { - print!("{}", render_plan(&ctx, &steps)); - println!( - "mode: {}; nothing was changed (--dry-run)", - ctx.mode.label() - ); - } - return i32::from(report.failed() || blocked); - } - if report.failed() { - eprintln!( - "leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command." - ); - return 1; - } - eprint!("{}", render_plan(&ctx, &steps)); - match run_up(&ctx, &steps).await { - Ok(code) => code, - Err(message) => { - eprintln!("leleka: {message}"); - eprintln!( - "leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)." - ); - 1 - } - } -} - -pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { - let changes = steps::prepare(ctx, steps).await?; - let config = steps::config_of(ctx)?; - match ctx.mode { - Mode::None => { - say(&format!( - "prepared. Start it with: {} run --config {}", - ctx.paths.bin("leleka").display(), - ctx.paths.run_config().display() - )); - Ok(0) - } - Mode::Systemd(scope) => { - #[cfg(unix)] - if scope == UnitScopeTag::System { - steps::ensure_service_user(ctx).await?; - steps::hand_over_to_service_user(ctx)?; - } - let changed = steps::install_unit(ctx, scope).await?; - steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?; - steps::wait_ready(ctx, Some(scope)).await?; - summary(ctx, config); - Ok(0) - } - Mode::Foreground => { - if let Some(fd) = ctx.opts.kar_fd { - if config.profile.kar_source == crate::profile::KarSource::None { - return Err(format!( - "--kar-fd {fd} was given but profile {} has kar_source none (no archive is used); drop --kar-fd", - config.profile.name - )); - } - crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?; - } - if steps::probe_ready(ctx).await { - say("a supervisor for this state directory is already ready"); - summary(ctx, config); - return Ok(0); - } - if crate::plan::service_running(&ctx.paths) { - return Err(format!( - "another supervisor is running for {} (not ready yet); wait for it or stop it first", - ctx.opts.dirs.state.display() - )); - } - let options = supervisor::Options { - config: ctx.paths.run_config(), - kar_fd: ctx.opts.kar_fd, - }; - let run = supervisor::run(options); - tokio::pin!(run); - let mut printed = false; - loop { - tokio::select! { - code = &mut run => return Ok(code), - ready = steps::wait_ready(ctx, None), if !printed => { - printed = true; - match ready { - Ok(()) => summary(ctx, config), - Err(message) => say(&message), - } - } - } - } - } - } -} - -pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { - let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); - json!({ - "ready": true, - "endpoint": format!("http://{}", ctx.opts.ports.api), - "model": config.model_id, - "model_digest": config.model_digest, - "api_key_file": ctx.paths.api_key().display().to_string(), - "gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})), - "profile": config.profile.name, - "gpu_budget_bytes": config.profile.gpu_budget_bytes, - "context_tokens": config.profile.context_tokens, - "kar_source": config.profile.kar_source.as_str(), - "ram_total_bytes": ctx.facts.memory.total, - "ram_available_at_start_bytes": ctx.facts.memory.available, - "service": ctx.mode.label(), - "expert_tier": crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets), - "logs": ctx.paths.logs().display().to_string(), - "state": ctx.opts.dirs.state.display().to_string(), - "assets": ctx.opts.dirs.assets.display().to_string(), - }) -} - -pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { - let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); - if ctx.opts.json { - println!( - "{}", - serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable") - ); - return; - } - let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); - let key_file = ctx.paths.api_key().display().to_string(); - let mut text = String::from("\nLeleka is ready.\n"); - text.push_str(&format!( - " endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n", - ctx.opts.ports.api - )); - text.push_str(&format!( - " model {} {}\n", - config.model_id, config.model_digest - )); - text.push_str(&format!( - " api key in {key_file} (send it as `Authorization: Bearer ...`)\n" - )); - if let Some(gpu) = gpu { - text.push_str(&format!( - " gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n", - gpu.name, - gpu.index, - gpu.sm.map_or("?".into(), |s| s.to_string()), - gpu.vram_total_mib, - gpu.driver - )); - } - text.push_str(&format!( - " profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n", - config.profile.name, - gib(config.profile.gpu_budget_bytes), - config.profile.context_tokens, - match config.profile.kar_source { - crate::profile::KarSource::Memfd => format!( - "a sealed memfd ({} of RAM held for the life of the service{})", - gib(config.profile.memfd_bytes()), - if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly { - "; sparse copy: only the byte ranges the serve path reads, holes elsewhere" - } else { - "" - } - ), - crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), - crate::profile::KarSource::None => - "none (EXPERIMENTAL: no archive; the PLE rows are read from the GGUF shard, qwen4exp-native-mtp-v1)".to_owned(), - } - )); - text.push_str(&format!( - " host RAM {} total, {} available before start\n", - gib(ctx.facts.memory.total), - gib(ctx.facts.memory.available) - )); - text.push_str(&format!( - " expert {}\n", - crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets).line() - )); - text.push_str(&format!(" service {}\n", ctx.mode.label())); - if ctx.mode == Mode::Systemd(UnitScopeTag::User) { - text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot -"); - } - text.push_str(&format!( - " logs {} (leleka.log, engine.log, gateway.log, api.log)\n", - ctx.paths.logs().display() - )); - if ctx.facts.os == "windows" { - text.push_str(&format!( - " try {} -", - powershell_try(&key_file, &ctx.opts.ports.api, &config.model_id) - )); - eprintln!("{text}"); - return; - } - text.push_str(&format!( - " try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n", - config.model_id, ctx.opts.ports.api - )); - eprintln!("{text}"); -} - -/// A PowerShell one-liner that sends one request to the API (the key file may be a UNC path into WSL). -pub fn powershell_try(key_file: &str, api: &str, model: &str) -> String { - format!( - "$k=(Get-Content -Raw '{key_file}').Trim(); Invoke-RestMethod -Method Post -Uri http://{api}/v1/responses -Headers @{{Authorization=\"Bearer $k\"}} -ContentType 'application/json' -Body '{{\"model\":\"{model}\",\"input\":\"hello\",\"max_output_tokens\":32}}'" - ) -} - -/// Which systemd unit of this deployment exists (system first), judged by the unit file. -fn installed_scope(paths: &crate::layout::Paths) -> Option { - let home = std::env::var_os("HOME").map(PathBuf::from); - [UnitScopeTag::System, UnitScopeTag::User] - .into_iter() - .find(|scope| { - crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name()) - .is_ok_and(|path| path.is_file()) - }) -} - -/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing. -async fn status(opts: UpOptions) -> i32 { - let paths = opts.dirs.paths(); - let api = crate::config::RunConfig::read(&paths.run_config()) - .map(|config| config.ports.api) - .unwrap_or_else(|_| opts.ports.api.clone()); - let status: Option = std::fs::read_to_string(paths.status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()); - let ready = steps::probe_ready_at(&paths, &api).await; - let expert_tier = crate::config::RunConfig::read(&paths.run_config()) - .ok() - .map(|config| crate::expert_profile::tier_report(&config, &config.dirs().assets)); - let gateway = if ready { - steps::fetch_status(&paths, &api).await - } else { - None - }; - let unit = match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - command.args(["is-active", paths.unit_name()]); - command - .output() - .await - .ok() - .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) - } - None => None, - }; - let requests = crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()); - print_status( - opts.json, - ready, - unit.map(|state| (paths.unit_name().to_owned(), state)), - status, - gateway.as_ref(), - expert_tier.as_ref(), - &paths.run_dir().display().to_string(), - requests.as_deref(), - ) -} - -/// The `leleka status` output from the pieces gathered on this host or through the WSL bridge. Exit code 1 when not ready. -#[allow(clippy::too_many_arguments)] -pub fn print_status( - json: bool, - ready: bool, - unit: Option<(String, String)>, - supervisor: Option, - gateway: Option<&Value>, - expert_tier: Option<&crate::expert_profile::TierReport>, - run_dir: &str, - requests: Option<&str>, -) -> i32 { - let machine = gateway - .map(|g| g["machine"].clone()) - .filter(Value::is_object); - if json { - println!( - "{}", - serde_json::to_string_pretty( - &json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), "supervisor": supervisor, "machine": machine, - "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), "expert_tier": expert_tier, "requests": requests}) - ) - .expect("serializable") - ); - } else { - println!("ready: {ready}"); - if let Some((name, state)) = unit { - println!("systemd unit {name}: {state}"); - } - match supervisor { - Some(s) => print!("{}", render_supervisor(&s, unix_now())), - None => println!("supervisor: no status file in {run_dir} (never started?)"), - } - if let Some(tier) = expert_tier { - println!("{}", tier.line()); - } - if let Some(line) = requests { - println!("{line}"); - } - if let Some(machine) = &machine { - print!("{}", render_machine(machine)); - } else if ready { - println!("engine load: the engine reports no telemetry yet"); - } - } - i32::from(!ready) -} - -fn unix_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs()) -} - -/// `3 min`, `2 h 05 min`, `4 days 3 h`: how long ago, for people. -pub fn age_text(seconds: u64) -> String { - duration_text(seconds) -} - -fn duration_text(seconds: u64) -> String { - match seconds { - s if s < 120 => format!("{s} s"), - s if s < 7200 => format!("{} min", s / 60), - s if s < 172_800 => format!("{} h {:02} min", s / 3600, s % 3600 / 60), - s => format!("{} days {} h", s / 86_400, s % 86_400 / 3600), - } -} - -/// The supervisor part of `leleka status`: what it does, for how long, what it restarted and why, whether it is alive. -pub fn render_supervisor(s: &Value, now: u64) -> String { - let updated = s["updated_unix"].as_u64().unwrap_or(0); - let age = now.saturating_sub(updated); - let mut out = format!( - "supervisor: phase {} (pid {}), updated {} ({} ago)\n {}\n", - s["phase"].as_str().unwrap_or("?"), - s["supervisor_pid"], - supervisor::format_utc(updated), - duration_text(age), - s["message"].as_str().unwrap_or("") - ); - // The supervisor rewrites its status at least every 30 s while it lives. - let live = !matches!(s["phase"].as_str(), Some("stopped" | "failed")); - if live && age > 120 { - out.push_str(&format!( - " WARNING: the status is {} old although the phase is {}: the supervisor is not running (crashed or killed)\n", - duration_text(age), - s["phase"].as_str().unwrap_or("?") - )); - } - if let Some(started) = s["started_unix"].as_u64() { - out.push_str(&format!( - " up {}", - duration_text(now.saturating_sub(started)) - )); - out.push_str(&format!( - ", engine restarts {} in total ({} in a row)", - s["restarts_total"].as_u64().unwrap_or(0), - s["engine_restarts"].as_u64().unwrap_or(0) - )); - if let (Some(at), Some(why)) = ( - s["last_restart_unix"].as_u64(), - s["last_restart_reason"].as_str(), - ) { - out.push_str(&format!( - "\n last restart {} ago: {why}", - duration_text(now.saturating_sub(at)) - )); - } - out.push('\n'); - } else { - out.push_str(&format!(" engine restarts {}\n", s["engine_restarts"])); - } - if let Some(health) = s["health"].as_str() { - out.push_str(&format!( - " health: {health}; logs {} MiB\n", - s["log_bytes"].as_u64().unwrap_or(0) >> 20 - )); - } - out -} - -/// `leleka reconfigure`. -/// -/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A -/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process. -/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise). -async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 { - let paths = opts.dirs.paths(); - let supervised = crate::plan::service_running(&paths); - if args.needs_restart() { - return reconfigure_by_restart(&opts, &args, supervised).await; - } - let settings = serde_json::Value::Object(args.settings.clone()).to_string(); - let api = crate::config::RunConfig::read(&paths.run_config()) - .map(|config| config.ports.api) - .unwrap_or_else(|_| opts.ports.api.clone()); - let Ok(key) = std::fs::read_to_string(paths.api_key()) else { - eprintln!( - "leleka: no API key in {} (is the service prepared?)", - paths.api_key().display() - ); - return 1; - }; - let Some(address) = crate::config::probe_address(&api) else { - eprintln!("leleka: cannot reach the API address {api}"); - return 1; - }; - let persist = args.persist.then_some(PersistTarget { - paths: &paths, - settings: &args.settings, - supervised, - }); - send_reconfigure(address, key.trim_end(), &settings, opts.json, persist).await -} - /// Where `--persist` writes after a successful runtime change. pub struct PersistTarget<'a> { pub paths: &'a crate::layout::Paths, @@ -707,784 +18,92 @@ pub struct PersistTarget<'a> { pub supervised: bool, } -/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge. -pub async fn send_reconfigure( - address: std::net::SocketAddr, - key: &str, - settings: &str, - json: bool, - persist: Option>, -) -> i32 { - eprintln!( - "leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)" - ); - let response = crate::http::post_json( - address, - "/v1/reconfigure", - Some(key), - settings, - std::time::Duration::from_secs(1900), - ) - .await; - match response { - Ok(response) => { - let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null); - let mut persisted = None; - if response.status == 200 - && let Some(target) = &persist - { - persisted = - Some(persist_settings(target.paths, target.settings, target.supervised).await); - } - if json { - let mut shown = document.clone(); - if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) { - object.insert("persisted".into(), json!(result.is_ok())); - } - println!( - "{}", - serde_json::to_string_pretty(&shown).unwrap_or(response.body) - ); - } else if response.status == 200 { - println!("reconfigured; the engine runs with:"); - print!("{}", render_settings(&document["settings"])); - match &persisted { - Some(Ok(note)) => println!("persisted: {note}"), - Some(Err(why)) => eprintln!( - "leleka: the engine runs with the new settings, but they were not persisted: {why}" - ), - None => {} - } - } else { - let message = document["error"]["message"] - .as_str() - .unwrap_or(&response.body); - eprintln!( - "leleka: the change was refused (HTTP {}): {message}", - response.status - ); - } - i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err())) - } - Err(message) => { - eprintln!("leleka: {message}"); - 1 - } - } -} +#[cfg(test)] +mod version_tests; -/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine -/// keeps it) and writes the file; with no supervisor the file is edited directly. -async fn persist_settings( - paths: &crate::layout::Paths, - settings: &serde_json::Map, - supervised: bool, -) -> Result { - if !supervised { - let changed = crate::reconfigure::persist_offline(paths, settings)?; - return Ok(format!( - "leleka.json updated ({} changed; no supervisor was running)", - changed.len() - )); - } - let request = crate::reconfigure::Request { - id: crate::reconfigure::new_request_id(), - settings: settings.clone(), - persist: true, - ..Default::default() - }; - let outcome = - ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?; - if outcome.state == crate::reconfigure::State::Done && outcome.persisted { - Ok(outcome.message) - } else { - Err(outcome.message) - } -} +#[cfg(test)] +mod machine_tests; -/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end). -async fn ask_supervisor( - paths: &crate::layout::Paths, - request: &crate::reconfigure::Request, - limit: std::time::Duration, - show_progress: bool, -) -> Result { - use crate::reconfigure::{State, read_outcome, write_request}; - write_request(paths, request)?; - let started = std::time::Instant::now(); - let mut last = String::new(); - loop { - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - match read_outcome(paths, &request.id) { - Some(outcome) if outcome.state != State::Running => return Ok(outcome), - Some(outcome) if show_progress && outcome.message != last => { - eprintln!("leleka: {}", outcome.message); - last = outcome.message; - } - _ => {} - } - if !crate::plan::service_running(paths) { - return Err("the supervisor stopped before it answered; see the service log".into()); - } - if started.elapsed() > limit { - let _ = std::fs::remove_file(paths.reconfigure_request()); - return Err(format!( - "the supervisor did not answer within {} s", - limit.as_secs() - )); - } - } -} +#[cfg(test)] +mod status_tests; -/// A budget or preset change: the supervisor restarts the engine process with the new numbers. -async fn reconfigure_by_restart(opts: &UpOptions, args: &ReconfigureArgs, supervised: bool) -> i32 { - let paths = opts.dirs.paths(); - if !supervised { - eprintln!( - "leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`", - paths.dirs.state.display() - ); - return 1; - } - let load_timeout = crate::config::RunConfig::read(&paths.run_config()) - .map_or(1800, |config| config.load_timeout_s); - let request = crate::reconfigure::Request { - id: crate::reconfigure::new_request_id(), - gpu_budget_gib: args.gpu_budget_gib, - preset: args.preset, - settings: args.settings.clone(), - persist: args.persist, - }; - eprintln!( - "leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)" - ); - // two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks - let limit = std::time::Duration::from_secs(2 * load_timeout + 300); - let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await { - Ok(outcome) => outcome, - Err(why) => { - eprintln!("leleka: {why}"); - return 1; - } - }; - let done = outcome.state == crate::reconfigure::State::Done; - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(&outcome).unwrap_or_default() - ); - } else if done { - println!("reconfigured: {}", outcome.message); - if let Some(effective) = &outcome.effective { - print!("{}", render_effective(effective)); - } - } else { - eprintln!("leleka: the change was not made: {}", outcome.message); - } - i32::from(!done) -} - -/// The numbers in force after a restart-in-place, one line each. -pub fn render_effective(effective: &Value) -> String { - let Some(object) = effective.as_object() else { - return String::new(); - }; - let mut out = String::new(); - for (key, value) in object { - if !value.is_null() { - out.push_str(&format!(" {key:20} {value}\n")); - } - } - out -} - -/// The settings block of the engine, one line per member. -pub fn render_settings(settings: &Value) -> String { - let Some(object) = settings.as_object() else { - return String::new(); - }; - let mut out = String::new(); - for (key, value) in object { - if key == "prefix_cache" && value.is_object() { - out.push_str(&format!( - " prefix cache {} MiB requested {}, tail {}, block {} tokens, kept {} min\n", - value["budget_mib"] - .as_u64() - .map_or("?".to_owned(), |m| m.to_string()), - value["requested"], - value["tail"].as_str().unwrap_or("?"), - value["block_tokens"], - value["retention_min"] - )); - } else if key == "prefix_cache" { - out.push_str(" prefix cache off\n"); - } else { - out.push_str(&format!(" {key:13} {value}\n")); - } - } - out -} - -/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context. -pub fn render_machine(machine: &Value) -> String { - let gib = |mib: &Value| { - mib.as_f64() - .map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0)) - }; - let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}")); - let pct = |value: &Value| { - value - .as_f64() - .map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0)) - }; - let mut out = format!( - "engine load ({}):\n", - machine["phase"].as_str().unwrap_or("?") - ); - let gpu = &machine["gpu"]; - if gpu.is_object() { - out.push_str(&format!( - " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n", - gpu["util_pct"], - gpu["mem_util_pct"], - gib(&gpu["vram_used_mib"]), - gib(&gpu["vram_total_mib"]), - gpu["power_w"] - .as_f64() - .map_or(String::new(), |w| format!(", {w:.0} W")), - gpu["sm_clock_mhz"] - .as_u64() - .map_or(String::new(), |m| format!(", {m} MHz")), - gpu["temp_c"] - .as_u64() - .map_or(String::new(), |t| format!(", {t} C")), - )); - } - let cpu = &machine["cpu"]; - if cpu.is_object() { - out.push_str(&format!( - " cpu {} of {} cores busy in the engine (whole system {}%)\n", - cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"] - )); - } - let ram = &machine["ram"]; - if ram.is_object() { - out.push_str(&format!( - " ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n", - gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"]) - )); - } - let rates = &machine["throughput"]; - out.push_str(&format!( - " prefill {} tok/s last, {} average, {} lifetime\n", - num(&rates["prefill_tok_s_last"]), - num(&rates["prefill_tok_s_avg"]), - num(&rates["prefill_tok_s_lifetime"]) - )); - out.push_str(&format!( - " decode {} tok/s last, {} average, {} lifetime{}\n", - num(&rates["decode_tok_s_last"]), - num(&rates["decode_tok_s_avg"]), - num(&rates["decode_tok_s_lifetime"]), - rates["decode_tok_s_live"] - .as_f64() - .map_or(String::new(), |v| format!(", {v:.0} now")) - )); - let cache = &machine["cache"]; - out.push_str(&format!( - " cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n", - pct(&cache["hit_ratio"]), - pct(&cache["token_hit_ratio"]), - cache["last_reused_tokens"], - cache["last_prompt_tokens"] - )); - let context = &machine["context"]; - out.push_str(&format!( - " context {} of {} tokens{}\n", - context["live_tokens"], - context["max_tokens"], - context["used_pct"] - .as_f64() - .map_or(String::new(), |p| format!(" ({p:.1}%)")) - )); - if machine["settings"].is_object() { - out.push_str("settings in force:\n"); - out.push_str(&render_settings(&machine["settings"])); - } - out -} - -/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the -/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. -/// `leleka verify --quick`: the health of the installation without reading the model. Reports, from what is on disk and what the -/// service says: whether each model file is stamped as verified in its present state (a stamped file is not hashed again at a start), -/// whether the service runs and answers, how old and how restarted it is, and how big the logs are. Exit 0 only when all is well. -async fn verify_quick(opts: &UpOptions) -> i32 { - use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; - let paths = opts.dirs.paths(); - let config = match crate::config::RunConfig::read(&paths.run_config()) { - Ok(config) => config, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } - }; - let stamps = VerifyStamps::new(paths.engine_stamps(), false); - let mut problems: Vec = Vec::new(); - let mut notes: Vec = Vec::new(); - let decode = |hex_text: &str| { - let mut out = [0u8; 32]; - hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out) - }; - let identity_of = |path: &std::path::Path| { - std::fs::File::open(path) - .and_then(|f| f.metadata()) - .ok() - .and_then(|m| FileIdentity::of(&m)) - }; - println!( - "model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):" - ); - for index in 0..2 { - let path = paths.shard(index); - let state = match ( - decode(crate::profile::SHARD_SHA256_HEX[index]), - identity_of(&path), - ) { - (_, None) => { - problems.push(format!("shard {index} is missing: {}", path.display())); - "MISSING" - } - (Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => { - "stamped (verified in its present state)" - } - _ => { - notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp")); - "not stamped" - } - }; - println!(" shard {index}: {state} {}", path.display()); - } - let kar = paths.kar(); - let kar_state = match identity_of(&kar) { - _ if config.profile.kar_source == crate::profile::KarSource::None => "not used (kar_source none)".to_owned(), - None => { - problems.push(format!("the archive is missing: {}", kar.display())); - "MISSING".to_owned() - } - Some(id) if id.size != crate::profile::ARCHIVE_BYTES => { - problems.push(format!( - "the archive has {} bytes, the pinned archive {}", - id.size, - crate::profile::ARCHIVE_BYTES - )); - "WRONG SIZE".to_owned() - } - Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => { - "stamped (verified in its present state)".to_owned() - } - Some(_) => { - notes.push("the archive is not stamped: the next start of the engine hashes the sealed copy (about a minute)".into()); - "not stamped".to_owned() - } - }; - println!(" archive: {kar_state} {}", kar.display()); - let api = config.ports.api.clone(); - let supervisor: Option = std::fs::read_to_string(paths.status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()); - let ready = steps::probe_ready_at(&paths, &api).await; - println!("service:"); - match &supervisor { - Some(s) => print!( - " {}", - render_supervisor(s, unix_now()) - .replace('\n', "\n ") - .trim_end_matches(' ') - ), - None => println!( - " no status file in {} (the service has not run)", - paths.run_dir().display() - ), - } - println!(" API answers /ready: {}", if ready { "yes" } else { "NO" }); - if !ready { - problems.push("the API does not answer /ready".into()); - } - if let Some(s) = &supervisor { - let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0)); - if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) { - problems.push(format!( - "the supervisor's status is {age} s old: it is not running" - )); - } - if s["phase"].as_str() == Some("failed") { - problems.push(format!( - "the supervisor failed: {}", - s["message"].as_str().unwrap_or("") - )); - } - } - let log_bytes = crate::logs::total_bytes(&paths.logs()); - println!( - " logs: {} MiB in {} (rotated at {} MiB per file, {} generations)", - log_bytes >> 20, - paths.logs().display(), - config.logs.limit_mib, - config.logs.keep - ); - match crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()) { - Some(line) => println!(" {line}"), - None => println!( - " requests: no request record yet in {} (`leleka logs --source requests`)", - paths.logs().join("requests.log").display() - ), - } - let recent = crate::logview::recent_requests(&paths.logs(), 200); - let failed = recent - .iter() - .filter(|r| matches!(r["fin"].as_str(), Some("error" | "rejected"))) - .count(); - if recent.len() >= 10 && failed * 5 > recent.len() { - notes.push(format!("{failed} of the last {} requests failed or were rejected: see `leleka logs --level warn --since 1h`", recent.len())); - } - for note in ¬es { - println!("note: {note}"); - } - if problems.is_empty() { - println!("health: OK"); - 0 - } else { - for problem in &problems { - println!("PROBLEM: {problem}"); - } - println!("health: NOT OK"); - 1 - } -} - -async fn verify(opts: UpOptions) -> i32 { - use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; - if opts.quick { - return verify_quick(&opts).await; - } - use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; - let paths = opts.dirs.paths(); - let config = match crate::config::RunConfig::read(&paths.run_config()) { - Ok(config) => config, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } - }; - let stamp_dir = paths.engine_stamps(); - if let Err(error) = std::fs::create_dir_all(&stamp_dir) { - eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); - return 1; - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); - } - let env = std::fs::read_to_string(paths.env_file()) - .map(|text| parse_env_file(&text)) - .unwrap_or_default(); - let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else { - eprintln!( - "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", - paths.env_file().display() - ); - return 2; - }; - // The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown. - let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets); - say(&tier.line()); - let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some(); - let started = std::time::Instant::now(); - say( - "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", - ); - let engine = tokio::process::Command::new(paths.bin("leleka-inference")) - .args(config.verify_args(true)) - .env(RUNTIME_TOKEN_ENV, token) - .env_remove("HF_TOKEN") - .stdin(std::process::Stdio::null()) - .status(); - // A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is - // hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). - let archive = tokio::task::spawn_blocking({ - let kar = paths.kar(); - let memfd = config.profile.kar_source == KarSource::Memfd; - let stamps = VerifyStamps::new(stamp_dir.clone(), true); - move || -> Result, String> { - if !memfd { - return Ok(None); - } - let begun = std::time::Instant::now(); - let file = std::fs::File::open(&kar) - .map_err(|e| format!("cannot open {}: {e}", kar.display()))?; - let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - let digest = - sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; - if digest != crate::profile::archive_sha256() { - return Err(format!( - "{} does not match the pinned archive digest", - kar.display() - )); - } - let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - if let (Some(before), true) = (before, before == after) { - stamps - .record("kar-source", &crate::profile::archive_sha256(), &before) - .map_err(|e| format!("cannot record the archive stamp: {e}"))?; - } - Ok(Some(begun.elapsed().as_secs_f64())) - } - }); - let (engine, archive) = tokio::join!(engine, archive); - let mut code = 0; - match engine { - Ok(status) if status.success() => {} - Ok(status) => { - eprintln!( - "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" - ); - code = 1; - } - Err(error) => { - eprintln!( - "leleka: cannot run {}: {error}", - paths.bin("leleka-inference").display() - ); - code = 1; - } - } - match archive { - Ok(Ok(Some(seconds))) => say(&format!( - "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" - )), - Ok(Ok(None)) => {} - Ok(Err(message)) => { - eprintln!("leleka: {message}"); - code = 1; - } - Err(error) => { - eprintln!("leleka: archive verification failed to run: {error}"); - code = 1; - } - } - if tier_failed { - eprintln!( - "leleka: the expert profile is missing or does not match its pinned digest; rerun `leleka up` (or pass --no-expert-tier to accept the slower decode)" - ); - code = 1; - } - say(&format!( - "verification {} in {:.1}s", - if code == 0 { "passed" } else { "FAILED" }, - started.elapsed().as_secs_f32() - )); - code -} - -async fn down(opts: UpOptions) -> i32 { - let paths = opts.dirs.paths(); - match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - match command.args(["stop", paths.unit_name()]).status().await { - Ok(status) if status.success() => { - eprintln!("leleka: stopped {}", paths.unit_name()); - 0 - } - Ok(status) => { - eprintln!("leleka: systemctl stop failed ({status})"); - 1 - } - Err(error) => { - eprintln!("leleka: cannot run systemctl: {error}"); - 1 - } - } - } - None => { - #[cfg(windows)] - { - return stop_foreground(&paths).await; - } - #[cfg(not(windows))] - { - eprintln!( - "leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)" - ); - 0 - } - } - } -} - -/// Windows: a supervisor in another console cannot be sent Ctrl-C, so it watches for a stop file in its run directory. +mod entry; +#[allow(unused_imports)] +pub use entry::env_var; +#[allow(unused_imports)] +use entry::home_dir; +#[allow(unused_imports)] +use entry::is_root; +#[allow(unused_imports)] +pub use entry::main_native; +#[allow(unused_imports)] +pub use entry::main_with; +#[allow(unused_imports)] +pub use entry::version_text; +mod preflight_report; +#[allow(unused_imports)] +use preflight_report::json_plan; +#[allow(unused_imports)] +use preflight_report::preflight; +#[allow(unused_imports)] +use preflight_report::print_report; +#[cfg(unix)] +#[allow(unused_imports)] +use preflight_report::seal_probe; +#[cfg(not(unix))] +#[allow(unused_imports)] +use preflight_report::seal_probe; +mod install_flow; +#[allow(unused_imports)] +pub use install_flow::powershell_try; +#[allow(unused_imports)] +pub use install_flow::run_up; +#[allow(unused_imports)] +pub use install_flow::summary; +#[allow(unused_imports)] +pub use install_flow::summary_json; +#[allow(unused_imports)] +pub use install_flow::up; +mod status_report; +#[allow(unused_imports)] +pub use status_report::age_text; +#[allow(unused_imports)] +use status_report::duration_text; +#[allow(unused_imports)] +use status_report::installed_scope; +#[allow(unused_imports)] +pub use status_report::print_status; +#[allow(unused_imports)] +pub use status_report::render_supervisor; +#[allow(unused_imports)] +use status_report::status; +#[allow(unused_imports)] +use status_report::unix_now; +mod settings_change; +#[allow(unused_imports)] +use settings_change::ask_supervisor; +#[allow(unused_imports)] +use settings_change::persist_settings; +#[allow(unused_imports)] +use settings_change::reconfigure; +#[allow(unused_imports)] +use settings_change::reconfigure_by_restart; +#[allow(unused_imports)] +pub use settings_change::render_effective; +#[allow(unused_imports)] +pub use settings_change::render_machine; +#[allow(unused_imports)] +pub use settings_change::render_settings; +#[allow(unused_imports)] +pub use settings_change::send_reconfigure; +mod verify_flow; +#[allow(unused_imports)] +use verify_flow::verify; +#[allow(unused_imports)] +use verify_flow::verify_quick; +mod stop_flow; +#[allow(unused_imports)] +use stop_flow::down; #[cfg(windows)] -pub async fn stop_foreground(paths: &crate::layout::Paths) -> i32 { - if !crate::plan::service_running(paths) { - eprintln!( - "leleka: no running supervisor for {} (Ctrl-C stops one that runs in a terminal)", - paths.dirs.state.display() - ); - return 0; - } - let request = paths.run_dir().join(supervisor::STOP_REQUEST_FILE); - if let Err(error) = std::fs::write( - &request, b"stop -", - ) { - eprintln!("leleka: cannot write {}: {error}", request.display()); - return 1; - } - eprintln!("leleka: stop requested: the API drains first, then the gateway and the engine"); - let started = std::time::Instant::now(); - while started.elapsed() < std::time::Duration::from_secs(120) { - tokio::time::sleep(std::time::Duration::from_secs(2)).await; - if !crate::plan::service_running(paths) { - eprintln!("leleka: stopped"); - return 0; - } - } - eprintln!("leleka: the supervisor is still draining after 120 s; check `leleka status`"); - 1 -} - -#[cfg(test)] -mod version_tests { - use super::version_text; - - #[test] - fn the_version_names_the_commit_and_the_strata_pin_and_keeps_the_first_line() { - let text = version_text(); - assert_eq!( - text.lines().next(), - Some(concat!("leleka ", env!("CARGO_PKG_VERSION"))) - ); - let pin = env!("LELEKA_BUILD_STRATA_PIN"); - // docs/upstream.md is in the repository this crate is built from; an exported tree without it reports `unknown`. - assert!( - pin == "unknown" || (pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit())), - "{pin}" - ); - assert!(text.contains(env!("LELEKA_BUILD_COMMIT")), "{text}"); - assert!(["clean", "dirty", "unknown"].contains(&env!("LELEKA_BUILD_TREE"))); - } -} - -#[cfg(test)] -mod machine_tests { - use super::render_machine; - use serde_json::json; - - #[test] - fn the_machine_view_names_every_figure_the_operator_asked_for() { - let text = render_machine(&json!({ - "phase": "decode", - "gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900}, - "cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0}, - "ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0}, - "throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0, - "decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2}, - "cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968}, - "context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65} - })); - for needle in [ - "engine load (decode)", - "91% busy", - "VRAM 29.3 of 31.8 GiB", - "480 W", - "7.4 of 32 cores", - "prefill 5050 tok/s", - "decode 131 tok/s", - "135 now", - "87% of requests", - "91% of prompt", - "179968 of 262144 tokens (68.7%)", - ] { - assert!( - text.contains(needle), - "{needle}\ -{text}" - ); - } - } - - #[test] - fn the_settings_block_lists_every_member_and_the_prefix_cache_on_one_line() { - let text = super::render_settings(&json!({ - "context_tokens": 65536, "prefill_capacity": 8192, "cpu_workers": 8, - "prefix_cache": {"budget_mib": 20480, "requested": 20480, "tail": "reply", "block_tokens": 8192, "retention_min": 60} - })); - for needle in [ - "context_tokens", - "65536", - "prefill_capacity", - "cpu_workers", - "prefix cache 20480 MiB requested 20480, tail reply, block 8192 tokens, kept 60 min", - ] { - assert!( - text.contains(needle), - "{needle} -{text}" - ); - } - assert!( - super::render_settings(&json!({"prefix_cache": null})).contains("prefix cache off") - ); - } - - #[test] - fn missing_blocks_are_left_out_not_invented() { - let text = render_machine( - &json!({"phase": "idle", "gpu": null, "cpu": null, "ram": null, - "throughput": {}, "cache": {}, "context": {"live_tokens": 0, "max_tokens": 8192}}), - ); - assert!( - !text.contains(" gpu ") && !text.contains(" cpu ") && !text.contains(" ram "), - "{text}" - ); - assert!(text.contains("prefill - tok/s")); - } -} - -#[cfg(test)] -mod status_tests { - use super::*; - use serde_json::json; - - #[test] - fn the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor() { - let s = json!({"phase": "ready", "supervisor_pid": 7, "updated_unix": 1_000_000, "started_unix": 900_000, "message": "ready", - "engine_restarts": 0, "restarts_total": 3, "last_restart_unix": 990_000, "last_restart_reason": "the engine process exited (signal: 9)", - "health": "healthy", "log_bytes": 5 * 1024 * 1024}); - let fresh = render_supervisor(&s, 1_000_010); - assert!( - fresh.contains("phase ready (pid 7)") && fresh.contains("up 27 h 46 min"), - "{fresh}" - ); - assert!( - fresh.contains("3 in total") - && fresh.contains("signal: 9") - && fresh.contains("health: healthy; logs 5 MiB"), - "{fresh}" - ); - assert!(!fresh.contains("WARNING"), "{fresh}"); - let stale = render_supervisor(&s, 1_000_000 + 3 * 3600); - assert!( - stale.contains("WARNING") && stale.contains("not running"), - "{stale}" - ); - // A supervisor that stopped cleanly is not "dead". - let stopped = json!({"phase": "stopped", "updated_unix": 1_000_000}); - assert!(!render_supervisor(&stopped, 2_000_000).contains("WARNING")); - } -} +#[allow(unused_imports)] +pub use stop_flow::stop_foreground; diff --git a/crates/deploy/src/app/entry.rs b/crates/deploy/src/app/entry.rs new file mode 100644 index 00000000..7d384575 --- /dev/null +++ b/crates/deploy/src/app/entry.rs @@ -0,0 +1,134 @@ +//! The process entry: environment, version text, root check and the command dispatch of `main`. + +#[allow(unused_imports)] +use super::*; + +pub fn env_var(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.is_empty()) +} + +/// What `leleka version` prints: the first line stays `leleka VERSION` (scripts parse it); the rest is the build identity embedded by +/// `build.rs` (docs/release/5090-v0.1-checklist.md, section 3). +pub fn version_text() -> String { + format!( + "leleka {} +commit {} ({}) +strata pin {} (upstream commit of docs/upstream.md at build time) +built for {}, {} profile", + env!("CARGO_PKG_VERSION"), + env!("LELEKA_BUILD_COMMIT"), + env!("LELEKA_BUILD_TREE"), + env!("LELEKA_BUILD_STRATA_PIN"), + env!("LELEKA_BUILD_TARGET"), + env!("LELEKA_BUILD_PROFILE"), + ) +} + +pub(super) fn is_root() -> bool { + #[cfg(target_os = "linux")] + { + rustix::process::geteuid().is_root() + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +/// The command line of `leleka`. On Windows the WSL2 route (`winfront`) takes the deployment commands first. +pub async fn main_with(args: Vec) -> i32 { + #[cfg(windows)] + if let Some(code) = crate::winfront::dispatch(&args).await { + return code; + } + main_native(args).await +} + +pub(super) fn home_dir() -> Option { + #[cfg(windows)] + { + std::env::var_os("USERPROFILE").map(PathBuf::from) + } + #[cfg(not(windows))] + { + std::env::var_os("HOME").map(PathBuf::from) + } +} + +/// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`). +pub async fn main_native(mut args: Vec) -> i32 { + // `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it). + if let Some(index) = args.iter().position(|a| a == "--hidden") { + args.remove(index); + crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed); + #[cfg(windows)] + crate::winsys::hide_console(); + } + let var = env_var; + let environment = Environment { + root: is_root(), + home: home_dir(), + var: &var, + }; + let command = match parse(&args, &environment) { + Ok(command) => command, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + match command { + Command::Help => { + print!("{USAGE}"); + 0 + } + Command::Version => { + println!("{}", version_text()); + 0 + } + Command::Profiles(None) => { + for (name, _) in BUILTIN { + let profile = Profile::builtin(name).expect("built-in"); + println!("{name}\n {}", profile.description); + } + 0 + } + Command::Profiles(Some(name)) => match Profile::builtin(&name) { + Some(profile) => { + print!("{}", crate::config::to_file_text(&profile)); + 0 + } + None => { + eprintln!("leleka: unknown profile {name:?}"); + 2 + } + }, + Command::Preflight(opts) => preflight(opts).await, + Command::Up(opts) => up(opts).await, + Command::Status(opts) => status(opts).await, + Command::Down(opts) => down(opts).await, + Command::Reconfigure(opts, args) => reconfigure(opts, args).await, + Command::Verify(opts) => verify(opts).await, + Command::Logs(opts, args) => crate::logview::run_logs(&opts, &args), + Command::Report(opts, args) => crate::logview::run_report(&opts, &args), + Command::Service(action, opts) => crate::winservice::run_native(action, opts).await, + Command::Run { config, kar_fd } => { + supervisor::run(supervisor::Options { config, kar_fd }).await + } + Command::SealProbe(file) => seal_probe(&file), + Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka exec-inherit: {message}"); + 2 + } + }, + Command::SealExec(rest) => match crate::sealed::seal_exec(&rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka seal-exec: {message}"); + 2 + } + }, + } +} diff --git a/crates/deploy/src/app/install_flow.rs b/crates/deploy/src/app/install_flow.rs new file mode 100644 index 00000000..7804785f --- /dev/null +++ b/crates/deploy/src/app/install_flow.rs @@ -0,0 +1,242 @@ +//! `leleka up`: run the plan, then print or serialize the summary of the installed service. + +#[allow(unused_imports)] +use super::*; + +pub async fn up(opts: UpOptions) -> i32 { + let ctx = gather(&opts, &env_var); + if let Err(message) = &ctx.profile { + eprintln!("leleka: {message}"); + return 1; + } + let report = ctx + .report + .as_ref() + .expect("report exists when the profile does"); + print_report(report); + if let Some(resources) = &ctx.needs.resources { + eprint!("{}", resources.render(&ctx.facts)); + } + let fs = gather_fs(&ctx).await; + let steps = plan_steps(&ctx, &fs); + let blocked = steps + .iter() + .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight"); + if opts.dry_run { + if opts.json { + println!( + "{}", + serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable") + ); + } else { + print!("{}", render_plan(&ctx, &steps)); + println!( + "mode: {}; nothing was changed (--dry-run)", + ctx.mode.label() + ); + } + return i32::from(report.failed() || blocked); + } + if report.failed() { + eprintln!( + "leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command." + ); + return 1; + } + eprint!("{}", render_plan(&ctx, &steps)); + match run_up(&ctx, &steps).await { + Ok(code) => code, + Err(message) => { + eprintln!("leleka: {message}"); + eprintln!( + "leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)." + ); + 1 + } + } +} + +pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { + let changes = steps::prepare(ctx, steps).await?; + let config = steps::config_of(ctx)?; + match ctx.mode { + Mode::None => { + say(&format!( + "prepared. Start it with: {} run --config {}", + ctx.paths.bin("leleka").display(), + ctx.paths.run_config().display() + )); + Ok(0) + } + Mode::Systemd(scope) => { + #[cfg(unix)] + if scope == UnitScopeTag::System { + steps::ensure_service_user(ctx).await?; + steps::hand_over_to_service_user(ctx)?; + } + let changed = steps::install_unit(ctx, scope).await?; + steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?; + steps::wait_ready(ctx, Some(scope)).await?; + summary(ctx, config); + Ok(0) + } + Mode::Foreground => { + if let Some(fd) = ctx.opts.kar_fd { + if config.profile.kar_source == crate::profile::KarSource::None { + return Err(format!( + "--kar-fd {fd} was given but profile {} has kar_source none (no archive is used); drop --kar-fd", + config.profile.name + )); + } + crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?; + } + if steps::probe_ready(ctx).await { + say("a supervisor for this state directory is already ready"); + summary(ctx, config); + return Ok(0); + } + if crate::plan::service_running(&ctx.paths) { + return Err(format!( + "another supervisor is running for {} (not ready yet); wait for it or stop it first", + ctx.opts.dirs.state.display() + )); + } + let options = supervisor::Options { + config: ctx.paths.run_config(), + kar_fd: ctx.opts.kar_fd, + }; + let run = supervisor::run(options); + tokio::pin!(run); + let mut printed = false; + loop { + tokio::select! { + code = &mut run => return Ok(code), + ready = steps::wait_ready(ctx, None), if !printed => { + printed = true; + match ready { + Ok(()) => summary(ctx, config), + Err(message) => say(&message), + } + } + } + } + } + } +} + +pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { + let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); + json!({ + "ready": true, + "endpoint": format!("http://{}", ctx.opts.ports.api), + "model": config.model_id, + "model_digest": config.model_digest, + "api_key_file": ctx.paths.api_key().display().to_string(), + "gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})), + "profile": config.profile.name, + "gpu_budget_bytes": config.profile.gpu_budget_bytes, + "context_tokens": config.profile.context_tokens, + "kar_source": config.profile.kar_source.as_str(), + "ram_total_bytes": ctx.facts.memory.total, + "ram_available_at_start_bytes": ctx.facts.memory.available, + "service": ctx.mode.label(), + "expert_tier": crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets), + "logs": ctx.paths.logs().display().to_string(), + "state": ctx.opts.dirs.state.display().to_string(), + "assets": ctx.opts.dirs.assets.display().to_string(), + }) +} + +pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { + let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); + if ctx.opts.json { + println!( + "{}", + serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable") + ); + return; + } + let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); + let key_file = ctx.paths.api_key().display().to_string(); + let mut text = String::from("\nLeleka is ready.\n"); + text.push_str(&format!( + " endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n", + ctx.opts.ports.api + )); + text.push_str(&format!( + " model {} {}\n", + config.model_id, config.model_digest + )); + text.push_str(&format!( + " api key in {key_file} (send it as `Authorization: Bearer ...`)\n" + )); + if let Some(gpu) = gpu { + text.push_str(&format!( + " gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n", + gpu.name, + gpu.index, + gpu.sm.map_or("?".into(), |s| s.to_string()), + gpu.vram_total_mib, + gpu.driver + )); + } + text.push_str(&format!( + " profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n", + config.profile.name, + gib(config.profile.gpu_budget_bytes), + config.profile.context_tokens, + match config.profile.kar_source { + crate::profile::KarSource::Memfd => format!( + "a sealed memfd ({} of RAM held for the life of the service{})", + gib(config.profile.memfd_bytes()), + if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly { + "; sparse copy: only the byte ranges the serve path reads, holes elsewhere" + } else { + "" + } + ), + crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), + crate::profile::KarSource::None => + "none (EXPERIMENTAL: no archive; the PLE rows are read from the GGUF shard, qwen4exp-native-mtp-v1)".to_owned(), + } + )); + text.push_str(&format!( + " host RAM {} total, {} available before start\n", + gib(ctx.facts.memory.total), + gib(ctx.facts.memory.available) + )); + text.push_str(&format!( + " expert {}\n", + crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets).line() + )); + text.push_str(&format!(" service {}\n", ctx.mode.label())); + if ctx.mode == Mode::Systemd(UnitScopeTag::User) { + text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot +"); + } + text.push_str(&format!( + " logs {} (leleka.log, engine.log, gateway.log, api.log)\n", + ctx.paths.logs().display() + )); + if ctx.facts.os == "windows" { + text.push_str(&format!( + " try {} +", + powershell_try(&key_file, &ctx.opts.ports.api, &config.model_id) + )); + eprintln!("{text}"); + return; + } + text.push_str(&format!( + " try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n", + config.model_id, ctx.opts.ports.api + )); + eprintln!("{text}"); +} + +/// A PowerShell one-liner that sends one request to the API (the key file may be a UNC path into WSL). +pub fn powershell_try(key_file: &str, api: &str, model: &str) -> String { + format!( + "$k=(Get-Content -Raw '{key_file}').Trim(); Invoke-RestMethod -Method Post -Uri http://{api}/v1/responses -Headers @{{Authorization=\"Bearer $k\"}} -ContentType 'application/json' -Body '{{\"model\":\"{model}\",\"input\":\"hello\",\"max_output_tokens\":32}}'" + ) +} diff --git a/crates/deploy/src/app/machine_tests.rs b/crates/deploy/src/app/machine_tests.rs new file mode 100644 index 00000000..104c3ff8 --- /dev/null +++ b/crates/deploy/src/app/machine_tests.rs @@ -0,0 +1,72 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::render_machine; +use serde_json::json; + +#[test] +fn the_machine_view_names_every_figure_the_operator_asked_for() { + let text = render_machine(&json!({ + "phase": "decode", + "gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900}, + "cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0}, + "ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0}, + "throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0, + "decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2}, + "cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968}, + "context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65} + })); + for needle in [ + "engine load (decode)", + "91% busy", + "VRAM 29.3 of 31.8 GiB", + "480 W", + "7.4 of 32 cores", + "prefill 5050 tok/s", + "decode 131 tok/s", + "135 now", + "87% of requests", + "91% of prompt", + "179968 of 262144 tokens (68.7%)", + ] { + assert!( + text.contains(needle), + "{needle}\ +{text}" + ); + } +} + +#[test] +fn the_settings_block_lists_every_member_and_the_prefix_cache_on_one_line() { + let text = super::render_settings(&json!({ + "context_tokens": 65536, "prefill_capacity": 8192, "cpu_workers": 8, + "prefix_cache": {"budget_mib": 20480, "requested": 20480, "tail": "reply", "block_tokens": 8192, "retention_min": 60} + })); + for needle in [ + "context_tokens", + "65536", + "prefill_capacity", + "cpu_workers", + "prefix cache 20480 MiB requested 20480, tail reply, block 8192 tokens, kept 60 min", + ] { + assert!( + text.contains(needle), + "{needle} +{text}" + ); + } + assert!(super::render_settings(&json!({"prefix_cache": null})).contains("prefix cache off")); +} + +#[test] +fn missing_blocks_are_left_out_not_invented() { + let text = render_machine( + &json!({"phase": "idle", "gpu": null, "cpu": null, "ram": null, + "throughput": {}, "cache": {}, "context": {"live_tokens": 0, "max_tokens": 8192}}), + ); + assert!( + !text.contains(" gpu ") && !text.contains(" cpu ") && !text.contains(" ram "), + "{text}" + ); + assert!(text.contains("prefill - tok/s")); +} diff --git a/crates/deploy/src/app/preflight_report.rs b/crates/deploy/src/app/preflight_report.rs new file mode 100644 index 00000000..4fcfb0f8 --- /dev/null +++ b/crates/deploy/src/app/preflight_report.rs @@ -0,0 +1,113 @@ +//! `leleka preflight` and the sealed-archive probe: the host checks and the JSON plan. + +#[allow(unused_imports)] +use super::*; + +/// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the file. +#[cfg(unix)] +pub(super) fn seal_probe(file: &std::path::Path) -> i32 { + use sha2::{Digest, Sha256}; + use std::os::unix::fs::FileExt; + let started = std::time::Instant::now(); + let (memfd, _identity, report) = + match crate::sealed::seal_file_report(file, None, &mut |done, total| { + eprintln!( + "sealing: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + ); + }) { + Ok(done) => done, + Err(message) => { + eprintln!("leleka seal-probe: {message}"); + return 1; + } + }; + let sealed_s = started.elapsed().as_secs_f64(); + let length = memfd.metadata().map_or(0, |m| m.len()); + let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new()); + let source = match std::fs::File::open(file) { + Ok(f) => f, + Err(error) => { + eprintln!("leleka seal-probe: {error}"); + return 1; + } + }; + let mut block = vec![0u8; 8 << 20]; + let mut other = vec![0u8; 8 << 20]; + let mut offset = 0u64; + while offset < length { + let n = (length - offset).min(block.len() as u64) as usize; + if memfd.read_exact_at(&mut block[..n], offset).is_err() + || source.read_exact_at(&mut other[..n], offset).is_err() + { + eprintln!("leleka seal-probe: read failed at {offset}"); + return 1; + } + from_memfd.update(&block[..n]); + from_file.update(&other[..n]); + offset += n as u64; + } + let (a, b) = ( + hex::encode(from_memfd.finalize()), + hex::encode(from_file.finalize()), + ); + println!( + "seal-probe {} bytes {} read={} sealed in {:.1} s ({:.0} MB/s) sha256(memfd)={} sha256(file)={} {}", + file.display(), + length, + report.strategy.as_str(), + sealed_s, + length as f64 / sealed_s.max(1e-9) / 1e6, + a, + b, + if a == b { "IDENTICAL" } else { "DIFFERENT" } + ); + i32::from(a != b) +} + +#[cfg(not(unix))] +pub(super) fn seal_probe(_file: &std::path::Path) -> i32 { + eprintln!("leleka seal-probe needs Linux"); + 2 +} + +pub(super) fn print_report(report: &Report) { + eprint!("{}", report.render()); +} + +pub(super) fn json_plan(ctx: &Context, steps: &[Step]) -> Value { + json!({ + "mode": ctx.mode, + "profile": ctx.config.as_ref().map(|c| c.profile.name.clone()), + "preflight": ctx.report, + "steps": steps, + "engine_command": ctx.config.as_ref().map(|c| { + let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()]; + args.extend(c.engine_args(c.kar_arg())); + args + }), + }) +} + +pub(super) async fn preflight(opts: UpOptions) -> i32 { + let ctx = gather(&opts, &env_var); + match (&ctx.profile, &ctx.report) { + (Err(message), _) => { + eprintln!("leleka: {message}"); + 1 + } + (Ok(_), Some(report)) => { + if opts.json { + println!( + "{}", + serde_json::to_string_pretty(report).expect("serializable") + ); + } else { + print_report(report); + } + i32::from(report.failed()) + } + _ => 1, + } +} diff --git a/crates/deploy/src/app/settings_change.rs b/crates/deploy/src/app/settings_change.rs new file mode 100644 index 00000000..80012e3a --- /dev/null +++ b/crates/deploy/src/app/settings_change.rs @@ -0,0 +1,349 @@ +//! `leleka reconfigure`: ask the supervisor, persist the settings or restart, and render the effective values. + +#[allow(unused_imports)] +use super::*; + +/// `leleka reconfigure`. +/// +/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A +/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process. +/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise). +pub(super) async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 { + let paths = opts.dirs.paths(); + let supervised = crate::plan::service_running(&paths); + if args.needs_restart() { + return reconfigure_by_restart(&opts, &args, supervised).await; + } + let settings = serde_json::Value::Object(args.settings.clone()).to_string(); + let api = crate::config::RunConfig::read(&paths.run_config()) + .map(|config| config.ports.api) + .unwrap_or_else(|_| opts.ports.api.clone()); + let Ok(key) = std::fs::read_to_string(paths.api_key()) else { + eprintln!( + "leleka: no API key in {} (is the service prepared?)", + paths.api_key().display() + ); + return 1; + }; + let Some(address) = crate::config::probe_address(&api) else { + eprintln!("leleka: cannot reach the API address {api}"); + return 1; + }; + let persist = args.persist.then_some(PersistTarget { + paths: &paths, + settings: &args.settings, + supervised, + }); + send_reconfigure(address, key.trim_end(), &settings, opts.json, persist).await +} + +/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge. +pub async fn send_reconfigure( + address: std::net::SocketAddr, + key: &str, + settings: &str, + json: bool, + persist: Option>, +) -> i32 { + eprintln!( + "leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)" + ); + let response = crate::http::post_json( + address, + "/v1/reconfigure", + Some(key), + settings, + std::time::Duration::from_secs(1900), + ) + .await; + match response { + Ok(response) => { + let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null); + let mut persisted = None; + if response.status == 200 + && let Some(target) = &persist + { + persisted = + Some(persist_settings(target.paths, target.settings, target.supervised).await); + } + if json { + let mut shown = document.clone(); + if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) { + object.insert("persisted".into(), json!(result.is_ok())); + } + println!( + "{}", + serde_json::to_string_pretty(&shown).unwrap_or(response.body) + ); + } else if response.status == 200 { + println!("reconfigured; the engine runs with:"); + print!("{}", render_settings(&document["settings"])); + match &persisted { + Some(Ok(note)) => println!("persisted: {note}"), + Some(Err(why)) => eprintln!( + "leleka: the engine runs with the new settings, but they were not persisted: {why}" + ), + None => {} + } + } else { + let message = document["error"]["message"] + .as_str() + .unwrap_or(&response.body); + eprintln!( + "leleka: the change was refused (HTTP {}): {message}", + response.status + ); + } + i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err())) + } + Err(message) => { + eprintln!("leleka: {message}"); + 1 + } + } +} + +/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine +/// keeps it) and writes the file; with no supervisor the file is edited directly. +pub(super) async fn persist_settings( + paths: &crate::layout::Paths, + settings: &serde_json::Map, + supervised: bool, +) -> Result { + if !supervised { + let changed = crate::reconfigure::persist_offline(paths, settings)?; + return Ok(format!( + "leleka.json updated ({} changed; no supervisor was running)", + changed.len() + )); + } + let request = crate::reconfigure::Request { + id: crate::reconfigure::new_request_id(), + settings: settings.clone(), + persist: true, + ..Default::default() + }; + let outcome = + ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?; + if outcome.state == crate::reconfigure::State::Done && outcome.persisted { + Ok(outcome.message) + } else { + Err(outcome.message) + } +} + +/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end). +pub(super) async fn ask_supervisor( + paths: &crate::layout::Paths, + request: &crate::reconfigure::Request, + limit: std::time::Duration, + show_progress: bool, +) -> Result { + use crate::reconfigure::{State, read_outcome, write_request}; + write_request(paths, request)?; + let started = std::time::Instant::now(); + let mut last = String::new(); + loop { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + match read_outcome(paths, &request.id) { + Some(outcome) if outcome.state != State::Running => return Ok(outcome), + Some(outcome) if show_progress && outcome.message != last => { + eprintln!("leleka: {}", outcome.message); + last = outcome.message; + } + _ => {} + } + if !crate::plan::service_running(paths) { + return Err("the supervisor stopped before it answered; see the service log".into()); + } + if started.elapsed() > limit { + let _ = std::fs::remove_file(paths.reconfigure_request()); + return Err(format!( + "the supervisor did not answer within {} s", + limit.as_secs() + )); + } + } +} + +/// A budget or preset change: the supervisor restarts the engine process with the new numbers. +pub(super) async fn reconfigure_by_restart( + opts: &UpOptions, + args: &ReconfigureArgs, + supervised: bool, +) -> i32 { + let paths = opts.dirs.paths(); + if !supervised { + eprintln!( + "leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`", + paths.dirs.state.display() + ); + return 1; + } + let load_timeout = crate::config::RunConfig::read(&paths.run_config()) + .map_or(1800, |config| config.load_timeout_s); + let request = crate::reconfigure::Request { + id: crate::reconfigure::new_request_id(), + gpu_budget_gib: args.gpu_budget_gib, + preset: args.preset, + settings: args.settings.clone(), + persist: args.persist, + }; + eprintln!( + "leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)" + ); + // two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks + let limit = std::time::Duration::from_secs(2 * load_timeout + 300); + let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await { + Ok(outcome) => outcome, + Err(why) => { + eprintln!("leleka: {why}"); + return 1; + } + }; + let done = outcome.state == crate::reconfigure::State::Done; + if opts.json { + println!( + "{}", + serde_json::to_string_pretty(&outcome).unwrap_or_default() + ); + } else if done { + println!("reconfigured: {}", outcome.message); + if let Some(effective) = &outcome.effective { + print!("{}", render_effective(effective)); + } + } else { + eprintln!("leleka: the change was not made: {}", outcome.message); + } + i32::from(!done) +} + +/// The numbers in force after a restart-in-place, one line each. +pub fn render_effective(effective: &Value) -> String { + let Some(object) = effective.as_object() else { + return String::new(); + }; + let mut out = String::new(); + for (key, value) in object { + if !value.is_null() { + out.push_str(&format!(" {key:20} {value}\n")); + } + } + out +} + +/// The settings block of the engine, one line per member. +pub fn render_settings(settings: &Value) -> String { + let Some(object) = settings.as_object() else { + return String::new(); + }; + let mut out = String::new(); + for (key, value) in object { + if key == "prefix_cache" && value.is_object() { + out.push_str(&format!( + " prefix cache {} MiB requested {}, tail {}, block {} tokens, kept {} min\n", + value["budget_mib"] + .as_u64() + .map_or("?".to_owned(), |m| m.to_string()), + value["requested"], + value["tail"].as_str().unwrap_or("?"), + value["block_tokens"], + value["retention_min"] + )); + } else if key == "prefix_cache" { + out.push_str(" prefix cache off\n"); + } else { + out.push_str(&format!(" {key:13} {value}\n")); + } + } + out +} + +/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context. +pub fn render_machine(machine: &Value) -> String { + let gib = |mib: &Value| { + mib.as_f64() + .map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0)) + }; + let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}")); + let pct = |value: &Value| { + value + .as_f64() + .map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0)) + }; + let mut out = format!( + "engine load ({}):\n", + machine["phase"].as_str().unwrap_or("?") + ); + let gpu = &machine["gpu"]; + if gpu.is_object() { + out.push_str(&format!( + " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n", + gpu["util_pct"], + gpu["mem_util_pct"], + gib(&gpu["vram_used_mib"]), + gib(&gpu["vram_total_mib"]), + gpu["power_w"] + .as_f64() + .map_or(String::new(), |w| format!(", {w:.0} W")), + gpu["sm_clock_mhz"] + .as_u64() + .map_or(String::new(), |m| format!(", {m} MHz")), + gpu["temp_c"] + .as_u64() + .map_or(String::new(), |t| format!(", {t} C")), + )); + } + let cpu = &machine["cpu"]; + if cpu.is_object() { + out.push_str(&format!( + " cpu {} of {} cores busy in the engine (whole system {}%)\n", + cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"] + )); + } + let ram = &machine["ram"]; + if ram.is_object() { + out.push_str(&format!( + " ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n", + gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"]) + )); + } + let rates = &machine["throughput"]; + out.push_str(&format!( + " prefill {} tok/s last, {} average, {} lifetime\n", + num(&rates["prefill_tok_s_last"]), + num(&rates["prefill_tok_s_avg"]), + num(&rates["prefill_tok_s_lifetime"]) + )); + out.push_str(&format!( + " decode {} tok/s last, {} average, {} lifetime{}\n", + num(&rates["decode_tok_s_last"]), + num(&rates["decode_tok_s_avg"]), + num(&rates["decode_tok_s_lifetime"]), + rates["decode_tok_s_live"] + .as_f64() + .map_or(String::new(), |v| format!(", {v:.0} now")) + )); + let cache = &machine["cache"]; + out.push_str(&format!( + " cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n", + pct(&cache["hit_ratio"]), + pct(&cache["token_hit_ratio"]), + cache["last_reused_tokens"], + cache["last_prompt_tokens"] + )); + let context = &machine["context"]; + out.push_str(&format!( + " context {} of {} tokens{}\n", + context["live_tokens"], + context["max_tokens"], + context["used_pct"] + .as_f64() + .map_or(String::new(), |p| format!(" ({p:.1}%)")) + )); + if machine["settings"].is_object() { + out.push_str("settings in force:\n"); + out.push_str(&render_settings(&machine["settings"])); + } + out +} diff --git a/crates/deploy/src/app/status_report.rs b/crates/deploy/src/app/status_report.rs new file mode 100644 index 00000000..d2bd7d67 --- /dev/null +++ b/crates/deploy/src/app/status_report.rs @@ -0,0 +1,182 @@ +//! `leleka status`: the installed scope, the supervisor document and its human rendering. + +#[allow(unused_imports)] +use super::*; + +/// Which systemd unit of this deployment exists (system first), judged by the unit file. +pub(super) fn installed_scope(paths: &crate::layout::Paths) -> Option { + let home = std::env::var_os("HOME").map(PathBuf::from); + [UnitScopeTag::System, UnitScopeTag::User] + .into_iter() + .find(|scope| { + crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name()) + .is_ok_and(|path| path.is_file()) + }) +} + +/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing. +pub(super) async fn status(opts: UpOptions) -> i32 { + let paths = opts.dirs.paths(); + let api = crate::config::RunConfig::read(&paths.run_config()) + .map(|config| config.ports.api) + .unwrap_or_else(|_| opts.ports.api.clone()); + let status: Option = std::fs::read_to_string(paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let ready = steps::probe_ready_at(&paths, &api).await; + let expert_tier = crate::config::RunConfig::read(&paths.run_config()) + .ok() + .map(|config| crate::expert_profile::tier_report(&config, &config.dirs().assets)); + let gateway = if ready { + steps::fetch_status(&paths, &api).await + } else { + None + }; + let unit = match installed_scope(&paths) { + Some(scope) => { + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + command.args(["is-active", paths.unit_name()]); + command + .output() + .await + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) + } + None => None, + }; + let requests = crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()); + print_status( + opts.json, + ready, + unit.map(|state| (paths.unit_name().to_owned(), state)), + status, + gateway.as_ref(), + expert_tier.as_ref(), + &paths.run_dir().display().to_string(), + requests.as_deref(), + ) +} + +/// The `leleka status` output from the pieces gathered on this host or through the WSL bridge. Exit code 1 when not ready. +#[allow(clippy::too_many_arguments)] +pub fn print_status( + json: bool, + ready: bool, + unit: Option<(String, String)>, + supervisor: Option, + gateway: Option<&Value>, + expert_tier: Option<&crate::expert_profile::TierReport>, + run_dir: &str, + requests: Option<&str>, +) -> i32 { + let machine = gateway + .map(|g| g["machine"].clone()) + .filter(Value::is_object); + if json { + println!( + "{}", + serde_json::to_string_pretty( + &json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), "supervisor": supervisor, "machine": machine, + "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), "expert_tier": expert_tier, "requests": requests}) + ) + .expect("serializable") + ); + } else { + println!("ready: {ready}"); + if let Some((name, state)) = unit { + println!("systemd unit {name}: {state}"); + } + match supervisor { + Some(s) => print!("{}", render_supervisor(&s, unix_now())), + None => println!("supervisor: no status file in {run_dir} (never started?)"), + } + if let Some(tier) = expert_tier { + println!("{}", tier.line()); + } + if let Some(line) = requests { + println!("{line}"); + } + if let Some(machine) = &machine { + print!("{}", render_machine(machine)); + } else if ready { + println!("engine load: the engine reports no telemetry yet"); + } + } + i32::from(!ready) +} + +pub(super) fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// `3 min`, `2 h 05 min`, `4 days 3 h`: how long ago, for people. +pub fn age_text(seconds: u64) -> String { + duration_text(seconds) +} + +pub(super) fn duration_text(seconds: u64) -> String { + match seconds { + s if s < 120 => format!("{s} s"), + s if s < 7200 => format!("{} min", s / 60), + s if s < 172_800 => format!("{} h {:02} min", s / 3600, s % 3600 / 60), + s => format!("{} days {} h", s / 86_400, s % 86_400 / 3600), + } +} + +/// The supervisor part of `leleka status`: what it does, for how long, what it restarted and why, whether it is alive. +pub fn render_supervisor(s: &Value, now: u64) -> String { + let updated = s["updated_unix"].as_u64().unwrap_or(0); + let age = now.saturating_sub(updated); + let mut out = format!( + "supervisor: phase {} (pid {}), updated {} ({} ago)\n {}\n", + s["phase"].as_str().unwrap_or("?"), + s["supervisor_pid"], + supervisor::format_utc(updated), + duration_text(age), + s["message"].as_str().unwrap_or("") + ); + // The supervisor rewrites its status at least every 30 s while it lives. + let live = !matches!(s["phase"].as_str(), Some("stopped" | "failed")); + if live && age > 120 { + out.push_str(&format!( + " WARNING: the status is {} old although the phase is {}: the supervisor is not running (crashed or killed)\n", + duration_text(age), + s["phase"].as_str().unwrap_or("?") + )); + } + if let Some(started) = s["started_unix"].as_u64() { + out.push_str(&format!( + " up {}", + duration_text(now.saturating_sub(started)) + )); + out.push_str(&format!( + ", engine restarts {} in total ({} in a row)", + s["restarts_total"].as_u64().unwrap_or(0), + s["engine_restarts"].as_u64().unwrap_or(0) + )); + if let (Some(at), Some(why)) = ( + s["last_restart_unix"].as_u64(), + s["last_restart_reason"].as_str(), + ) { + out.push_str(&format!( + "\n last restart {} ago: {why}", + duration_text(now.saturating_sub(at)) + )); + } + out.push('\n'); + } else { + out.push_str(&format!(" engine restarts {}\n", s["engine_restarts"])); + } + if let Some(health) = s["health"].as_str() { + out.push_str(&format!( + " health: {health}; logs {} MiB\n", + s["log_bytes"].as_u64().unwrap_or(0) >> 20 + )); + } + out +} diff --git a/crates/deploy/src/app/status_tests.rs b/crates/deploy/src/app/status_tests.rs new file mode 100644 index 00000000..705f449f --- /dev/null +++ b/crates/deploy/src/app/status_tests.rs @@ -0,0 +1,31 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use serde_json::json; + +#[test] +fn the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor() { + let s = json!({"phase": "ready", "supervisor_pid": 7, "updated_unix": 1_000_000, "started_unix": 900_000, "message": "ready", + "engine_restarts": 0, "restarts_total": 3, "last_restart_unix": 990_000, "last_restart_reason": "the engine process exited (signal: 9)", + "health": "healthy", "log_bytes": 5 * 1024 * 1024}); + let fresh = render_supervisor(&s, 1_000_010); + assert!( + fresh.contains("phase ready (pid 7)") && fresh.contains("up 27 h 46 min"), + "{fresh}" + ); + assert!( + fresh.contains("3 in total") + && fresh.contains("signal: 9") + && fresh.contains("health: healthy; logs 5 MiB"), + "{fresh}" + ); + assert!(!fresh.contains("WARNING"), "{fresh}"); + let stale = render_supervisor(&s, 1_000_000 + 3 * 3600); + assert!( + stale.contains("WARNING") && stale.contains("not running"), + "{stale}" + ); + // A supervisor that stopped cleanly is not "dead". + let stopped = json!({"phase": "stopped", "updated_unix": 1_000_000}); + assert!(!render_supervisor(&stopped, 2_000_000).contains("WARNING")); +} diff --git a/crates/deploy/src/app/stop_flow.rs b/crates/deploy/src/app/stop_flow.rs new file mode 100644 index 00000000..97d06337 --- /dev/null +++ b/crates/deploy/src/app/stop_flow.rs @@ -0,0 +1,74 @@ +//! `leleka down`: stop the service (or the foreground supervisor) and wait for the drain. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn down(opts: UpOptions) -> i32 { + let paths = opts.dirs.paths(); + match installed_scope(&paths) { + Some(scope) => { + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + match command.args(["stop", paths.unit_name()]).status().await { + Ok(status) if status.success() => { + eprintln!("leleka: stopped {}", paths.unit_name()); + 0 + } + Ok(status) => { + eprintln!("leleka: systemctl stop failed ({status})"); + 1 + } + Err(error) => { + eprintln!("leleka: cannot run systemctl: {error}"); + 1 + } + } + } + None => { + #[cfg(windows)] + { + return stop_foreground(&paths).await; + } + #[cfg(not(windows))] + { + eprintln!( + "leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)" + ); + 0 + } + } + } +} + +/// Windows: a supervisor in another console cannot be sent Ctrl-C, so it watches for a stop file in its run directory. +#[cfg(windows)] +pub async fn stop_foreground(paths: &crate::layout::Paths) -> i32 { + if !crate::plan::service_running(paths) { + eprintln!( + "leleka: no running supervisor for {} (Ctrl-C stops one that runs in a terminal)", + paths.dirs.state.display() + ); + return 0; + } + let request = paths.run_dir().join(supervisor::STOP_REQUEST_FILE); + if let Err(error) = std::fs::write( + &request, b"stop +", + ) { + eprintln!("leleka: cannot write {}: {error}", request.display()); + return 1; + } + eprintln!("leleka: stop requested: the API drains first, then the gateway and the engine"); + let started = std::time::Instant::now(); + while started.elapsed() < std::time::Duration::from_secs(120) { + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + if !crate::plan::service_running(paths) { + eprintln!("leleka: stopped"); + return 0; + } + } + eprintln!("leleka: the supervisor is still draining after 120 s; check `leleka status`"); + 1 +} diff --git a/crates/deploy/src/app/verify_flow.rs b/crates/deploy/src/app/verify_flow.rs new file mode 100644 index 00000000..56c990b2 --- /dev/null +++ b/crates/deploy/src/app/verify_flow.rs @@ -0,0 +1,280 @@ +//! `leleka verify`: the quick offline check and the full verification against a running engine. + +#[allow(unused_imports)] +use super::*; + +/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the +/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. +/// `leleka verify --quick`: the health of the installation without reading the model. Reports, from what is on disk and what the +/// service says: whether each model file is stamped as verified in its present state (a stamped file is not hashed again at a start), +/// whether the service runs and answers, how old and how restarted it is, and how big the logs are. Exit 0 only when all is well. +pub(super) async fn verify_quick(opts: &UpOptions) -> i32 { + use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; + let paths = opts.dirs.paths(); + let config = match crate::config::RunConfig::read(&paths.run_config()) { + Ok(config) => config, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + let stamps = VerifyStamps::new(paths.engine_stamps(), false); + let mut problems: Vec = Vec::new(); + let mut notes: Vec = Vec::new(); + let decode = |hex_text: &str| { + let mut out = [0u8; 32]; + hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out) + }; + let identity_of = |path: &std::path::Path| { + std::fs::File::open(path) + .and_then(|f| f.metadata()) + .ok() + .and_then(|m| FileIdentity::of(&m)) + }; + println!( + "model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):" + ); + for index in 0..2 { + let path = paths.shard(index); + let state = match ( + decode(crate::profile::SHARD_SHA256_HEX[index]), + identity_of(&path), + ) { + (_, None) => { + problems.push(format!("shard {index} is missing: {}", path.display())); + "MISSING" + } + (Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => { + "stamped (verified in its present state)" + } + _ => { + notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp")); + "not stamped" + } + }; + println!(" shard {index}: {state} {}", path.display()); + } + let kar = paths.kar(); + let kar_state = match identity_of(&kar) { + _ if config.profile.kar_source == crate::profile::KarSource::None => { + "not used (kar_source none)".to_owned() + } + None => { + problems.push(format!("the archive is missing: {}", kar.display())); + "MISSING".to_owned() + } + Some(id) if id.size != crate::profile::ARCHIVE_BYTES => { + problems.push(format!( + "the archive has {} bytes, the pinned archive {}", + id.size, + crate::profile::ARCHIVE_BYTES + )); + "WRONG SIZE".to_owned() + } + Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => { + "stamped (verified in its present state)".to_owned() + } + Some(_) => { + notes.push("the archive is not stamped: the next start of the engine hashes the sealed copy (about a minute)".into()); + "not stamped".to_owned() + } + }; + println!(" archive: {kar_state} {}", kar.display()); + let api = config.ports.api.clone(); + let supervisor: Option = std::fs::read_to_string(paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let ready = steps::probe_ready_at(&paths, &api).await; + println!("service:"); + match &supervisor { + Some(s) => print!( + " {}", + render_supervisor(s, unix_now()) + .replace('\n', "\n ") + .trim_end_matches(' ') + ), + None => println!( + " no status file in {} (the service has not run)", + paths.run_dir().display() + ), + } + println!(" API answers /ready: {}", if ready { "yes" } else { "NO" }); + if !ready { + problems.push("the API does not answer /ready".into()); + } + if let Some(s) = &supervisor { + let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0)); + if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) { + problems.push(format!( + "the supervisor's status is {age} s old: it is not running" + )); + } + if s["phase"].as_str() == Some("failed") { + problems.push(format!( + "the supervisor failed: {}", + s["message"].as_str().unwrap_or("") + )); + } + } + let log_bytes = crate::logs::total_bytes(&paths.logs()); + println!( + " logs: {} MiB in {} (rotated at {} MiB per file, {} generations)", + log_bytes >> 20, + paths.logs().display(), + config.logs.limit_mib, + config.logs.keep + ); + match crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()) { + Some(line) => println!(" {line}"), + None => println!( + " requests: no request record yet in {} (`leleka logs --source requests`)", + paths.logs().join("requests.log").display() + ), + } + let recent = crate::logview::recent_requests(&paths.logs(), 200); + let failed = recent + .iter() + .filter(|r| matches!(r["fin"].as_str(), Some("error" | "rejected"))) + .count(); + if recent.len() >= 10 && failed * 5 > recent.len() { + notes.push(format!("{failed} of the last {} requests failed or were rejected: see `leleka logs --level warn --since 1h`", recent.len())); + } + for note in ¬es { + println!("note: {note}"); + } + if problems.is_empty() { + println!("health: OK"); + 0 + } else { + for problem in &problems { + println!("PROBLEM: {problem}"); + } + println!("health: NOT OK"); + 1 + } +} + +pub(super) async fn verify(opts: UpOptions) -> i32 { + use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; + if opts.quick { + return verify_quick(&opts).await; + } + use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; + let paths = opts.dirs.paths(); + let config = match crate::config::RunConfig::read(&paths.run_config()) { + Ok(config) => config, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + let stamp_dir = paths.engine_stamps(); + if let Err(error) = std::fs::create_dir_all(&stamp_dir) { + eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); + return 1; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); + } + let env = std::fs::read_to_string(paths.env_file()) + .map(|text| parse_env_file(&text)) + .unwrap_or_default(); + let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else { + eprintln!( + "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", + paths.env_file().display() + ); + return 2; + }; + // The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown. + let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets); + say(&tier.line()); + let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some(); + let started = std::time::Instant::now(); + say( + "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", + ); + let engine = tokio::process::Command::new(paths.bin("leleka-inference")) + .args(config.verify_args(true)) + .env(RUNTIME_TOKEN_ENV, token) + .env_remove("HF_TOKEN") + .stdin(std::process::Stdio::null()) + .status(); + // A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is + // hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). + let archive = tokio::task::spawn_blocking({ + let kar = paths.kar(); + let memfd = config.profile.kar_source == KarSource::Memfd; + let stamps = VerifyStamps::new(stamp_dir.clone(), true); + move || -> Result, String> { + if !memfd { + return Ok(None); + } + let begun = std::time::Instant::now(); + let file = std::fs::File::open(&kar) + .map_err(|e| format!("cannot open {}: {e}", kar.display()))?; + let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + let digest = + sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; + if digest != crate::profile::archive_sha256() { + return Err(format!( + "{} does not match the pinned archive digest", + kar.display() + )); + } + let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + if let (Some(before), true) = (before, before == after) { + stamps + .record("kar-source", &crate::profile::archive_sha256(), &before) + .map_err(|e| format!("cannot record the archive stamp: {e}"))?; + } + Ok(Some(begun.elapsed().as_secs_f64())) + } + }); + let (engine, archive) = tokio::join!(engine, archive); + let mut code = 0; + match engine { + Ok(status) if status.success() => {} + Ok(status) => { + eprintln!( + "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" + ); + code = 1; + } + Err(error) => { + eprintln!( + "leleka: cannot run {}: {error}", + paths.bin("leleka-inference").display() + ); + code = 1; + } + } + match archive { + Ok(Ok(Some(seconds))) => say(&format!( + "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" + )), + Ok(Ok(None)) => {} + Ok(Err(message)) => { + eprintln!("leleka: {message}"); + code = 1; + } + Err(error) => { + eprintln!("leleka: archive verification failed to run: {error}"); + code = 1; + } + } + if tier_failed { + eprintln!( + "leleka: the expert profile is missing or does not match its pinned digest; rerun `leleka up` (or pass --no-expert-tier to accept the slower decode)" + ); + code = 1; + } + say(&format!( + "verification {} in {:.1}s", + if code == 0 { "passed" } else { "FAILED" }, + started.elapsed().as_secs_f32() + )); + code +} diff --git a/crates/deploy/src/app/version_tests.rs b/crates/deploy/src/app/version_tests.rs new file mode 100644 index 00000000..51fc9879 --- /dev/null +++ b/crates/deploy/src/app/version_tests.rs @@ -0,0 +1,20 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::version_text; + +#[test] +fn the_version_names_the_commit_and_the_strata_pin_and_keeps_the_first_line() { + let text = version_text(); + assert_eq!( + text.lines().next(), + Some(concat!("leleka ", env!("CARGO_PKG_VERSION"))) + ); + let pin = env!("LELEKA_BUILD_STRATA_PIN"); + // docs/upstream.md is in the repository this crate is built from; an exported tree without it reports `unknown`. + assert!( + pin == "unknown" || (pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit())), + "{pin}" + ); + assert!(text.contains(env!("LELEKA_BUILD_COMMIT")), "{text}"); + assert!(["clean", "dirty", "unknown"].contains(&env!("LELEKA_BUILD_TREE"))); +} diff --git a/crates/deploy/src/bin/fake_runtime.rs b/crates/deploy/src/bin/fake_runtime.rs deleted file mode 100644 index 80f03621..00000000 --- a/crates/deploy/src/bin/fake_runtime.rs +++ /dev/null @@ -1,426 +0,0 @@ -//! Test double for the six runtime programs, selected by the name it is invoked as (symlinks named -//! `leleka-inference`, `leleka-daemon`, `leleka-cli`, `strata-next`). Used only by the integration tests of -//! `leleka-deploy` (`--features test-fakes`); it speaks just enough of each program's command line and of the -//! HTTP readiness contract to exercise the supervisor and the `up` flow without a GPU or a model. -//! -//! Shared state lives in `PREFIX/fake/` (found from the invocation path `PREFIX/bin/NAME`): `engine.pid`, -//! `loaded`, `calls.log`, and the one-shot switches `crash-engine-once` / `fail-engine`. -use std::{ - fs, - io::{Read, Write}, - net::{TcpListener, TcpStream}, - path::{Path, PathBuf}, - time::Duration, -}; - -fn main() { - let mut args = std::env::args(); - let invoked = args.next().unwrap_or_default(); - let name = Path::new(&invoked) - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("") - .trim_end_matches(".exe") - .to_owned(); - let args: Vec = args.collect(); - let bin_dir = Path::new(&invoked) - .parent() - .map(Path::to_path_buf) - .unwrap_or_default(); - let fake = bin_dir - .parent() - .map(|p| p.join("fake")) - .unwrap_or_else(|| PathBuf::from("fake")); - let _ = fs::create_dir_all(&fake); - log_call(&fake, &name, &args); - match name.as_str() { - "leleka-inference" => engine(&fake, &args), - "leleka-daemon" => daemon(&args), - "leleka-cli" => cli(&fake, &args), - "strata-next" => strata(&fake, &args), - other => { - eprintln!("fake runtime invoked as {other:?}"); - std::process::exit(64); - } - } -} - -fn log_call(fake: &Path, name: &str, args: &[String]) { - // Tokens never appear on a command line; the log is for call counting. - if let Ok(mut file) = fs::OpenOptions::new() - .create(true) - .append(true) - .open(fake.join("calls.log")) - { - let _ = writeln!(file, "{name} {}", args.join(" ")); - } -} - -fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .map(String::as_str) -} - -fn alive(address: &str) -> bool { - address - .parse() - .is_ok_and(|a| TcpStream::connect_timeout(&a, Duration::from_secs(2)).is_ok()) -} - -fn engine(fake: &Path, args: &[String]) { - if args.iter().any(|a| a == "--verify-only") { - // `--verify-only`: the load-time source verification, no listener, no model. - if fake.join("fail-verify").exists() { - eprintln!("fake engine: a file does not match its pinned digest"); - std::process::exit(1); - } - eprintln!("leleka-load-time phase=all_sources_verified seconds=0.01 total=0.01"); - return; - } - if fake.join("fail-engine").exists() { - eprintln!("fake engine: failing on request"); - std::process::exit(7); - } - let token = std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default(); - if token.len() < 32 { - eprintln!("fake engine: LELEKA_RUNTIME_TOKEN missing"); - std::process::exit(2); - } - if std::env::var_os("HF_TOKEN").is_some() { - eprintln!("fake engine: HF_TOKEN leaked into the engine environment"); - std::process::exit(3); - } - // `fail-engine-budget` holds a `--gpu-budget` value (bytes) the engine refuses to start with: a new setting that - // does not come up, while the previous one does. - if let (Ok(refused), Some(budget)) = ( - fs::read_to_string(fake.join("fail-engine-budget")), - flag(args, "--gpu-budget"), - ) && refused.trim() == budget - { - eprintln!("fake engine: refusing a budget of {budget} bytes"); - std::process::exit(9); - } - let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned(); - if let Some(fd) = flag(args, "--kar-archive-fd") { - // The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd. - let number: u32 = fd.parse().unwrap_or(0); - let path = format!("/proc/self/fd/{number}"); - let meta = fs::metadata(&path); - let ok = number >= 3 && meta.as_ref().is_ok_and(|m| m.is_file()); - if !ok { - eprintln!("fake engine: descriptor {fd} is not an inherited regular file"); - std::process::exit(4); - } - eprintln!( - "fake engine: kar fd {number} bytes {}", - meta.map(|m| m.len()).unwrap_or(0) - ); - } else if let Some(file) = flag(args, "--kar-archive-file") { - if !Path::new(file).is_file() { - eprintln!("fake engine: archive file {file} missing"); - std::process::exit(4); - } - } else { - eprintln!("fake engine: no archive argument"); - std::process::exit(5); - } - let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { - eprintln!("fake engine: cannot bind {listen}: {e}"); - std::process::exit(6); - }); - let _ = fs::remove_file(fake.join("loaded")); - let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string()); - eprintln!( - "fake engine: listening on {listen} pid {}", - std::process::id() - ); - if fake.join("fail-load").exists() { - // The real engine reports a failed load on its own stderr and stays up. - eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable"); - } - if fake.join("crash-engine-once").exists() { - let _ = fs::remove_file(fake.join("crash-engine-once")); - std::thread::spawn(|| { - std::thread::sleep(Duration::from_millis(1500)); - eprintln!("fake engine: crashing on request"); - std::process::exit(9); - }); - } - for stream in listener.incoming() { - drop(stream); - } -} - -fn daemon(args: &[String]) { - let config: serde_json::Value = flag(args, "--config") - .and_then(|p| fs::read_to_string(p).ok()) - .and_then(|t| serde_json::from_str(&t).ok()) - .unwrap_or_default(); - let listen = config["listen"] - .as_str() - .unwrap_or("127.0.0.1:0") - .to_owned(); - if std::env::var("LELEKA_GATEWAY_TOKEN") - .unwrap_or_default() - .len() - < 32 - { - eprintln!("fake daemon: LELEKA_GATEWAY_TOKEN missing"); - std::process::exit(2); - } - let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { - eprintln!("fake daemon: cannot bind {listen}: {e}"); - std::process::exit(6); - }); - for stream in listener.incoming() { - drop(stream); - } -} - -fn cli(fake: &Path, args: &[String]) { - let config: serde_json::Value = flag(args, "--config") - .and_then(|p| fs::read_to_string(p).ok()) - .and_then(|t| serde_json::from_str(&t).ok()) - .unwrap_or_default(); - let engine_address = config["runtimes"][0]["address"] - .as_str() - .unwrap_or("") - .to_owned(); - let id = config["runtimes"][0]["id"] - .as_str() - .unwrap_or("") - .to_owned(); - let rest: Vec<&str> = args.iter().skip(2).map(String::as_str).collect(); - match rest.as_slice() { - ["status"] => { - let connected = alive(&engine_address); - let ready = connected && fake.join("loaded").exists(); - println!( - "{}", - serde_json::json!({"schema_version":1,"runtimes":[{"id":id,"connected":connected,"epoch":"e","loaded_handle":null,"model_ready":ready,"configuration_action_required":false}]}) - ); - } - ["load-mtp", model, profile] => { - if *model != id || *profile != "qwen4exp-kar-ple-mtp-v1" || !alive(&engine_address) { - eprintln!("Error: \"runtime_not_connected\""); - std::process::exit(1); - } - // Like the real CLI: the operation id and epoch are printed before the command is sent. - println!("{{\"operation_id\":\"op-1\",\"epoch\":\"e\",\"model\":\"{id}\"}}"); - // Loading takes a moment in the real engine. - std::thread::sleep(Duration::from_millis(700)); - if !fake.join("fail-load").exists() { - let _ = fs::write(fake.join("loaded"), "1"); - } - println!("{{\"state\":1}}"); - } - ["operation", model, "op-1", "e"] if *model == id => { - let state = if fake.join("fail-load").exists() { - 3 - } else if fake.join("loaded").exists() { - 2 - } else { - 1 - }; - println!( - "{{ - \"state\": {state} -}}" - ); - } - _ => { - eprintln!("fake cli: unsupported {rest:?}"); - std::process::exit(2); - } - } -} - -fn strata(fake: &Path, args: &[String]) { - let args: Vec<&str> = args.iter().map(String::as_str).collect(); - match args.as_slice() { - ["api-key", "init", "--file", file] => { - if !Path::new(file).exists() { - let key = "fake-api-key-0123456789abcdef0123456789abcdef"; - let mut options = fs::OpenOptions::new(); - options.create_new(true).write(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let _ = options - .open(file) - .and_then(|mut f| f.write_all(key.as_bytes())); - } - println!("{{\"created\":false}}"); - } - ["model", "fetch", _, "--output", dir] => { - fetch_shards(dir); - println!("fetched"); - } - ["model", "verify", _, "--output", _] => println!("verified"), - [ - "model", - "ensure-sharded-streamed", - _, - "--source-dir", - source_dir, - "--output", - kar, - "--levels", - "2", - ] => { - // Like the real tool: fetch and verify the shards first. - fetch_shards(source_dir); - if !Path::new(kar).exists() { - fs::File::create(kar) - .and_then(|f| f.set_len(55_295_529_472)) - .expect("sparse archive"); - fs::write(format!("{kar}.provenance.json"), "{}").expect("provenance"); - } - println!("created and verified experimental streamed KAR-2: {kar}"); - } - ["model", "extract-tokenizer", _, "--output", dir] => { - fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir"); - fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}") - .expect("tokenizer file"); - } - ["serve", "--config", config] => api(fake, config), - other => { - eprintln!("fake strata-next: unsupported {other:?}"); - std::process::exit(2); - } - } -} - -fn fetch_shards(dir: &str) { - fs::create_dir_all(dir).expect("model dir"); - for (name, size) in [ - ( - "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - 54_817_524_224u64, - ), - ( - "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - 28_800_138_432u64, - ), - ] { - let path = Path::new(dir).join(name); - if !path.exists() { - fs::File::create(&path) - .and_then(|f| f.set_len(size)) - .expect("sparse shard"); - } - } -} - -fn api(fake: &Path, config: &str) { - let config: serde_json::Value = fs::read_to_string(config) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()) - .unwrap_or_default(); - let bind = config["bind"].as_str().unwrap_or("127.0.0.1:0").to_owned(); - let engine_address = config["runtime"]["address"] - .as_str() - .unwrap_or("") - .to_owned(); - let key = config["api_key_file"] - .as_str() - .and_then(|p| fs::read_to_string(p).ok()) - .unwrap_or_default() - .trim() - .to_owned(); - if std::env::var("LELEKA_RUNTIME_TOKEN") - .unwrap_or_default() - .len() - < 32 - { - eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing"); - std::process::exit(2); - } - let listener = TcpListener::bind(&bind).unwrap_or_else(|e| { - eprintln!("fake api: cannot bind {bind}: {e}"); - std::process::exit(6); - }); - for stream in listener.incoming().flatten() { - let (fake, engine_address, key) = (fake.to_path_buf(), engine_address.clone(), key.clone()); - std::thread::spawn(move || respond(stream, &fake, &engine_address, &key)); - } -} - -fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str, key: &str) { - // The head and the body of a POST may arrive in separate segments: read until Content-Length bytes of body are in. - let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); - let mut raw: Vec = Vec::new(); - let mut buffer = [0u8; 4096]; - loop { - let count = stream.read(&mut buffer).unwrap_or(0); - raw.extend_from_slice(&buffer[..count]); - let text = String::from_utf8_lossy(&raw).into_owned(); - let complete = text.split_once("\r\n\r\n").is_some_and(|(head, body)| { - let wanted = head - .lines() - .find_map(|l| { - l.to_ascii_lowercase() - .strip_prefix("content-length:") - .and_then(|v| v.trim().parse::().ok()) - }) - .unwrap_or(0); - body.len() >= wanted - }); - if count == 0 || complete { - break; - } - } - let request = String::from_utf8_lossy(&raw).into_owned(); - let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned(); - let authorized = request.contains(&format!("Authorization: Bearer {key}\r\n")); - let ready = alive(engine_address) && fake.join("loaded").exists(); - let (status, body) = match path.as_str() { - "/health" => ("200 OK", "{\"ok\":true}".to_owned()), - _ if !authorized => ( - "401 Unauthorized", - "{\"error\":\"unauthorized\"}".to_owned(), - ), - "/ready" if ready => ( - "200 OK", - "{\"service\":\"strata-control\",\"ready\":true}".to_owned(), - ), - "/ready" => ( - "503 Service Unavailable", - "{\"service\":\"strata-control\",\"ready\":false}".to_owned(), - ), - // The gateway status document with an engine telemetry block, as `leleka status` renders it. - // The control plane's own view: the worker state and the request that is active (a switch file makes one stay active). - // One-shot: the next answer after it is a healthy one (the restarted engine is not hung). - "/metrics" if fake.join("hang-decode").exists() => { - let _ = fs::remove_file(fake.join("hang-decode")); - ( - "200 OK", - "{\"worker\":\"ready\",\"up\":true,\"active\":true,\"active_elapsed_ms\":600000}".to_owned(), - ) - } - "/metrics" => ( - "200 OK", - format!("{{\"worker\":\"{}\",\"up\":{ready},\"active\":false,\"active_elapsed_ms\":null}}", if ready { "ready" } else { "failed" }), - ), - "/v1/status" if ready => ( - "200 OK", - "{\"loaded\":true,\"machine\":{\"phase\":\"idle\",\"gpu\":null,\"cpu\":null,\"ram\":null,\"throughput\":{},\"cache\":{},\"context\":{\"live_tokens\":0,\"max_tokens\":8192}},\"prefix_cache\":null}".to_owned(), - ), - // `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers. - "/v1/reconfigure" if request.starts_with("POST") && ready => { - let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}"); - let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default(); - ("200 OK", serde_json::json!({"settings": settings}).to_string()) - } - _ => ("404 Not Found", "{}".to_owned()), - }; - let _ = write!( - stream, - "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", - body.len() - ); -} diff --git a/crates/deploy/src/bin/fake_runtime/cli_double.rs b/crates/deploy/src/bin/fake_runtime/cli_double.rs new file mode 100644 index 00000000..b8d3b379 --- /dev/null +++ b/crates/deploy/src/bin/fake_runtime/cli_double.rs @@ -0,0 +1,83 @@ +//! The `leleka-cli` double: typed load, verify and shard fetch answers. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn cli(fake: &Path, args: &[String]) { + let config: serde_json::Value = flag(args, "--config") + .and_then(|p| fs::read_to_string(p).ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let engine_address = config["runtimes"][0]["address"] + .as_str() + .unwrap_or("") + .to_owned(); + let id = config["runtimes"][0]["id"] + .as_str() + .unwrap_or("") + .to_owned(); + let rest: Vec<&str> = args.iter().skip(2).map(String::as_str).collect(); + match rest.as_slice() { + ["status"] => { + let connected = alive(&engine_address); + let ready = connected && fake.join("loaded").exists(); + println!( + "{}", + serde_json::json!({"schema_version":1,"runtimes":[{"id":id,"connected":connected,"epoch":"e","loaded_handle":null,"model_ready":ready,"configuration_action_required":false}]}) + ); + } + ["load-mtp", model, profile] => { + if *model != id || *profile != "qwen4exp-kar-ple-mtp-v1" || !alive(&engine_address) { + eprintln!("Error: \"runtime_not_connected\""); + std::process::exit(1); + } + // Like the real CLI: the operation id and epoch are printed before the command is sent. + println!("{{\"operation_id\":\"op-1\",\"epoch\":\"e\",\"model\":\"{id}\"}}"); + // Loading takes a moment in the real engine. + std::thread::sleep(Duration::from_millis(700)); + if !fake.join("fail-load").exists() { + let _ = fs::write(fake.join("loaded"), "1"); + } + println!("{{\"state\":1}}"); + } + ["operation", model, "op-1", "e"] if *model == id => { + let state = if fake.join("fail-load").exists() { + 3 + } else if fake.join("loaded").exists() { + 2 + } else { + 1 + }; + println!( + "{{ + \"state\": {state} +}}" + ); + } + _ => { + eprintln!("fake cli: unsupported {rest:?}"); + std::process::exit(2); + } + } +} + +pub(super) fn fetch_shards(dir: &str) { + fs::create_dir_all(dir).expect("model dir"); + for (name, size) in [ + ( + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + 54_817_524_224u64, + ), + ( + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + 28_800_138_432u64, + ), + ] { + let path = Path::new(dir).join(name); + if !path.exists() { + fs::File::create(&path) + .and_then(|f| f.set_len(size)) + .expect("sparse shard"); + } + } +} diff --git a/crates/deploy/src/bin/fake_runtime/engine_double.rs b/crates/deploy/src/bin/fake_runtime/engine_double.rs new file mode 100644 index 00000000..f550eff1 --- /dev/null +++ b/crates/deploy/src/bin/fake_runtime/engine_double.rs @@ -0,0 +1,94 @@ +//! The `leleka-inference` double: its port, its pid file and its one-shot crash and failure switches. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn alive(address: &str) -> bool { + address + .parse() + .is_ok_and(|a| TcpStream::connect_timeout(&a, Duration::from_secs(2)).is_ok()) +} + +pub(super) fn engine(fake: &Path, args: &[String]) { + if args.iter().any(|a| a == "--verify-only") { + // `--verify-only`: the load-time source verification, no listener, no model. + if fake.join("fail-verify").exists() { + eprintln!("fake engine: a file does not match its pinned digest"); + std::process::exit(1); + } + eprintln!("leleka-load-time phase=all_sources_verified seconds=0.01 total=0.01"); + return; + } + if fake.join("fail-engine").exists() { + eprintln!("fake engine: failing on request"); + std::process::exit(7); + } + let token = std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default(); + if token.len() < 32 { + eprintln!("fake engine: LELEKA_RUNTIME_TOKEN missing"); + std::process::exit(2); + } + if std::env::var_os("HF_TOKEN").is_some() { + eprintln!("fake engine: HF_TOKEN leaked into the engine environment"); + std::process::exit(3); + } + // `fail-engine-budget` holds a `--gpu-budget` value (bytes) the engine refuses to start with: a new setting that + // does not come up, while the previous one does. + if let (Ok(refused), Some(budget)) = ( + fs::read_to_string(fake.join("fail-engine-budget")), + flag(args, "--gpu-budget"), + ) && refused.trim() == budget + { + eprintln!("fake engine: refusing a budget of {budget} bytes"); + std::process::exit(9); + } + let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned(); + if let Some(fd) = flag(args, "--kar-archive-fd") { + // The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd. + let number: u32 = fd.parse().unwrap_or(0); + let path = format!("/proc/self/fd/{number}"); + let meta = fs::metadata(&path); + let ok = number >= 3 && meta.as_ref().is_ok_and(|m| m.is_file()); + if !ok { + eprintln!("fake engine: descriptor {fd} is not an inherited regular file"); + std::process::exit(4); + } + eprintln!( + "fake engine: kar fd {number} bytes {}", + meta.map(|m| m.len()).unwrap_or(0) + ); + } else if let Some(file) = flag(args, "--kar-archive-file") { + if !Path::new(file).is_file() { + eprintln!("fake engine: archive file {file} missing"); + std::process::exit(4); + } + } else { + eprintln!("fake engine: no archive argument"); + std::process::exit(5); + } + let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { + eprintln!("fake engine: cannot bind {listen}: {e}"); + std::process::exit(6); + }); + let _ = fs::remove_file(fake.join("loaded")); + let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string()); + eprintln!( + "fake engine: listening on {listen} pid {}", + std::process::id() + ); + if fake.join("fail-load").exists() { + // The real engine reports a failed load on its own stderr and stays up. + eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable"); + } + if fake.join("crash-engine-once").exists() { + let _ = fs::remove_file(fake.join("crash-engine-once")); + std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(1500)); + eprintln!("fake engine: crashing on request"); + std::process::exit(9); + }); + } + for stream in listener.incoming() { + drop(stream); + } +} diff --git a/crates/deploy/src/bin/fake_runtime/gateway_double.rs b/crates/deploy/src/bin/fake_runtime/gateway_double.rs new file mode 100644 index 00000000..f2d031a7 --- /dev/null +++ b/crates/deploy/src/bin/fake_runtime/gateway_double.rs @@ -0,0 +1,171 @@ +//! The gateway and API doubles: the strata process and its HTTP readiness answers. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn strata(fake: &Path, args: &[String]) { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + match args.as_slice() { + ["api-key", "init", "--file", file] => { + if !Path::new(file).exists() { + let key = "fake-api-key-0123456789abcdef0123456789abcdef"; + let mut options = fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let _ = options + .open(file) + .and_then(|mut f| f.write_all(key.as_bytes())); + } + println!("{{\"created\":false}}"); + } + ["model", "fetch", _, "--output", dir] => { + fetch_shards(dir); + println!("fetched"); + } + ["model", "verify", _, "--output", _] => println!("verified"), + [ + "model", + "ensure-sharded-streamed", + _, + "--source-dir", + source_dir, + "--output", + kar, + "--levels", + "2", + ] => { + // Like the real tool: fetch and verify the shards first. + fetch_shards(source_dir); + if !Path::new(kar).exists() { + fs::File::create(kar) + .and_then(|f| f.set_len(55_295_529_472)) + .expect("sparse archive"); + fs::write(format!("{kar}.provenance.json"), "{}").expect("provenance"); + } + println!("created and verified experimental streamed KAR-2: {kar}"); + } + ["model", "extract-tokenizer", _, "--output", dir] => { + fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir"); + fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}") + .expect("tokenizer file"); + } + ["serve", "--config", config] => api(fake, config), + other => { + eprintln!("fake strata-next: unsupported {other:?}"); + std::process::exit(2); + } + } +} + +pub(super) fn api(fake: &Path, config: &str) { + let config: serde_json::Value = fs::read_to_string(config) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let bind = config["bind"].as_str().unwrap_or("127.0.0.1:0").to_owned(); + let engine_address = config["runtime"]["address"] + .as_str() + .unwrap_or("") + .to_owned(); + let key = config["api_key_file"] + .as_str() + .and_then(|p| fs::read_to_string(p).ok()) + .unwrap_or_default() + .trim() + .to_owned(); + if std::env::var("LELEKA_RUNTIME_TOKEN") + .unwrap_or_default() + .len() + < 32 + { + eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing"); + std::process::exit(2); + } + let listener = TcpListener::bind(&bind).unwrap_or_else(|e| { + eprintln!("fake api: cannot bind {bind}: {e}"); + std::process::exit(6); + }); + for stream in listener.incoming().flatten() { + let (fake, engine_address, key) = (fake.to_path_buf(), engine_address.clone(), key.clone()); + std::thread::spawn(move || respond(stream, &fake, &engine_address, &key)); + } +} + +pub(super) fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str, key: &str) { + // The head and the body of a POST may arrive in separate segments: read until Content-Length bytes of body are in. + let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); + let mut raw: Vec = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + let count = stream.read(&mut buffer).unwrap_or(0); + raw.extend_from_slice(&buffer[..count]); + let text = String::from_utf8_lossy(&raw).into_owned(); + let complete = text.split_once("\r\n\r\n").is_some_and(|(head, body)| { + let wanted = head + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .and_then(|v| v.trim().parse::().ok()) + }) + .unwrap_or(0); + body.len() >= wanted + }); + if count == 0 || complete { + break; + } + } + let request = String::from_utf8_lossy(&raw).into_owned(); + let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned(); + let authorized = request.contains(&format!("Authorization: Bearer {key}\r\n")); + let ready = alive(engine_address) && fake.join("loaded").exists(); + let (status, body) = match path.as_str() { + "/health" => ("200 OK", "{\"ok\":true}".to_owned()), + _ if !authorized => ( + "401 Unauthorized", + "{\"error\":\"unauthorized\"}".to_owned(), + ), + "/ready" if ready => ( + "200 OK", + "{\"service\":\"strata-control\",\"ready\":true}".to_owned(), + ), + "/ready" => ( + "503 Service Unavailable", + "{\"service\":\"strata-control\",\"ready\":false}".to_owned(), + ), + // The gateway status document with an engine telemetry block, as `leleka status` renders it. + // The control plane's own view: the worker state and the request that is active (a switch file makes one stay active). + // One-shot: the next answer after it is a healthy one (the restarted engine is not hung). + "/metrics" if fake.join("hang-decode").exists() => { + let _ = fs::remove_file(fake.join("hang-decode")); + ( + "200 OK", + "{\"worker\":\"ready\",\"up\":true,\"active\":true,\"active_elapsed_ms\":600000}".to_owned(), + ) + } + "/metrics" => ( + "200 OK", + format!("{{\"worker\":\"{}\",\"up\":{ready},\"active\":false,\"active_elapsed_ms\":null}}", if ready { "ready" } else { "failed" }), + ), + "/v1/status" if ready => ( + "200 OK", + "{\"loaded\":true,\"machine\":{\"phase\":\"idle\",\"gpu\":null,\"cpu\":null,\"ram\":null,\"throughput\":{},\"cache\":{},\"context\":{\"live_tokens\":0,\"max_tokens\":8192}},\"prefix_cache\":null}".to_owned(), + ), + // `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers. + "/v1/reconfigure" if request.starts_with("POST") && ready => { + let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}"); + let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default(); + ("200 OK", serde_json::json!({"settings": settings}).to_string()) + } + _ => ("404 Not Found", "{}".to_owned()), + }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); +} diff --git a/crates/deploy/src/bin/fake_runtime/main.rs b/crates/deploy/src/bin/fake_runtime/main.rs new file mode 100644 index 00000000..baade9a0 --- /dev/null +++ b/crates/deploy/src/bin/fake_runtime/main.rs @@ -0,0 +1,108 @@ +//! Test double for the six runtime programs, selected by the name it is invoked as (symlinks named +//! `leleka-inference`, `leleka-daemon`, `leleka-cli`, `strata-next`). Used only by the integration tests of +//! `leleka-deploy` (`--features test-fakes`); it speaks just enough of each program's command line and of the +//! HTTP readiness contract to exercise the supervisor and the `up` flow without a GPU or a model. +//! +//! Shared state lives in `PREFIX/fake/` (found from the invocation path `PREFIX/bin/NAME`): `engine.pid`, +//! `loaded`, `calls.log`, and the one-shot switches `crash-engine-once` / `fail-engine`. +use std::{ + fs, + io::{Read, Write}, + net::{TcpListener, TcpStream}, + path::{Path, PathBuf}, + time::Duration, +}; + +fn main() { + let mut args = std::env::args(); + let invoked = args.next().unwrap_or_default(); + let name = Path::new(&invoked) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .trim_end_matches(".exe") + .to_owned(); + let args: Vec = args.collect(); + let bin_dir = Path::new(&invoked) + .parent() + .map(Path::to_path_buf) + .unwrap_or_default(); + let fake = bin_dir + .parent() + .map(|p| p.join("fake")) + .unwrap_or_else(|| PathBuf::from("fake")); + let _ = fs::create_dir_all(&fake); + log_call(&fake, &name, &args); + match name.as_str() { + "leleka-inference" => engine(&fake, &args), + "leleka-daemon" => daemon(&args), + "leleka-cli" => cli(&fake, &args), + "strata-next" => strata(&fake, &args), + other => { + eprintln!("fake runtime invoked as {other:?}"); + std::process::exit(64); + } + } +} + +fn log_call(fake: &Path, name: &str, args: &[String]) { + // Tokens never appear on a command line; the log is for call counting. + if let Ok(mut file) = fs::OpenOptions::new() + .create(true) + .append(true) + .open(fake.join("calls.log")) + { + let _ = writeln!(file, "{name} {}", args.join(" ")); + } +} + +fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1)) + .map(String::as_str) +} + +fn daemon(args: &[String]) { + let config: serde_json::Value = flag(args, "--config") + .and_then(|p| fs::read_to_string(p).ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let listen = config["listen"] + .as_str() + .unwrap_or("127.0.0.1:0") + .to_owned(); + if std::env::var("LELEKA_GATEWAY_TOKEN") + .unwrap_or_default() + .len() + < 32 + { + eprintln!("fake daemon: LELEKA_GATEWAY_TOKEN missing"); + std::process::exit(2); + } + let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { + eprintln!("fake daemon: cannot bind {listen}: {e}"); + std::process::exit(6); + }); + for stream in listener.incoming() { + drop(stream); + } +} + +mod engine_double; +#[allow(unused_imports)] +use engine_double::alive; +#[allow(unused_imports)] +use engine_double::engine; +mod cli_double; +#[allow(unused_imports)] +use cli_double::cli; +#[allow(unused_imports)] +use cli_double::fetch_shards; +mod gateway_double; +#[allow(unused_imports)] +use gateway_double::api; +#[allow(unused_imports)] +use gateway_double::respond; +#[allow(unused_imports)] +use gateway_double::strata; diff --git a/crates/deploy/src/cli/tests.rs b/crates/deploy/src/cli/tests.rs index 4457770b..130e1be0 100644 --- a/crates/deploy/src/cli/tests.rs +++ b/crates/deploy/src/cli/tests.rs @@ -18,390 +18,5 @@ fn parse_as(root: bool, args: &[&str]) -> Result { ) } -#[test] -fn logs_and_report_take_their_own_flags_and_the_locating_ones() { - let state = if cfg!(windows) { - "C:\\x\\state" - } else { - "/var/lib/x" - }; - let Ok(Command::Logs(options, logs)) = parse_as( - false, - &[ - "logs", - "--tail", - "20", - "--since=15m", - "--level", - "warn", - "--request", - "0b1c2d3e", - "--state-dir", - state, - ], - ) else { - panic!() - }; - assert_eq!( - ( - logs.tail, - logs.since.as_deref(), - logs.level.as_deref(), - logs.request.as_deref() - ), - (Some(20), Some("15m"), Some("warn"), Some("0b1c2d3e")) - ); - assert_eq!(options.dirs.state, PathBuf::from(state)); - assert!( - matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api")) - ); - assert!(parse_as(false, &["logs", "--tail", "0"]).is_err()); - assert!(parse_as(false, &["logs", "--tail", "x"]).is_err()); - assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err()); - assert!(parse_as(false, &["logs", "--bogus"]).is_err()); - let Ok(Command::Report(_, report)) = parse_as(false, &["report"]) else { - panic!() - }; - assert!( - !report.yes && report.last == 50 && report.out.is_none(), - "the opt-in is explicit" - ); - let Ok(Command::Report(_, report)) = - parse_as(false, &["report", "--yes", "--last", "200", "--out", "-"]) - else { - panic!() - }; - assert!(report.yes && report.last == 200 && report.out.as_deref() == Some("-")); - assert!(parse_as(false, &["report", "--last", "9999"]).is_err()); - assert!( - USAGE.contains("leleka logs") && USAGE.contains("leleka report") && USAGE.contains("--yes") - ); -} - -#[cfg(unix)] -#[test] -fn up_defaults_for_a_user() { - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert_eq!( - options.dirs.assets, - PathBuf::from("/home/para/.local/share/leleka/assets") - ); - assert_eq!(options.ports.api, "127.0.0.1:8081"); - assert!(options.fetch && options.install_cublas && !options.dry_run); - assert_eq!(options.mode, ModeChoice::Auto); - assert_eq!(options.timeout_s, 3600); -} - -#[test] -fn the_expert_profile_flags_parse_and_exclude_each_other() { - let Command::Up(options) = parse_as( - false, - &["up", "--expert-profile-file", "/mnt/usb/expert-profile.bin"], - ) - .unwrap() else { - panic!() - }; - assert_eq!( - options.expert_profile_file, - Some(PathBuf::from("/mnt/usb/expert-profile.bin")) - ); - assert!(!options.no_expert_tier); - let Command::Up(options) = parse_as(false, &["up", "--no-expert-tier"]).unwrap() else { - panic!() - }; - assert!(options.no_expert_tier && options.expert_profile_file.is_none()); - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert!(!options.no_expert_tier && options.expert_profile_file.is_none()); - let error = parse_as( - false, - &["up", "--no-expert-tier", "--expert-profile-file", "/x"], - ) - .unwrap_err(); - assert!(error.contains("contradict"), "{error}"); - assert!(parse_as(false, &["up", "--no-expert-tier=1"]).is_err()); -} - -#[test] -fn flags_accept_both_forms_and_reject_mistakes() { - let Command::Up(options) = parse_as( - false, - &[ - "up", - "--assets=/data/l", - "--gpu", - "1", - "--foreground", - "--dry-run", - "--json", - "--no-fetch", - "--api-port=9000", - ], - ) - .unwrap() else { - panic!() - }; - assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); - assert_eq!( - ( - options.gpu, - options.mode, - options.dry_run, - options.json, - options.fetch - ), - (1, ModeChoice::Foreground, true, true, false) - ); - assert_eq!(options.ports.api, "127.0.0.1:9000"); - for bad in [ - &["up", "--nope"][..], - &["up", "--gpu"], - &["up", "--dry-run", "--dry-run"], - &["up", "--dry-run=1"], - &["up", "--assets", "relative/dir"], - &["up", "--api-port", "80"], - &["up", "--api-port", "9000", "--engine-port", "9000"], - &["up", "--mode", "weird"], - &["up", "--foreground", "--mode", "user"], - &["up", "--gpu-budget-gib", "0"], - &["up", "--context-tokens", "999999"], - &["up", "--timeout-s", "0"], - ] { - assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); - } -} - -#[test] -fn the_resource_preset_comes_from_the_flag_then_the_environment() { - use crate::resources::Preset; - let preset = |args: &[&str]| match parse_as(false, args) { - Ok(Command::Up(options)) => Ok(options.preset), - Ok(_) => unreachable!(), - Err(message) => Err(message), - }; - assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); - assert_eq!( - preset(&["up", "--preset", "workstation"]), - Ok(Preset::Workstation) - ); - assert!( - preset(&["up", "--preset", "shared"]) - .unwrap_err() - .contains("unknown preset") - ); -} - -#[test] -fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() { - let Ok(Command::Reconfigure(options, args)) = parse_as( - false, - &[ - "reconfigure", - "--context-tokens", - "65536", - "--prefix-cache-tail=reply", - "--prefix-cache-mib", - "20480", - "--spec-min-p", - "0.5", - "--state-dir", - "/var/lib/leleka/state", - ], - ) else { - panic!("reconfigure did not parse"); - }; - assert_eq!( - options.dirs.state, - std::path::PathBuf::from("/var/lib/leleka/state") - ); - assert!(!args.needs_restart() && !args.persist); - let value = serde_json::Value::Object(args.settings); - assert_eq!(value["context_tokens"], 65536); - assert_eq!(value["prefix_cache_tail"], "reply"); - assert_eq!(value["prefix_cache_mib"], "20480"); - assert_eq!(value["spec_min_p"], 0.5); - assert!( - parse_as(false, &["reconfigure"]) - .unwrap_err() - .contains("at least one setting") - ); - assert!( - parse_as(false, &["reconfigure", "--cpu-workers", "many"]) - .unwrap_err() - .contains("whole number") - ); - assert!( - parse_as( - false, - &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"] - ) - .unwrap_err() - .contains("twice") - ); -} - -#[test] -fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { - let Ok(Command::Reconfigure(options, args)) = parse_as( - false, - &[ - "reconfigure", - "--gpu-budget-gib", - "24", - "--preset=workstation", - "--persist", - "--context-tokens", - "65536", - "--state-dir", - "/s", - ], - ) else { - panic!("reconfigure did not parse"); - }; - assert!(args.needs_restart() && args.persist); - assert_eq!(args.gpu_budget_gib, Some(24)); - assert_eq!(args.preset, Some(crate::resources::Preset::Workstation)); - assert_eq!(args.settings["context_tokens"], 65536); - // they are the restart request, not `up` options: the service is located by the remaining flags only - assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); - assert_eq!(options.gpu_budget_gib, None); - assert_eq!(options.preset, crate::resources::Preset::Dedicated); - // the budget or the preset alone is a request; nothing at all is not - assert!(matches!( - parse_as(false, &["reconfigure", "--preset", "dedicated"]), - Ok(Command::Reconfigure(..)) - )); - assert!(matches!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), - Ok(Command::Reconfigure(..)) - )); - assert!( - parse_as(false, &["reconfigure", "--persist"]) - .unwrap_err() - .contains("at least one setting") - ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]) - .unwrap_err() - .contains("1..1024") - ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]) - .unwrap_err() - .contains("whole number") - ); - assert!( - parse_as(false, &["reconfigure", "--preset", "shared"]) - .unwrap_err() - .contains("unknown preset") - ); - assert!( - parse_as( - false, - &["reconfigure", "--persist=yes", "--cpu-workers", "2"] - ) - .unwrap_err() - .contains("no value") - ); - assert!( - parse_as( - false, - &[ - "reconfigure", - "--gpu-budget-gib", - "20", - "--gpu-budget-gib", - "21" - ] - ) - .unwrap_err() - .contains("twice") - ); -} - -#[test] -fn api_bind_is_explicit_and_only_for_the_api() { - let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() else { - panic!() - }; - assert_eq!(options.ports.api, "0.0.0.0:8081"); - assert_eq!(options.ports.engine, "127.0.0.1:18766"); - assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); - assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); -} - -#[cfg(windows)] -#[test] -fn windows_has_no_systemd_modes_and_defaults_to_the_profile() { - assert!( - parse_as(false, &["up", "--mode", "system"]) - .unwrap_err() - .contains("--foreground") - ); - assert!(parse_as(false, &["up", "--mode=user"]).is_err()); - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert!( - options.dirs.state.ends_with("leleka/state"), - "{:?}", - options.dirs - ); - assert_eq!(options.mode, ModeChoice::Auto); - assert!(parse_as(false, &["up", "--assets", "D:\\models"]).is_ok()); - assert!(parse_as(false, &["up", "--assets", "models"]).is_err()); -} - -#[cfg(unix)] -#[test] -fn system_mode_needs_root() { - assert!( - parse_as(false, &["up", "--mode", "system"]) - .unwrap_err() - .contains("root") - ); - assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); - let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { - panic!() - }; - assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); -} - -#[test] -fn other_commands() { - assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); - assert!(matches!( - parse_as(false, &["profiles"]).unwrap(), - Command::Profiles(None) - )); - assert!(matches!( - parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), - Command::Profiles(Some(_)) - )); - let Command::Run { config, kar_fd } = parse_as( - false, - &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], - ) - .unwrap() else { - panic!() - }; - assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); - assert!(parse_as(false, &["run"]).is_err()); - assert!(parse_as(false, &["frobnicate"]).is_err()); - assert!(matches!( - parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), - Command::ExecInherit(_) - )); - assert!(matches!( - parse_as(false, &["seal-exec", "--file", "f", "--", "x"]).unwrap(), - Command::SealExec(_) - )); - assert!(matches!( - parse_as(false, &["seal-probe", "/x/y"]).unwrap(), - Command::SealProbe(_) - )); - assert!(parse_as(false, &["seal-probe"]).is_err()); -} +mod flags; +mod reconfigure_args; diff --git a/crates/deploy/src/cli/tests/flags.rs b/crates/deploy/src/cli/tests/flags.rs new file mode 100644 index 00000000..687fa7ec --- /dev/null +++ b/crates/deploy/src/cli/tests/flags.rs @@ -0,0 +1,264 @@ +//! Flags of every command: both forms, mistakes, defaults, presets and platform rules. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn logs_and_report_take_their_own_flags_and_the_locating_ones() { + let state = if cfg!(windows) { + "C:\\x\\state" + } else { + "/var/lib/x" + }; + let Ok(Command::Logs(options, logs)) = parse_as( + false, + &[ + "logs", + "--tail", + "20", + "--since=15m", + "--level", + "warn", + "--request", + "0b1c2d3e", + "--state-dir", + state, + ], + ) else { + panic!() + }; + assert_eq!( + ( + logs.tail, + logs.since.as_deref(), + logs.level.as_deref(), + logs.request.as_deref() + ), + (Some(20), Some("15m"), Some("warn"), Some("0b1c2d3e")) + ); + assert_eq!(options.dirs.state, PathBuf::from(state)); + assert!( + matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api")) + ); + assert!(parse_as(false, &["logs", "--tail", "0"]).is_err()); + assert!(parse_as(false, &["logs", "--tail", "x"]).is_err()); + assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err()); + assert!(parse_as(false, &["logs", "--bogus"]).is_err()); + let Ok(Command::Report(_, report)) = parse_as(false, &["report"]) else { + panic!() + }; + assert!( + !report.yes && report.last == 50 && report.out.is_none(), + "the opt-in is explicit" + ); + let Ok(Command::Report(_, report)) = + parse_as(false, &["report", "--yes", "--last", "200", "--out", "-"]) + else { + panic!() + }; + assert!(report.yes && report.last == 200 && report.out.as_deref() == Some("-")); + assert!(parse_as(false, &["report", "--last", "9999"]).is_err()); + assert!( + USAGE.contains("leleka logs") && USAGE.contains("leleka report") && USAGE.contains("--yes") + ); +} + +#[cfg(unix)] +#[test] +fn up_defaults_for_a_user() { + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert_eq!( + options.dirs.assets, + PathBuf::from("/home/para/.local/share/leleka/assets") + ); + assert_eq!(options.ports.api, "127.0.0.1:8081"); + assert!(options.fetch && options.install_cublas && !options.dry_run); + assert_eq!(options.mode, ModeChoice::Auto); + assert_eq!(options.timeout_s, 3600); +} + +#[test] +fn the_expert_profile_flags_parse_and_exclude_each_other() { + let Command::Up(options) = parse_as( + false, + &["up", "--expert-profile-file", "/mnt/usb/expert-profile.bin"], + ) + .unwrap() else { + panic!() + }; + assert_eq!( + options.expert_profile_file, + Some(PathBuf::from("/mnt/usb/expert-profile.bin")) + ); + assert!(!options.no_expert_tier); + let Command::Up(options) = parse_as(false, &["up", "--no-expert-tier"]).unwrap() else { + panic!() + }; + assert!(options.no_expert_tier && options.expert_profile_file.is_none()); + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert!(!options.no_expert_tier && options.expert_profile_file.is_none()); + let error = parse_as( + false, + &["up", "--no-expert-tier", "--expert-profile-file", "/x"], + ) + .unwrap_err(); + assert!(error.contains("contradict"), "{error}"); + assert!(parse_as(false, &["up", "--no-expert-tier=1"]).is_err()); +} + +#[test] +fn flags_accept_both_forms_and_reject_mistakes() { + let Command::Up(options) = parse_as( + false, + &[ + "up", + "--assets=/data/l", + "--gpu", + "1", + "--foreground", + "--dry-run", + "--json", + "--no-fetch", + "--api-port=9000", + ], + ) + .unwrap() else { + panic!() + }; + assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); + assert_eq!( + ( + options.gpu, + options.mode, + options.dry_run, + options.json, + options.fetch + ), + (1, ModeChoice::Foreground, true, true, false) + ); + assert_eq!(options.ports.api, "127.0.0.1:9000"); + for bad in [ + &["up", "--nope"][..], + &["up", "--gpu"], + &["up", "--dry-run", "--dry-run"], + &["up", "--dry-run=1"], + &["up", "--assets", "relative/dir"], + &["up", "--api-port", "80"], + &["up", "--api-port", "9000", "--engine-port", "9000"], + &["up", "--mode", "weird"], + &["up", "--foreground", "--mode", "user"], + &["up", "--gpu-budget-gib", "0"], + &["up", "--context-tokens", "999999"], + &["up", "--timeout-s", "0"], + ] { + assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); + } +} + +#[test] +fn the_resource_preset_comes_from_the_flag_then_the_environment() { + use crate::resources::Preset; + let preset = |args: &[&str]| match parse_as(false, args) { + Ok(Command::Up(options)) => Ok(options.preset), + Ok(_) => unreachable!(), + Err(message) => Err(message), + }; + assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); + assert_eq!( + preset(&["up", "--preset", "workstation"]), + Ok(Preset::Workstation) + ); + assert!( + preset(&["up", "--preset", "shared"]) + .unwrap_err() + .contains("unknown preset") + ); +} + +#[test] +fn api_bind_is_explicit_and_only_for_the_api() { + let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() else { + panic!() + }; + assert_eq!(options.ports.api, "0.0.0.0:8081"); + assert_eq!(options.ports.engine, "127.0.0.1:18766"); + assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); + assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); +} + +#[cfg(windows)] +#[test] +fn windows_has_no_systemd_modes_and_defaults_to_the_profile() { + assert!( + parse_as(false, &["up", "--mode", "system"]) + .unwrap_err() + .contains("--foreground") + ); + assert!(parse_as(false, &["up", "--mode=user"]).is_err()); + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert!( + options.dirs.state.ends_with("leleka/state"), + "{:?}", + options.dirs + ); + assert_eq!(options.mode, ModeChoice::Auto); + assert!(parse_as(false, &["up", "--assets", "D:\\models"]).is_ok()); + assert!(parse_as(false, &["up", "--assets", "models"]).is_err()); +} + +#[cfg(unix)] +#[test] +fn system_mode_needs_root() { + assert!( + parse_as(false, &["up", "--mode", "system"]) + .unwrap_err() + .contains("root") + ); + assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); + let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { + panic!() + }; + assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); +} + +#[test] +fn other_commands() { + assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); + assert!(matches!( + parse_as(false, &["profiles"]).unwrap(), + Command::Profiles(None) + )); + assert!(matches!( + parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), + Command::Profiles(Some(_)) + )); + let Command::Run { config, kar_fd } = parse_as( + false, + &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], + ) + .unwrap() else { + panic!() + }; + assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); + assert!(parse_as(false, &["run"]).is_err()); + assert!(parse_as(false, &["frobnicate"]).is_err()); + assert!(matches!( + parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), + Command::ExecInherit(_) + )); + assert!(matches!( + parse_as(false, &["seal-exec", "--file", "f", "--", "x"]).unwrap(), + Command::SealExec(_) + )); + assert!(matches!( + parse_as(false, &["seal-probe", "/x/y"]).unwrap(), + Command::SealProbe(_) + )); + assert!(parse_as(false, &["seal-probe"]).is_err()); +} diff --git a/crates/deploy/src/cli/tests/reconfigure_args.rs b/crates/deploy/src/cli/tests/reconfigure_args.rs new file mode 100644 index 00000000..d391aa39 --- /dev/null +++ b/crates/deploy/src/cli/tests/reconfigure_args.rs @@ -0,0 +1,132 @@ +//! The `reconfigure` arguments: settings, budget, preset and persist taken out of the `up` flags. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() { + let Ok(Command::Reconfigure(options, args)) = parse_as( + false, + &[ + "reconfigure", + "--context-tokens", + "65536", + "--prefix-cache-tail=reply", + "--prefix-cache-mib", + "20480", + "--spec-min-p", + "0.5", + "--state-dir", + "/var/lib/leleka/state", + ], + ) else { + panic!("reconfigure did not parse"); + }; + assert_eq!( + options.dirs.state, + std::path::PathBuf::from("/var/lib/leleka/state") + ); + assert!(!args.needs_restart() && !args.persist); + let value = serde_json::Value::Object(args.settings); + assert_eq!(value["context_tokens"], 65536); + assert_eq!(value["prefix_cache_tail"], "reply"); + assert_eq!(value["prefix_cache_mib"], "20480"); + assert_eq!(value["spec_min_p"], 0.5); + assert!( + parse_as(false, &["reconfigure"]) + .unwrap_err() + .contains("at least one setting") + ); + assert!( + parse_as(false, &["reconfigure", "--cpu-workers", "many"]) + .unwrap_err() + .contains("whole number") + ); + assert!( + parse_as( + false, + &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"] + ) + .unwrap_err() + .contains("twice") + ); +} + +#[test] +fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { + let Ok(Command::Reconfigure(options, args)) = parse_as( + false, + &[ + "reconfigure", + "--gpu-budget-gib", + "24", + "--preset=workstation", + "--persist", + "--context-tokens", + "65536", + "--state-dir", + "/s", + ], + ) else { + panic!("reconfigure did not parse"); + }; + assert!(args.needs_restart() && args.persist); + assert_eq!(args.gpu_budget_gib, Some(24)); + assert_eq!(args.preset, Some(crate::resources::Preset::Workstation)); + assert_eq!(args.settings["context_tokens"], 65536); + // they are the restart request, not `up` options: the service is located by the remaining flags only + assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); + assert_eq!(options.gpu_budget_gib, None); + assert_eq!(options.preset, crate::resources::Preset::Dedicated); + // the budget or the preset alone is a request; nothing at all is not + assert!(matches!( + parse_as(false, &["reconfigure", "--preset", "dedicated"]), + Ok(Command::Reconfigure(..)) + )); + assert!(matches!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), + Ok(Command::Reconfigure(..)) + )); + assert!( + parse_as(false, &["reconfigure", "--persist"]) + .unwrap_err() + .contains("at least one setting") + ); + assert!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]) + .unwrap_err() + .contains("1..1024") + ); + assert!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]) + .unwrap_err() + .contains("whole number") + ); + assert!( + parse_as(false, &["reconfigure", "--preset", "shared"]) + .unwrap_err() + .contains("unknown preset") + ); + assert!( + parse_as( + false, + &["reconfigure", "--persist=yes", "--cpu-workers", "2"] + ) + .unwrap_err() + .contains("no value") + ); + assert!( + parse_as( + false, + &[ + "reconfigure", + "--gpu-budget-gib", + "20", + "--gpu-budget-gib", + "21" + ] + ) + .unwrap_err() + .contains("twice") + ); +} diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index 2186b8cd..82bf96dc 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -264,174 +264,6 @@ impl RunConfig { config.validate()?; Ok(config) } - - /// Arguments of `leleka-inference`, in the order its parser requires (seven fixed pairs first, then the - /// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`]. - pub fn engine_args(&self, kar: KarArg) -> Vec { - let paths = self.paths(); - let profile = &self.profile; - let mut args: Vec = vec![ - "--listen".into(), - self.ports.engine.clone(), - "--token-env".into(), - RUNTIME_TOKEN_ENV.into(), - "--shard0".into(), - paths.shard(0).display().to_string(), - "--shard1".into(), - paths.shard(1).display().to_string(), - "--gpu".into(), - self.gpu.to_string(), - "--gpu-budget".into(), - profile.gpu_budget_bytes.to_string(), - "--context-tokens".into(), - profile.context_tokens.to_string(), - ]; - match kar { - KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), - KarArg::File => args.extend([ - "--kar-archive-file".into(), - paths.kar().display().to_string(), - ]), - KarArg::None => {} - } - if kar != KarArg::None { - args.extend([ - "--kar-provenance".into(), - paths.kar_provenance().display().to_string(), - ]); - } - args.extend([ - "--mtp-pack".into(), - paths.mtp_pack().display().to_string(), - "--mtp-staging".into(), - paths.mtp_staging().display().to_string(), - "--backend-mode".into(), - "original".into(), - "--expert-source".into(), - profile.expert_source.as_str().into(), - // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine - // drafts over the full 248k-row head, about 0.2 ms more per draft step. - "--mtp-rt-dir".into(), - paths.mtp_pack().display().to_string(), - ]); - if let Some(value) = profile.prefill_capacity { - args.extend(["--original-prefill-capacity".into(), value.to_string()]); - } - if let Some(value) = &profile.kv { - args.extend(["--kv".into(), value.clone()]); - } - if let Some(value) = profile.kv_resident { - args.extend(["--kv-resident".into(), value.to_string()]); - } - if let Some(value) = profile.prompt_cache { - args.extend(["--prompt-cache".into(), value.to_string()]); - } - if let Some(value) = profile.spec_min_p { - args.extend(["--spec-min-p".into(), value.to_string()]); - } - args.extend(profile.memory.args()); - if self.verify_stamps { - args.extend([ - "--verify-stamps".into(), - paths.engine_stamps().display().to_string(), - ]); - } - args - } - - /// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed. - /// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the - /// supervisor-side hash of the archive file is `leleka verify`'s other half). - pub fn verify_args(&self, rehash: bool) -> Vec { - let paths = self.paths(); - let mut args = self.engine_args(KarArg::File); - // Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use. - args.truncate(14); - if self.profile.kar_source == KarSource::File { - args.extend([ - "--kar-archive-file".into(), - paths.kar().display().to_string(), - "--kar-provenance".into(), - paths.kar_provenance().display().to_string(), - ]); - } - args.push("--verify-only".into()); - if rehash { - args.push("--verify-rehash".into()); - } - args.extend([ - "--verify-stamps".into(), - paths.engine_stamps().display().to_string(), - ]); - args - } - - pub fn kar_arg(&self) -> KarArg { - match self.profile.kar_source { - KarSource::Memfd => KarArg::Fd, - KarSource::File => KarArg::File, - KarSource::None => KarArg::None, - } - } - - /// The typed load's profile id: the KAR PLE form, or `kar_source: none`'s native-PLE form (`qwen4exp-native-mtp-v1`). - pub fn mtp_profile(&self) -> &'static str { - if self.profile.kar_source == KarSource::None { - NATIVE_MTP_PROFILE - } else { - MTP_PROFILE - } - } - - /// The engine's extra environment: profile switches, then the `up`-resolved ones (which win). - pub fn engine_environment(&self) -> BTreeMap { - let mut env = self.profile.memory.env(); - env.extend(self.profile.engine_env.clone()); - env.extend(self.engine_env.clone()); - env - } - - pub fn daemon_json(&self) -> Value { - json!({ - "schema_version": 1, - "listen": self.ports.daemon, - "token_env": GATEWAY_TOKEN_ENV, - "runtimes": [{ - "id": self.model_id, - "address": self.ports.engine, - "token_env": RUNTIME_TOKEN_ENV, - "artifact_digest": self.model_digest, - }] - }) - } - - pub fn strata_json(&self) -> Value { - let paths = self.paths(); - json!({ - "bind": self.ports.api, - "api_key_file": paths.api_key().display().to_string(), - "model": self.model_id, - "shutdown_grace_s": self.shutdown_grace_s, - "runtime": { - "address": self.ports.engine, - "token_env": RUNTIME_TOKEN_ENV, - "tokenizer_dir": paths.tokenizer_dir().display().to_string(), - "model": { - "family": "qwen4exp", - "architecture": "qwen4exp", - "weight_format": "gguf:iq3_s", - "artifact_digest": self.model_digest, - }, - "mode": {"type": "mtp", "profile_id": self.mtp_profile()}, - "max_context": self.profile.context_tokens, - // A request to an engine that stopped answering ends with an error instead of staying open. - "stall_timeout_s": self.request_limits.stall_timeout_s, - "generation_timeout_s": self.request_limits.generation_timeout_s, - // The control plane refuses a ceiling that is not below the context (the laptop profile has 8192). - "max_output_tokens": 32768u32.min(self.profile.context_tokens.saturating_sub(1).max(1)), - } - }) - } } /// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on @@ -500,294 +332,7 @@ pub fn merge_env(existing: &str, updates: &[(&str, String)]) -> String { pub const ENV_HEADER: &str = "# Written by `leleka up`; mode 0600; never commit. Two independent secrets and the loader path."; #[cfg(test)] -mod tests { - use super::*; +mod tests; - /// Command line as one string with `/` separators, so the expectations read the same on Windows. - fn flat(args: &[String]) -> String { - args.join(" ").replace('\\', "/") - } - - fn config(profile: &str) -> RunConfig { - let dirs = Dirs { - prefix: "/opt/leleka".into(), - state: "/var/lib/leleka/state".into(), - assets: "/data/leleka".into(), - }; - RunConfig::new( - &dirs, - Ports { - api: "127.0.0.1:8081".into(), - engine: "127.0.0.1:18766".into(), - daemon: "127.0.0.1:18080".into(), - }, - 0, - Profile::builtin(profile).unwrap(), - BTreeMap::new(), - ) - } - - #[test] - fn server_engine_command_matches_the_documented_one() { - let args = config("rtx5090-32g").engine_args(KarArg::Fd); - let text = flat(&args); - // docs/rust-runtime-run.md, step 1. - assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}"); - assert!(text.contains("--gpu 0 --gpu-budget 32819404800 --context-tokens 262144")); - assert!(text.contains("--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json")); - assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident --mtp-rt-dir /data/leleka/data/mtp-rt")); - // The engine parser reads the first 14 arguments positionally. - assert_eq!(args[..14].len(), 14); - assert_eq!(args[12], "--context-tokens"); - } - - #[test] - fn verify_arguments_keep_the_seven_pairs_and_choose_the_archive_by_profile() { - let server = config("rtx5090-32g"); - let args = server.verify_args(false); - assert_eq!(&args[..14], &server.engine_args(KarArg::Fd)[..14]); - let text = flat(&args); - assert!( - text.ends_with("--verify-only --verify-stamps /var/lib/leleka/state/stamps/engine"), - "{text}" - ); - assert!( - !text.contains("--kar-archive") && !text.contains("--backend-mode"), - "{text}" - ); - assert!( - server - .verify_args(true) - .contains(&"--verify-rehash".to_owned()) - ); - let laptop = flat(&config("rtx3080-16g").verify_args(true)); - assert!( - laptop - .contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance"), - "{laptop}" - ); - } - - #[test] - fn stamps_are_in_the_engine_command_unless_switched_off() { - let mut c = config("rtx5090-32g"); - assert!( - flat(&c.engine_args(KarArg::Fd)) - .contains("--verify-stamps /var/lib/leleka/state/stamps/engine") - ); - c.verify_stamps = false; - assert!( - !c.engine_args(KarArg::Fd) - .join(" ") - .contains("--verify-stamps") - ); - } - - #[test] - fn laptop_uses_the_file_source_the_256k_context_and_the_6144_chunk() { - let config = config("rtx3080-16g"); - assert_eq!(config.kar_arg(), KarArg::File); - let text = flat(&config.engine_args(config.kar_arg())); - assert!( - text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance") - ); - assert!(text.contains("--gpu-budget 16106127360 --context-tokens 262144")); - assert!(text.contains("--original-prefill-capacity 6144"), "{text}"); - assert!( - text.contains("--prefix-cache-tail prompt") - && text.contains("--prefix-cache-block 6144"), - "{text}" - ); - assert!(text.contains("--expert-source mapped")); - assert!(!text.contains("{FD}")); - } - - #[test] - fn the_gguf_ple_profile_passes_no_archive_and_loads_the_native_mtp_profile() { - let c = config("rtx5090-32g-gguf-ple"); - assert_eq!(c.kar_arg(), KarArg::None); - assert_eq!(c.mtp_profile(), "qwen4exp-native-mtp-v1"); - let args = c.engine_args(c.kar_arg()); - let text = flat(&args); - assert!( - !text.contains("--kar") && !text.contains("{FD}"), - "{text}" - ); - // the seven fixed pairs stay first and the rest follows without a gap - assert_eq!(args[12], "--context-tokens"); - assert_eq!(args[14], "--mtp-pack", "{text}"); - assert!(text.contains("--backend-mode original --expert-source resident"), "{text}"); - assert_eq!( - c.strata_json()["runtime"]["mode"]["profile_id"], - "qwen4exp-native-mtp-v1" - ); - let verify = flat(&c.verify_args(true)); - assert!(!verify.contains("--kar"), "{verify}"); - assert_eq!( - c.engine_environment().get("LELEKA_PLE_DIRECT").map(String::as_str), - Some("0") - ); - } - - #[test] - fn every_other_profile_keeps_its_archive_arguments_and_profile_id() { - for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx3080-16g"] { - let c = config(name); - assert_eq!(c.mtp_profile(), "qwen4exp-kar-ple-mtp-v1", "{name}"); - let text = flat(&c.engine_args(c.kar_arg())); - assert!( - text.contains("--kar-archive-") && text.contains("--kar-provenance"), - "{name}: {text}" - ); - assert!(!c.engine_environment().contains_key("LELEKA_PLE_DIRECT"), "{name}"); - } - } - - fn config_of(profile: &str) -> RunConfig { - config(profile) - } - - #[test] - fn generated_configs_are_consistent() { - let config = config("rtx5090-32g"); - let daemon = config.daemon_json(); - assert_eq!(daemon["runtimes"][0]["address"], "127.0.0.1:18766"); - assert_eq!(daemon["runtimes"][0]["artifact_digest"], MODEL_DIGEST); - let strata = config.strata_json(); - assert_eq!( - strata["runtime"]["address"], - daemon["runtimes"][0]["address"] - ); - assert_eq!( - strata["runtime"]["mode"]["profile_id"], - "qwen4exp-kar-ple-mtp-v1" - ); - assert_eq!( - strata["runtime"]["tokenizer_dir"] - .as_str() - .unwrap() - .replace('\\', "/"), - "/data/leleka/tokenizer-assets/tokenizer" - ); - assert_eq!(strata["runtime"]["max_context"], 262144); - assert_eq!(strata["runtime"]["max_output_tokens"], 32768); - // A context of 8K needs a ceiling below it, or `strata-next check-config` refuses the file (the laptop profile used to have one). - let mut small = config_of("rtx3080-16g"); - small.profile.context_tokens = 8192; - assert_eq!(small.strata_json()["runtime"]["max_output_tokens"], 8191); - assert_eq!( - config_of("rtx3080-16g").strata_json()["runtime"]["max_output_tokens"], - 32768 - ); - // No secret is ever part of a generated config. - let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config); - assert!(!text.to_ascii_lowercase().contains("secret")); - } - - #[test] - fn validation_rejects_non_loopback_and_future_schemas() { - // Only the API may be bound beyond loopback (container use); the others never. - let mut open_api = config("rtx5090-32g"); - open_api.ports.api = "0.0.0.0:8081".into(); - assert!(open_api.validate().is_ok()); - assert_eq!( - probe_address("0.0.0.0:8081"), - Some("127.0.0.1:8081".parse().unwrap()) - ); - assert_eq!( - probe_address("127.0.0.1:1"), - Some("127.0.0.1:1".parse().unwrap()) - ); - assert_eq!(probe_address("nonsense"), None); - let mut bad = config("rtx5090-32g"); - bad.ports.engine = "0.0.0.0:18766".into(); - assert!(bad.validate().unwrap_err().contains("loopback")); - let mut bad = config("rtx5090-32g"); - bad.schema_version = 9; - assert!(bad.validate().unwrap_err().contains("schema_version")); - assert!(config("rtx3080-16g").validate().is_ok()); - } - - #[test] - fn round_trip_through_json() { - let original = config("rtx3080-16g"); - let text = to_file_text(&original); - let back: RunConfig = serde_json::from_str(&text).unwrap(); - assert_eq!(back, original); - } - - #[test] - fn env_merge_keeps_secrets_and_updates_the_loader_path() { - let existing = "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/old\nOTHER=1\n"; - let merged = merge_env( - existing, - &[ - ("LD_LIBRARY_PATH", "/new".into()), - ("LELEKA_GATEWAY_TOKEN", "bbbb".into()), - ], - ); - assert_eq!( - merged, - "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/new\nOTHER=1\nLELEKA_GATEWAY_TOKEN=bbbb\n" - ); - assert_eq!( - merge_env(&merged, &[("LD_LIBRARY_PATH", "/new".into())]), - merged - ); - } - - #[test] - fn tokens_are_printable_distinct_and_long_enough() { - let (a, b) = (new_token().unwrap(), new_token().unwrap()); - assert_ne!(a, b); - assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c))); - } - - #[test] - fn the_server_profile_switches_reach_the_engine_environment_through_the_saved_config() { - // `up` saves the RunConfig (profile.engine_env inside) as leleka.json; `run` loads it and `start_engine` hands - // `engine_environment()` to the child (`child_env` sets every pair). The 5090 profile's engine_env must arrive. - let saved = serde_json::to_string(&config("rtx5090-32g")).unwrap(); - let loaded: RunConfig = serde_json::from_str(&saved).unwrap(); - let env = loaded.engine_environment(); - for (key, value) in [ - ("LELEKA_SM120_ATTN_DAILY_MTP", "1"), - ("LELEKA_ORIGINAL_SERVE_SEED", "off"), - ("LELEKA_CHAIN", "all"), - ] { - assert_eq!(env.get(key).map(String::as_str), Some(value), "{key}"); - } - assert!( - !config("rtx3080-16g") - .engine_environment() - .contains_key("LELEKA_SM120_ATTN_DAILY_MTP") - ); - // an operator's `engine_env` (the `up` resolved one) wins over the profile - let mut operator = loaded; - operator - .engine_env - .insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "0".into()); - assert_eq!( - operator.engine_environment()["LELEKA_SM120_ATTN_DAILY_MTP"], - "0" - ); - } - - #[test] - fn expert_environment_wins_over_the_profile() { - let mut config = config("rtx3080-16g"); - config - .profile - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.1".into()); - config - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.2".into()); - config - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".into(), "auto".into()); - let env = config.engine_environment(); - assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2"); - assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto"); - } -} +mod engine_launch; +mod service_documents; diff --git a/crates/deploy/src/config/engine_launch.rs b/crates/deploy/src/config/engine_launch.rs new file mode 100644 index 00000000..65322181 --- /dev/null +++ b/crates/deploy/src/config/engine_launch.rs @@ -0,0 +1,132 @@ +//! What the engine process is started with: arguments, verify arguments, archive argument, MTP profile and environment. + +#[allow(unused_imports)] +use super::*; + +impl RunConfig { + /// Arguments of `leleka-inference`, in the order its parser requires (seven fixed pairs first, then the + /// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`]. + pub fn engine_args(&self, kar: KarArg) -> Vec { + let paths = self.paths(); + let profile = &self.profile; + let mut args: Vec = vec![ + "--listen".into(), + self.ports.engine.clone(), + "--token-env".into(), + RUNTIME_TOKEN_ENV.into(), + "--shard0".into(), + paths.shard(0).display().to_string(), + "--shard1".into(), + paths.shard(1).display().to_string(), + "--gpu".into(), + self.gpu.to_string(), + "--gpu-budget".into(), + profile.gpu_budget_bytes.to_string(), + "--context-tokens".into(), + profile.context_tokens.to_string(), + ]; + match kar { + KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), + KarArg::File => args.extend([ + "--kar-archive-file".into(), + paths.kar().display().to_string(), + ]), + KarArg::None => {} + } + if kar != KarArg::None { + args.extend([ + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + ]); + } + args.extend([ + "--mtp-pack".into(), + paths.mtp_pack().display().to_string(), + "--mtp-staging".into(), + paths.mtp_staging().display().to_string(), + "--backend-mode".into(), + "original".into(), + "--expert-source".into(), + profile.expert_source.as_str().into(), + // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine + // drafts over the full 248k-row head, about 0.2 ms more per draft step. + "--mtp-rt-dir".into(), + paths.mtp_pack().display().to_string(), + ]); + if let Some(value) = profile.prefill_capacity { + args.extend(["--original-prefill-capacity".into(), value.to_string()]); + } + if let Some(value) = &profile.kv { + args.extend(["--kv".into(), value.clone()]); + } + if let Some(value) = profile.kv_resident { + args.extend(["--kv-resident".into(), value.to_string()]); + } + if let Some(value) = profile.prompt_cache { + args.extend(["--prompt-cache".into(), value.to_string()]); + } + if let Some(value) = profile.spec_min_p { + args.extend(["--spec-min-p".into(), value.to_string()]); + } + args.extend(profile.memory.args()); + if self.verify_stamps { + args.extend([ + "--verify-stamps".into(), + paths.engine_stamps().display().to_string(), + ]); + } + args + } + + /// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed. + /// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the + /// supervisor-side hash of the archive file is `leleka verify`'s other half). + pub fn verify_args(&self, rehash: bool) -> Vec { + let paths = self.paths(); + let mut args = self.engine_args(KarArg::File); + // Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use. + args.truncate(14); + if self.profile.kar_source == KarSource::File { + args.extend([ + "--kar-archive-file".into(), + paths.kar().display().to_string(), + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + ]); + } + args.push("--verify-only".into()); + if rehash { + args.push("--verify-rehash".into()); + } + args.extend([ + "--verify-stamps".into(), + paths.engine_stamps().display().to_string(), + ]); + args + } + + pub fn kar_arg(&self) -> KarArg { + match self.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + KarSource::None => KarArg::None, + } + } + + /// The typed load's profile id: the KAR PLE form, or `kar_source: none`'s native-PLE form (`qwen4exp-native-mtp-v1`). + pub fn mtp_profile(&self) -> &'static str { + if self.profile.kar_source == KarSource::None { + NATIVE_MTP_PROFILE + } else { + MTP_PROFILE + } + } + + /// The engine's extra environment: profile switches, then the `up`-resolved ones (which win). + pub fn engine_environment(&self) -> BTreeMap { + let mut env = self.profile.memory.env(); + env.extend(self.profile.engine_env.clone()); + env.extend(self.engine_env.clone()); + env + } +} diff --git a/crates/deploy/src/config/service_documents.rs b/crates/deploy/src/config/service_documents.rs new file mode 100644 index 00000000..fb827f2f --- /dev/null +++ b/crates/deploy/src/config/service_documents.rs @@ -0,0 +1,48 @@ +//! The JSON documents the service writes for the daemon and the gateway. + +#[allow(unused_imports)] +use super::*; + +impl RunConfig { + pub fn daemon_json(&self) -> Value { + json!({ + "schema_version": 1, + "listen": self.ports.daemon, + "token_env": GATEWAY_TOKEN_ENV, + "runtimes": [{ + "id": self.model_id, + "address": self.ports.engine, + "token_env": RUNTIME_TOKEN_ENV, + "artifact_digest": self.model_digest, + }] + }) + } + + pub fn strata_json(&self) -> Value { + let paths = self.paths(); + json!({ + "bind": self.ports.api, + "api_key_file": paths.api_key().display().to_string(), + "model": self.model_id, + "shutdown_grace_s": self.shutdown_grace_s, + "runtime": { + "address": self.ports.engine, + "token_env": RUNTIME_TOKEN_ENV, + "tokenizer_dir": paths.tokenizer_dir().display().to_string(), + "model": { + "family": "qwen4exp", + "architecture": "qwen4exp", + "weight_format": "gguf:iq3_s", + "artifact_digest": self.model_digest, + }, + "mode": {"type": "mtp", "profile_id": self.mtp_profile()}, + "max_context": self.profile.context_tokens, + // A request to an engine that stopped answering ends with an error instead of staying open. + "stall_timeout_s": self.request_limits.stall_timeout_s, + "generation_timeout_s": self.request_limits.generation_timeout_s, + // The control plane refuses a ceiling that is not below the context (the laptop profile has 8192). + "max_output_tokens": 32768u32.min(self.profile.context_tokens.saturating_sub(1).max(1)), + } + }) + } +} diff --git a/crates/deploy/src/config/tests.rs b/crates/deploy/src/config/tests.rs new file mode 100644 index 00000000..d53cf3e2 --- /dev/null +++ b/crates/deploy/src/config/tests.rs @@ -0,0 +1,294 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// Command line as one string with `/` separators, so the expectations read the same on Windows. +fn flat(args: &[String]) -> String { + args.join(" ").replace('\\', "/") +} + +fn config(profile: &str) -> RunConfig { + let dirs = Dirs { + prefix: "/opt/leleka".into(), + state: "/var/lib/leleka/state".into(), + assets: "/data/leleka".into(), + }; + RunConfig::new( + &dirs, + Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }, + 0, + Profile::builtin(profile).unwrap(), + BTreeMap::new(), + ) +} + +#[test] +fn server_engine_command_matches_the_documented_one() { + let args = config("rtx5090-32g").engine_args(KarArg::Fd); + let text = flat(&args); + // docs/rust-runtime-run.md, step 1. + assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}"); + assert!(text.contains("--gpu 0 --gpu-budget 32819404800 --context-tokens 262144")); + assert!(text.contains( + "--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json" + )); + assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident --mtp-rt-dir /data/leleka/data/mtp-rt")); + // The engine parser reads the first 14 arguments positionally. + assert_eq!(args[..14].len(), 14); + assert_eq!(args[12], "--context-tokens"); +} + +#[test] +fn verify_arguments_keep_the_seven_pairs_and_choose_the_archive_by_profile() { + let server = config("rtx5090-32g"); + let args = server.verify_args(false); + assert_eq!(&args[..14], &server.engine_args(KarArg::Fd)[..14]); + let text = flat(&args); + assert!( + text.ends_with("--verify-only --verify-stamps /var/lib/leleka/state/stamps/engine"), + "{text}" + ); + assert!( + !text.contains("--kar-archive") && !text.contains("--backend-mode"), + "{text}" + ); + assert!( + server + .verify_args(true) + .contains(&"--verify-rehash".to_owned()) + ); + let laptop = flat(&config("rtx3080-16g").verify_args(true)); + assert!( + laptop.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance"), + "{laptop}" + ); +} + +#[test] +fn stamps_are_in_the_engine_command_unless_switched_off() { + let mut c = config("rtx5090-32g"); + assert!( + flat(&c.engine_args(KarArg::Fd)) + .contains("--verify-stamps /var/lib/leleka/state/stamps/engine") + ); + c.verify_stamps = false; + assert!( + !c.engine_args(KarArg::Fd) + .join(" ") + .contains("--verify-stamps") + ); +} + +#[test] +fn laptop_uses_the_file_source_the_256k_context_and_the_6144_chunk() { + let config = config("rtx3080-16g"); + assert_eq!(config.kar_arg(), KarArg::File); + let text = flat(&config.engine_args(config.kar_arg())); + assert!(text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance")); + assert!(text.contains("--gpu-budget 16106127360 --context-tokens 262144")); + assert!(text.contains("--original-prefill-capacity 6144"), "{text}"); + assert!( + text.contains("--prefix-cache-tail prompt") && text.contains("--prefix-cache-block 6144"), + "{text}" + ); + assert!(text.contains("--expert-source mapped")); + assert!(!text.contains("{FD}")); +} + +#[test] +fn the_gguf_ple_profile_passes_no_archive_and_loads_the_native_mtp_profile() { + let c = config("rtx5090-32g-gguf-ple"); + assert_eq!(c.kar_arg(), KarArg::None); + assert_eq!(c.mtp_profile(), "qwen4exp-native-mtp-v1"); + let args = c.engine_args(c.kar_arg()); + let text = flat(&args); + assert!(!text.contains("--kar") && !text.contains("{FD}"), "{text}"); + // the seven fixed pairs stay first and the rest follows without a gap + assert_eq!(args[12], "--context-tokens"); + assert_eq!(args[14], "--mtp-pack", "{text}"); + assert!( + text.contains("--backend-mode original --expert-source resident"), + "{text}" + ); + assert_eq!( + c.strata_json()["runtime"]["mode"]["profile_id"], + "qwen4exp-native-mtp-v1" + ); + let verify = flat(&c.verify_args(true)); + assert!(!verify.contains("--kar"), "{verify}"); + assert_eq!( + c.engine_environment() + .get("LELEKA_PLE_DIRECT") + .map(String::as_str), + Some("0") + ); +} + +#[test] +fn every_other_profile_keeps_its_archive_arguments_and_profile_id() { + for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx3080-16g"] { + let c = config(name); + assert_eq!(c.mtp_profile(), "qwen4exp-kar-ple-mtp-v1", "{name}"); + let text = flat(&c.engine_args(c.kar_arg())); + assert!( + text.contains("--kar-archive-") && text.contains("--kar-provenance"), + "{name}: {text}" + ); + assert!( + !c.engine_environment().contains_key("LELEKA_PLE_DIRECT"), + "{name}" + ); + } +} + +fn config_of(profile: &str) -> RunConfig { + config(profile) +} + +#[test] +fn generated_configs_are_consistent() { + let config = config("rtx5090-32g"); + let daemon = config.daemon_json(); + assert_eq!(daemon["runtimes"][0]["address"], "127.0.0.1:18766"); + assert_eq!(daemon["runtimes"][0]["artifact_digest"], MODEL_DIGEST); + let strata = config.strata_json(); + assert_eq!( + strata["runtime"]["address"], + daemon["runtimes"][0]["address"] + ); + assert_eq!( + strata["runtime"]["mode"]["profile_id"], + "qwen4exp-kar-ple-mtp-v1" + ); + assert_eq!( + strata["runtime"]["tokenizer_dir"] + .as_str() + .unwrap() + .replace('\\', "/"), + "/data/leleka/tokenizer-assets/tokenizer" + ); + assert_eq!(strata["runtime"]["max_context"], 262144); + assert_eq!(strata["runtime"]["max_output_tokens"], 32768); + // A context of 8K needs a ceiling below it, or `strata-next check-config` refuses the file (the laptop profile used to have one). + let mut small = config_of("rtx3080-16g"); + small.profile.context_tokens = 8192; + assert_eq!(small.strata_json()["runtime"]["max_output_tokens"], 8191); + assert_eq!( + config_of("rtx3080-16g").strata_json()["runtime"]["max_output_tokens"], + 32768 + ); + // No secret is ever part of a generated config. + let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config); + assert!(!text.to_ascii_lowercase().contains("secret")); +} + +#[test] +fn validation_rejects_non_loopback_and_future_schemas() { + // Only the API may be bound beyond loopback (container use); the others never. + let mut open_api = config("rtx5090-32g"); + open_api.ports.api = "0.0.0.0:8081".into(); + assert!(open_api.validate().is_ok()); + assert_eq!( + probe_address("0.0.0.0:8081"), + Some("127.0.0.1:8081".parse().unwrap()) + ); + assert_eq!( + probe_address("127.0.0.1:1"), + Some("127.0.0.1:1".parse().unwrap()) + ); + assert_eq!(probe_address("nonsense"), None); + let mut bad = config("rtx5090-32g"); + bad.ports.engine = "0.0.0.0:18766".into(); + assert!(bad.validate().unwrap_err().contains("loopback")); + let mut bad = config("rtx5090-32g"); + bad.schema_version = 9; + assert!(bad.validate().unwrap_err().contains("schema_version")); + assert!(config("rtx3080-16g").validate().is_ok()); +} + +#[test] +fn round_trip_through_json() { + let original = config("rtx3080-16g"); + let text = to_file_text(&original); + let back: RunConfig = serde_json::from_str(&text).unwrap(); + assert_eq!(back, original); +} + +#[test] +fn env_merge_keeps_secrets_and_updates_the_loader_path() { + let existing = "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/old\nOTHER=1\n"; + let merged = merge_env( + existing, + &[ + ("LD_LIBRARY_PATH", "/new".into()), + ("LELEKA_GATEWAY_TOKEN", "bbbb".into()), + ], + ); + assert_eq!( + merged, + "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/new\nOTHER=1\nLELEKA_GATEWAY_TOKEN=bbbb\n" + ); + assert_eq!( + merge_env(&merged, &[("LD_LIBRARY_PATH", "/new".into())]), + merged + ); +} + +#[test] +fn tokens_are_printable_distinct_and_long_enough() { + let (a, b) = (new_token().unwrap(), new_token().unwrap()); + assert_ne!(a, b); + assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c))); +} + +#[test] +fn the_server_profile_switches_reach_the_engine_environment_through_the_saved_config() { + // `up` saves the RunConfig (profile.engine_env inside) as leleka.json; `run` loads it and `start_engine` hands + // `engine_environment()` to the child (`child_env` sets every pair). The 5090 profile's engine_env must arrive. + let saved = serde_json::to_string(&config("rtx5090-32g")).unwrap(); + let loaded: RunConfig = serde_json::from_str(&saved).unwrap(); + let env = loaded.engine_environment(); + for (key, value) in [ + ("LELEKA_SM120_ATTN_DAILY_MTP", "1"), + ("LELEKA_ORIGINAL_SERVE_SEED", "off"), + ("LELEKA_CHAIN", "all"), + ] { + assert_eq!(env.get(key).map(String::as_str), Some(value), "{key}"); + } + assert!( + !config("rtx3080-16g") + .engine_environment() + .contains_key("LELEKA_SM120_ATTN_DAILY_MTP") + ); + // an operator's `engine_env` (the `up` resolved one) wins over the profile + let mut operator = loaded; + operator + .engine_env + .insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "0".into()); + assert_eq!( + operator.engine_environment()["LELEKA_SM120_ATTN_DAILY_MTP"], + "0" + ); +} + +#[test] +fn expert_environment_wins_over_the_profile() { + let mut config = config("rtx3080-16g"); + config + .profile + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.1".into()); + config + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.2".into()); + config + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".into(), "auto".into()); + let env = config.engine_environment(); + assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2"); + assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto"); +} diff --git a/crates/deploy/src/expert_profile/tests.rs b/crates/deploy/src/expert_profile/tests.rs index 4dd10bbf..14a606e9 100644 --- a/crates/deploy/src/expert_profile/tests.rs +++ b/crates/deploy/src/expert_profile/tests.rs @@ -20,333 +20,6 @@ fn fixture_digest() -> String { sha256_hex(FIXTURE) } -#[test] -fn the_pinned_numbers_are_consistent() { - assert_eq!(PINNED_SHA256.len(), 64); - assert_eq!(PINNED_BYTES, 24 + 4 * 24_576 + 4 * 48 * 512); - assert!(SOURCES.iter().all(|url| url.starts_with("https://"))); - assert!(SOURCES[0].contains(UPSTREAM_COMMIT) && SOURCES[1].contains(UPSTREAM_COMMIT)); - assert_eq!(short_digest(PINNED_SHA256), "8f59b4aa...388975baf"); - assert_eq!(crate::plan::EXPERT_PROFILE_SHA256, PINNED_SHA256); -} - -#[test] -fn a_file_is_absent_valid_or_wrong() { - let dir = temp("state"); - let path = dir.join("p.bin"); - assert_eq!(file_state(&path, &fixture_digest()), FileState::Absent); - std::fs::write(&path, FIXTURE).unwrap(); - assert_eq!(file_state(&path, &fixture_digest()), FileState::Valid); - assert!( - matches!(file_state(&path, PINNED_SHA256), FileState::WrongDigest { actual } if actual == fixture_digest()) - ); - std::fs::write(&path, vec![0u8; (MAX_BYTES + 5) as usize]).unwrap(); - assert!(matches!( - file_state(&path, PINNED_SHA256), - FileState::WrongDigest { .. } - )); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn the_embedded_table_is_the_pinned_upstream_file() { - assert_eq!(EMBEDDED.len() as u64, PINNED_BYTES); - assert_eq!(sha256_hex(EMBEDDED), PINNED_SHA256); - assert_eq!(&EMBEDDED[..4], b"STRP"); - assert!(embedded_for(PINNED_SHA256).is_some()); - assert!(embedded_for(&fixture_digest()).is_none()); -} - -#[test] -fn the_embedded_table_is_installed_offline_before_any_download() { - let dir = temp("embedded"); - let dest = dir.join("data").join("expert-profile.bin"); - let mut never = |_: &str, _: &Path| -> Result<(), String> { - panic!("offline: the embedded table must be used before any download") - }; - let request = Request { - dest: &dest, - expected: PINNED_SHA256, - local: None, - embedded: embedded_for(PINNED_SHA256), - sources: &SOURCES, - }; - assert_eq!( - provision(&request, &mut never).unwrap(), - Outcome::Installed { - origin: EMBEDDED_ORIGIN.into(), - moved_aside: None - } - ); - assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); - assert!(!with_suffix(&dest, ".part").exists()); - assert_eq!( - provision(&request, &mut never).unwrap(), - Outcome::AlreadyPresent - ); - // an explicit file wins over the embedded table - let other = dir.join("other.bin"); - std::fs::write(&other, EMBEDDED).unwrap(); - let second = dir.join("second").join("p.bin"); - let outcome = provision( - &Request { - dest: &second, - local: Some(&other), - ..request - }, - &mut never, - ) - .unwrap(); - assert!(matches!(outcome, Outcome::Installed { origin, .. } if origin.ends_with("other.bin"))); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn an_embedded_table_that_fails_its_digest_falls_back_to_the_download() { - let dir = temp("embedded-bad"); - let dest = dir.join("expert-profile.bin"); - let digest = fixture_digest(); - let mut fetch = |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: Some(b"corrupted copy"), - sources: &["https://one.test/p.bin"], - }; - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::Installed { - origin: "https://one.test/p.bin".into(), - moved_aside: None - } - ); - // ... and without a source the failure names the embedded table - let _ = std::fs::remove_file(&dest); - let error = provision( - &Request { - sources: &[], - ..request - }, - &mut fetch, - ) - .unwrap_err(); - assert!( - error.contains("embedded") && error.contains("is not the expected"), - "{error}" - ); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() { - let dir = temp("download"); - let dest = dir.join("data").join("expert-profile.bin"); - let calls = RefCell::new(Vec::new()); - let mut fetch = |url: &str, part: &Path| { - calls.borrow_mut().push(url.to_owned()); - std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin", "https://two.test/p.bin"], - }; - let outcome = provision(&request, &mut fetch).unwrap(); - assert_eq!( - outcome, - Outcome::Installed { - origin: "https://one.test/p.bin".into(), - moved_aside: None - } - ); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - assert!( - !with_suffix(&dest, ".part").exists(), - "the staging file is gone" - ); - // Second run: nothing is fetched. - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::AlreadyPresent - ); - assert_eq!(calls.borrow().len(), 1); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_digest_mismatch_fails_closed_and_installs_nothing() { - let dir = temp("mismatch"); - let dest = dir.join("expert-profile.bin"); - let mut fetch = |_: &str, part: &Path| { - std::fs::write(part, b"an error page, not the table").map_err(|e| e.to_string()) - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin", "https://two.test/p.bin"], - }; - let error = provision(&request, &mut fetch).unwrap_err(); - assert!( - error.contains("one.test") - && error.contains("two.test") - && error.contains("is not the expected"), - "{error}" - ); - assert!( - error.contains("--expert-profile-file") && error.contains("--no-expert-tier"), - "{error}" - ); - assert!(!dest.exists() && !with_suffix(&dest, ".part").exists()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn the_next_source_is_tried_when_one_fails() { - let dir = temp("fallback"); - let dest = dir.join("expert-profile.bin"); - let mut fetch = |url: &str, part: &Path| { - if url.contains("down") { - Err("curl exited with 22".to_owned()) - } else { - std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) - } - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://down.test/p.bin", "https://up.test/p.bin"], - }; - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::Installed { - origin: "https://up.test/p.bin".into(), - moved_aside: None - } - ); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { - let dir = temp("local"); - let dest = dir.join("data").join("expert-profile.bin"); - let good = dir.join("good.bin"); - let bad = dir.join("bad.bin"); - std::fs::write(&good, FIXTURE).unwrap(); - std::fs::write(&bad, b"my own learned table").unwrap(); - let digest = fixture_digest(); - let mut never = |_: &str, _: &Path| -> Result<(), String> { - panic!("offline: no download may be attempted") - }; - let refused = provision( - &Request { - dest: &dest, - expected: &digest, - local: Some(&bad), - embedded: None, - sources: &["https://x.test/p"], - }, - &mut never, - ) - .unwrap_err(); - assert!( - refused.contains("only the pinned upstream table"), - "{refused}" - ); - assert!(!dest.exists()); - let outcome = provision( - &Request { - dest: &dest, - expected: &digest, - local: Some(&good), - embedded: None, - sources: &["https://x.test/p"], - }, - &mut never, - ) - .unwrap(); - assert!(matches!( - outcome, - Outcome::Installed { - moved_aside: None, - .. - } - )); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - let missing = provision( - &Request { - dest: &dir.join("other.bin"), - expected: &digest, - local: Some(&dir.join("nope.bin")), - embedded: None, - sources: &[], - }, - &mut never, - ) - .unwrap_err(); - assert!(missing.contains("--expert-profile-file"), "{missing}"); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_wrong_file_in_the_way_is_moved_aside_never_deleted() { - let dir = temp("aside"); - let dest = dir.join("expert-profile.bin"); - std::fs::write(&dest, b"learned by hand").unwrap(); - let mut fetch = |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); - let digest = fixture_digest(); - let outcome = provision( - &Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin"], - }, - &mut fetch, - ) - .unwrap(); - let Outcome::Installed { - moved_aside: Some(aside), - .. - } = outcome - else { - panic!("{outcome:?}") - }; - assert_eq!(std::fs::read(&aside).unwrap(), b"learned by hand"); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_custom_digest_without_sources_asks_for_the_file() { - let dir = temp("custom"); - let mut fetch = |_: &str, _: &Path| -> Result<(), String> { panic!("no sources") }; - let error = provision( - &Request { - dest: &dir.join("p.bin"), - expected: &fixture_digest(), - local: None, - embedded: None, - sources: &[], - }, - &mut fetch, - ) - .unwrap_err(); - assert!(error.contains("no download source"), "{error}"); - let _ = std::fs::remove_dir_all(dir); -} - fn config(assets: &Path, expert_tier: bool, with_env: bool) -> RunConfig { let mut profile = Profile::builtin("rtx5090-32g").unwrap(); profile.expert_profile_sha256 = Some(fixture_digest()); @@ -373,112 +46,6 @@ fn config(assets: &Path, expert_tier: bool, with_env: bool) -> RunConfig { config } -#[test] -fn the_report_says_on_with_the_digest_or_off_with_the_reason() { - let dir = temp("report"); - let path = dir.join("data").join("expert-profile.bin"); - // missing - let report = tier_report(&config(&dir, true, true), &dir); - assert!( - !report.on && !report.opted_out && report.reason.contains("is missing"), - "{report:?}" - ); - assert!( - report.line().starts_with("WARNING expert tier OFF"), - "{}", - report.line() - ); - // present and valid - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, FIXTURE).unwrap(); - let report = tier_report(&config(&dir, true, true), &dir); - assert!(report.on, "{report:?}"); - assert!( - report.line().starts_with("expert tier ON") - && report.line().contains(&short_digest(&fixture_digest())), - "{}", - report.line() - ); - // valid file but a configuration written without the switches - let report = tier_report(&config(&dir, true, false), &dir); - assert!( - !report.on && report.reason.contains("rerun `leleka up`"), - "{report:?}" - ); - // explicit opt-out - let report = tier_report(&config(&dir, false, false), &dir); - assert!( - !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), - "{report:?}" - ); - // a replaced file - std::fs::write(&path, b"something else").unwrap(); - let report = tier_report(&config(&dir, true, true), &dir); - assert!( - !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), - "{report:?}" - ); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_digest_observed_elsewhere_gives_the_same_report() { - let dir = temp("bridge"); - let cfg = config(&dir, true, true); - let shown = "/home/me/leleka/data/expert-profile.bin"; - let digest = fixture_digest(); - assert!( - tier_report_with(&cfg, shown, || FileState::from_digest( - Some(&digest), - &digest - )) - .on - ); - let missing = tier_report_with(&cfg, shown, || FileState::from_digest(None, &digest)); - assert!(!missing.on && missing.reason.contains(shown), "{missing:?}"); - let wrong = tier_report_with(&cfg, shown, || { - FileState::from_digest(Some("00ff"), &digest) - }); - assert!(!wrong.on && wrong.sha256.as_deref() == Some("00ff")); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_profile_without_a_tier_reports_off_and_the_engine_never_gets_a_bad_table() { - let dir = temp("env"); - let mut no_tier = config(&dir, true, true); - no_tier.profile.expert_profile = None; - assert!(!tier_report(&no_tier, &dir).on); - // valid file: the switches pass through - let path = dir.join("data").join("expert-profile.bin"); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, FIXTURE).unwrap(); - let cfg = config(&dir, true, true); - let (env, report) = start_environment(&cfg, &dir); - assert!(env.contains_key(PROFILE_ENV) && report.on); - // the file changed since `up`: the switches are dropped - std::fs::write(&path, b"changed").unwrap(); - let (env, report) = start_environment(&cfg, &dir); - assert!(!report.on && !env.contains_key(PROFILE_ENV) && !env.contains_key(SLOTS_ENV)); - let _ = std::fs::remove_dir_all(dir); -} - -/// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`. -#[test] -#[ignore = "network"] -fn pinned_sources_serve_the_pinned_table() { - let dir = temp("live"); - for url in SOURCES.iter().take(2) { - let out = dir.join("p.bin"); - let status = std::process::Command::new("curl") - .args(["-fsSL", "--proto", "=https", "--max-time", "60", "-o"]) - .arg(&out) - .arg(url) - .status() - .unwrap(); - assert!(status.success(), "{url}"); - assert_eq!(file_state(&out, PINNED_SHA256), FileState::Valid, "{url}"); - assert_eq!(std::fs::metadata(&out).unwrap().len(), PINNED_BYTES); - } - let _ = std::fs::remove_dir_all(dir); -} +mod embedded_table; +mod report; +mod sources; diff --git a/crates/deploy/src/expert_profile/tests/embedded_table.rs b/crates/deploy/src/expert_profile/tests/embedded_table.rs new file mode 100644 index 00000000..3d482747 --- /dev/null +++ b/crates/deploy/src/expert_profile/tests/embedded_table.rs @@ -0,0 +1,142 @@ +//! The pinned numbers and the table embedded in the binary: installed offline before any download. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_pinned_numbers_are_consistent() { + assert_eq!(PINNED_SHA256.len(), 64); + assert_eq!(PINNED_BYTES, 24 + 4 * 24_576 + 4 * 48 * 512); + assert!(SOURCES.iter().all(|url| url.starts_with("https://"))); + assert!(SOURCES[0].contains(UPSTREAM_COMMIT) && SOURCES[1].contains(UPSTREAM_COMMIT)); + assert_eq!(short_digest(PINNED_SHA256), "8f59b4aa...388975baf"); + assert_eq!(crate::plan::EXPERT_PROFILE_SHA256, PINNED_SHA256); +} + +#[test] +fn a_file_is_absent_valid_or_wrong() { + let dir = temp("state"); + let path = dir.join("p.bin"); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Absent); + std::fs::write(&path, FIXTURE).unwrap(); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Valid); + assert!( + matches!(file_state(&path, PINNED_SHA256), FileState::WrongDigest { actual } if actual == fixture_digest()) + ); + std::fs::write(&path, vec![0u8; (MAX_BYTES + 5) as usize]).unwrap(); + assert!(matches!( + file_state(&path, PINNED_SHA256), + FileState::WrongDigest { .. } + )); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_embedded_table_is_the_pinned_upstream_file() { + assert_eq!(EMBEDDED.len() as u64, PINNED_BYTES); + assert_eq!(sha256_hex(EMBEDDED), PINNED_SHA256); + assert_eq!(&EMBEDDED[..4], b"STRP"); + assert!(embedded_for(PINNED_SHA256).is_some()); + assert!(embedded_for(&fixture_digest()).is_none()); +} + +#[test] +fn the_embedded_table_is_installed_offline_before_any_download() { + let dir = temp("embedded"); + let dest = dir.join("data").join("expert-profile.bin"); + let mut never = |_: &str, _: &Path| -> Result<(), String> { + panic!("offline: the embedded table must be used before any download") + }; + let request = Request { + dest: &dest, + expected: PINNED_SHA256, + local: None, + embedded: embedded_for(PINNED_SHA256), + sources: &SOURCES, + }; + assert_eq!( + provision(&request, &mut never).unwrap(), + Outcome::Installed { + origin: EMBEDDED_ORIGIN.into(), + moved_aside: None + } + ); + assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); + assert!(!with_suffix(&dest, ".part").exists()); + assert_eq!( + provision(&request, &mut never).unwrap(), + Outcome::AlreadyPresent + ); + // an explicit file wins over the embedded table + let other = dir.join("other.bin"); + std::fs::write(&other, EMBEDDED).unwrap(); + let second = dir.join("second").join("p.bin"); + let outcome = provision( + &Request { + dest: &second, + local: Some(&other), + ..request + }, + &mut never, + ) + .unwrap(); + assert!(matches!(outcome, Outcome::Installed { origin, .. } if origin.ends_with("other.bin"))); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_embedded_table_that_fails_its_digest_falls_back_to_the_download() { + let dir = temp("embedded-bad"); + let dest = dir.join("expert-profile.bin"); + let digest = fixture_digest(); + let mut fetch = |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: Some(b"corrupted copy"), + sources: &["https://one.test/p.bin"], + }; + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::Installed { + origin: "https://one.test/p.bin".into(), + moved_aside: None + } + ); + // ... and without a source the failure names the embedded table + let _ = std::fs::remove_file(&dest); + let error = provision( + &Request { + sources: &[], + ..request + }, + &mut fetch, + ) + .unwrap_err(); + assert!( + error.contains("embedded") && error.contains("is not the expected"), + "{error}" + ); + let _ = std::fs::remove_dir_all(dir); +} + +/// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`. +#[test] +#[ignore = "network"] +fn pinned_sources_serve_the_pinned_table() { + let dir = temp("live"); + for url in SOURCES.iter().take(2) { + let out = dir.join("p.bin"); + let status = std::process::Command::new("curl") + .args(["-fsSL", "--proto", "=https", "--max-time", "60", "-o"]) + .arg(&out) + .arg(url) + .status() + .unwrap(); + assert!(status.success(), "{url}"); + assert_eq!(file_state(&out, PINNED_SHA256), FileState::Valid, "{url}"); + assert_eq!(std::fs::metadata(&out).unwrap().len(), PINNED_BYTES); + } + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/deploy/src/expert_profile/tests/report.rs b/crates/deploy/src/expert_profile/tests/report.rs new file mode 100644 index 00000000..bac5407d --- /dev/null +++ b/crates/deploy/src/expert_profile/tests/report.rs @@ -0,0 +1,94 @@ +//! The on/off report of the expert tier and the table the engine receives. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_report_says_on_with_the_digest_or_off_with_the_reason() { + let dir = temp("report"); + let path = dir.join("data").join("expert-profile.bin"); + // missing + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && !report.opted_out && report.reason.contains("is missing"), + "{report:?}" + ); + assert!( + report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + // present and valid + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!(report.on, "{report:?}"); + assert!( + report.line().starts_with("expert tier ON") + && report.line().contains(&short_digest(&fixture_digest())), + "{}", + report.line() + ); + // valid file but a configuration written without the switches + let report = tier_report(&config(&dir, true, false), &dir); + assert!( + !report.on && report.reason.contains("rerun `leleka up`"), + "{report:?}" + ); + // explicit opt-out + let report = tier_report(&config(&dir, false, false), &dir); + assert!( + !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), + "{report:?}" + ); + // a replaced file + std::fs::write(&path, b"something else").unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), + "{report:?}" + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_digest_observed_elsewhere_gives_the_same_report() { + let dir = temp("bridge"); + let cfg = config(&dir, true, true); + let shown = "/home/me/leleka/data/expert-profile.bin"; + let digest = fixture_digest(); + assert!( + tier_report_with(&cfg, shown, || FileState::from_digest( + Some(&digest), + &digest + )) + .on + ); + let missing = tier_report_with(&cfg, shown, || FileState::from_digest(None, &digest)); + assert!(!missing.on && missing.reason.contains(shown), "{missing:?}"); + let wrong = tier_report_with(&cfg, shown, || { + FileState::from_digest(Some("00ff"), &digest) + }); + assert!(!wrong.on && wrong.sha256.as_deref() == Some("00ff")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_profile_without_a_tier_reports_off_and_the_engine_never_gets_a_bad_table() { + let dir = temp("env"); + let mut no_tier = config(&dir, true, true); + no_tier.profile.expert_profile = None; + assert!(!tier_report(&no_tier, &dir).on); + // valid file: the switches pass through + let path = dir.join("data").join("expert-profile.bin"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let cfg = config(&dir, true, true); + let (env, report) = start_environment(&cfg, &dir); + assert!(env.contains_key(PROFILE_ENV) && report.on); + // the file changed since `up`: the switches are dropped + std::fs::write(&path, b"changed").unwrap(); + let (env, report) = start_environment(&cfg, &dir); + assert!(!report.on && !env.contains_key(PROFILE_ENV) && !env.contains_key(SLOTS_ENV)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/deploy/src/expert_profile/tests/sources.rs b/crates/deploy/src/expert_profile/tests/sources.rs new file mode 100644 index 00000000..2e49b595 --- /dev/null +++ b/crates/deploy/src/expert_profile/tests/sources.rs @@ -0,0 +1,213 @@ +//! Downloads, local files and wrong files: verified, installed or refused, never deleted. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() { + let dir = temp("download"); + let dest = dir.join("data").join("expert-profile.bin"); + let calls = RefCell::new(Vec::new()); + let mut fetch = |url: &str, part: &Path| { + calls.borrow_mut().push(url.to_owned()); + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let outcome = provision(&request, &mut fetch).unwrap(); + assert_eq!( + outcome, + Outcome::Installed { + origin: "https://one.test/p.bin".into(), + moved_aside: None + } + ); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + assert!( + !with_suffix(&dest, ".part").exists(), + "the staging file is gone" + ); + // Second run: nothing is fetched. + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::AlreadyPresent + ); + assert_eq!(calls.borrow().len(), 1); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_digest_mismatch_fails_closed_and_installs_nothing() { + let dir = temp("mismatch"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |_: &str, part: &Path| { + std::fs::write(part, b"an error page, not the table").map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let error = provision(&request, &mut fetch).unwrap_err(); + assert!( + error.contains("one.test") + && error.contains("two.test") + && error.contains("is not the expected"), + "{error}" + ); + assert!( + error.contains("--expert-profile-file") && error.contains("--no-expert-tier"), + "{error}" + ); + assert!(!dest.exists() && !with_suffix(&dest, ".part").exists()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_next_source_is_tried_when_one_fails() { + let dir = temp("fallback"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |url: &str, part: &Path| { + if url.contains("down") { + Err("curl exited with 22".to_owned()) + } else { + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + } + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://down.test/p.bin", "https://up.test/p.bin"], + }; + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::Installed { + origin: "https://up.test/p.bin".into(), + moved_aside: None + } + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { + let dir = temp("local"); + let dest = dir.join("data").join("expert-profile.bin"); + let good = dir.join("good.bin"); + let bad = dir.join("bad.bin"); + std::fs::write(&good, FIXTURE).unwrap(); + std::fs::write(&bad, b"my own learned table").unwrap(); + let digest = fixture_digest(); + let mut never = |_: &str, _: &Path| -> Result<(), String> { + panic!("offline: no download may be attempted") + }; + let refused = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&bad), + embedded: None, + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap_err(); + assert!( + refused.contains("only the pinned upstream table"), + "{refused}" + ); + assert!(!dest.exists()); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&good), + embedded: None, + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap(); + assert!(matches!( + outcome, + Outcome::Installed { + moved_aside: None, + .. + } + )); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let missing = provision( + &Request { + dest: &dir.join("other.bin"), + expected: &digest, + local: Some(&dir.join("nope.bin")), + embedded: None, + sources: &[], + }, + &mut never, + ) + .unwrap_err(); + assert!(missing.contains("--expert-profile-file"), "{missing}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_wrong_file_in_the_way_is_moved_aside_never_deleted() { + let dir = temp("aside"); + let dest = dir.join("expert-profile.bin"); + std::fs::write(&dest, b"learned by hand").unwrap(); + let mut fetch = |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); + let digest = fixture_digest(); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin"], + }, + &mut fetch, + ) + .unwrap(); + let Outcome::Installed { + moved_aside: Some(aside), + .. + } = outcome + else { + panic!("{outcome:?}") + }; + assert_eq!(std::fs::read(&aside).unwrap(), b"learned by hand"); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_custom_digest_without_sources_asks_for_the_file() { + let dir = temp("custom"); + let mut fetch = |_: &str, _: &Path| -> Result<(), String> { panic!("no sources") }; + let error = provision( + &Request { + dest: &dir.join("p.bin"), + expected: &fixture_digest(), + local: None, + embedded: None, + sources: &[], + }, + &mut fetch, + ) + .unwrap_err(); + assert!(error.contains("no download source"), "{error}"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/deploy/src/facts.rs b/crates/deploy/src/facts.rs index 56480aeb..f18eeab6 100644 --- a/crates/deploy/src/facts.rs +++ b/crates/deploy/src/facts.rs @@ -90,302 +90,10 @@ pub const WINDOWS_LIBRARIES: [(&str, &str); 3] = [ ]; #[cfg(windows)] -mod windows { - use super::*; - use leleka_memory::{ProcSource, RealProc}; - use std::{net::TcpListener, process::Command}; - - fn nvidia_smi() -> Option { - let path = std::env::var_os("PATH").unwrap_or_default(); - let mut dirs: Vec = std::env::split_paths(&path).collect(); - dirs.extend(WINDOWS_NVIDIA_SMI_DIRS.iter().map(PathBuf::from)); - find_in_dirs("nvidia-smi.exe", &dirs) - } - - fn query(smi: &Path, columns: &str) -> std::io::Result { - Command::new(smi) - .args([ - &format!("--query-gpu={columns}"), - "--format=csv,noheader,nounits", - ]) - .output() - } - - pub fn probe(request: &ProbeRequest) -> Facts { - let mut facts = Facts { - os: "windows".to_owned(), - arch: std::env::consts::ARCH.to_owned(), - hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), - ..Facts::default() - }; - // The memory governor's Win32 view, rendered as /proc/meminfo: available = available physical memory, - // swap = commit limit - RAM (`leleka-memory/src/winproc.rs`). - facts.memory = RealProc - .read("/proc/meminfo") - .map(|text| parse_meminfo(&text)) - .unwrap_or_default(); - facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); - facts.cpu_physical_cores = crate::winsys::physical_cores().unwrap_or(0); - - match nvidia_smi() { - None => { - facts.nvidia_smi_error = - Some("nvidia-smi.exe was not found in PATH or System32".into()) - } - Some(smi) => { - facts.nvidia_smi_found = true; - match query( - &smi, - "index,name,driver_version,memory.total,memory.free,compute_cap", - ) { - Ok(output) if output.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); - } - Ok(output) => { - match query(&smi, "index,name,driver_version,memory.total,memory.free") { - Ok(second) if second.status.success() => { - facts.gpus = - parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); - } - _ => { - let text = String::from_utf8_lossy(&output.stderr); - facts.nvidia_smi_error = Some( - text.lines() - .next() - .unwrap_or("nvidia-smi failed") - .to_owned(), - ); - } - } - } - Err(error) => facts.nvidia_smi_error = Some(error.to_string()), - } - } - } - - let mut library_dirs: Vec = request.extra_library_dirs.clone(); - if let Some(binary_dir) = &request.binary_dir { - library_dirs.push(binary_dir.clone()); - } - // Where `scripts/windows/fetch-cublas.ps1` puts the two cuBLAS DLLs. - // LOCALAPPDATA is not set in every kind of terminal or service session: fall back to the profile folder. - let local = std::env::var_os("LOCALAPPDATA") - .map(PathBuf::from) - .or_else(|| { - std::env::var_os("USERPROFILE") - .map(|home| PathBuf::from(home).join("AppData").join("Local")) - }); - if let Some(local) = local { - library_dirs.push(local.join("leleka").join("cublas").join("bin")); - } - if let Some(paths) = std::env::var_os("PATH") { - library_dirs - .extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); - } - if let Some(root) = std::env::var_os("SystemRoot") { - library_dirs.push(PathBuf::from(root).join("System32")); - } - for (soname, dll) in WINDOWS_LIBRARIES { - facts - .libs - .insert(soname.to_owned(), find_in_dirs(dll, &library_dirs)); - } - - for (key, path) in &request.dirs { - facts.dirs.insert( - key.clone(), - DirFact { - path: path.clone(), - free_bytes: crate::winsys::free_bytes(path), - fs_type: None, - }, - ); - } - for port in &request.ports { - if TcpListener::bind(("127.0.0.1", *port)).is_err() { - facts.busy_ports.push(*port); - } - } - if let Some(dir) = &request.binary_dir { - for name in &request.binaries { - facts - .binaries - .insert(name.clone(), dir.join(name).is_file()); - } - } - facts - } -} +mod windows; #[cfg(target_os = "linux")] -mod linux { - use super::*; - use std::{net::TcpListener, process::Command}; - - fn read(path: &str) -> String { - std::fs::read_to_string(path).unwrap_or_default() - } - - fn which(name: &str, extra: &[&str]) -> Option { - let path = std::env::var_os("PATH").unwrap_or_default(); - std::env::split_paths(&path) - .chain(extra.iter().map(PathBuf::from)) - .map(|dir| dir.join(name)) - .find(|candidate| candidate.is_file()) - } - - fn nearest_existing(path: &Path) -> PathBuf { - let mut current = path.to_path_buf(); - while !current.exists() { - if !current.pop() { - return PathBuf::from("/"); - } - } - current - } - - fn free_bytes(path: &Path) -> Option { - let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?; - Some(stat.f_bavail.saturating_mul(stat.f_frsize)) - } - - fn memfd_works() -> bool { - use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; - let Ok(fd) = memfd_create( - "leleka-preflight", - MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, - ) else { - return false; - }; - fcntl_add_seals(&fd, SealFlags::SEAL).is_ok() - } - - pub fn probe(request: &ProbeRequest) -> Facts { - let mut facts = Facts { - os: std::env::consts::OS.to_owned(), - arch: std::env::consts::ARCH.to_owned(), - root: rustix::process::geteuid().is_root(), - hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), - lab_holder: lab_holder_running(), - ..Facts::default() - }; - facts.wsl = is_wsl(&read("/proc/version")); - facts.memory = parse_meminfo(&read("/proc/meminfo")); - facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); - facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max")); - facts.systemd_system = Path::new("/run/systemd/system").is_dir(); - facts.proc_fd = Path::new("/proc/self/fd").is_dir(); - facts.memfd_ok = memfd_works(); - - let smi = which( - "nvidia-smi", - &["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"], - ); - match smi { - None => { - facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into()); - } - Some(smi) => { - facts.nvidia_smi_found = true; - match Command::new(smi) - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", - "--format=csv,noheader,nounits", - ]) - .output() - { - Ok(output) if output.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); - } - Ok(output) => { - // compute_cap is unknown to old drivers: retry without it. - let retry = Command::new("nvidia-smi") - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free", - "--format=csv,noheader,nounits", - ]) - .output(); - match retry { - Ok(second) if second.status.success() => { - facts.gpus = - parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); - } - _ => { - let text = String::from_utf8_lossy(&output.stderr); - facts.nvidia_smi_error = - Some(text.lines().next().unwrap_or("nvidia-smi failed").to_owned()); - } - } - } - Err(error) => facts.nvidia_smi_error = Some(error.to_string()), - } - } - } - - let ldconfig = Command::new("ldconfig") - .arg("-p") - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) - .unwrap_or_default(); - let mut library_dirs: Vec = request.extra_library_dirs.clone(); - if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") { - library_dirs - .extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); - } - for fixed in [ - "/usr/lib/wsl/lib", - "/usr/local/cuda/lib64", - "/usr/lib/x86_64-linux-gnu", - "/usr/lib64", - ] { - library_dirs.push(PathBuf::from(fixed)); - } - for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] { - facts.libs.insert( - soname.to_owned(), - find_library(soname, &library_dirs, &ldconfig), - ); - } - - for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { - facts.tools.insert( - tool.to_owned(), - which(tool, &["/usr/sbin", "/sbin"]).is_some(), - ); - } - - let mounts = read("/proc/mounts"); - for (key, path) in &request.dirs { - facts.dirs.insert( - key.clone(), - DirFact { - path: path.clone(), - free_bytes: free_bytes(path), - fs_type: fs_type_for(&mounts, &nearest_existing(path)), - }, - ); - } - for port in &request.ports { - if TcpListener::bind(("127.0.0.1", *port)).is_err() { - facts.busy_ports.push(*port); - } - } - if let Some(dir) = &request.binary_dir { - for name in &request.binaries { - facts - .binaries - .insert(name.clone(), is_executable(&dir.join(name))); - } - } - facts - } - - fn is_executable(path: &Path) -> bool { - use std::os::unix::fs::PermissionsExt; - path.metadata() - .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) - } -} +mod linux; #[cfg(test)] mod tests; diff --git a/crates/deploy/src/facts/linux.rs b/crates/deploy/src/facts/linux.rs new file mode 100644 index 00000000..b1e37412 --- /dev/null +++ b/crates/deploy/src/facts/linux.rs @@ -0,0 +1,170 @@ +//! Linux probe of the host facts: /proc, nvidia-smi, ports and the CUDA libraries in the loader path. + +use super::*; +use std::{net::TcpListener, process::Command}; + +fn read(path: &str) -> String { + std::fs::read_to_string(path).unwrap_or_default() +} + +fn which(name: &str, extra: &[&str]) -> Option { + let path = std::env::var_os("PATH").unwrap_or_default(); + std::env::split_paths(&path) + .chain(extra.iter().map(PathBuf::from)) + .map(|dir| dir.join(name)) + .find(|candidate| candidate.is_file()) +} + +fn nearest_existing(path: &Path) -> PathBuf { + let mut current = path.to_path_buf(); + while !current.exists() { + if !current.pop() { + return PathBuf::from("/"); + } + } + current +} + +fn free_bytes(path: &Path) -> Option { + let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?; + Some(stat.f_bavail.saturating_mul(stat.f_frsize)) +} + +fn memfd_works() -> bool { + use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; + let Ok(fd) = memfd_create( + "leleka-preflight", + MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, + ) else { + return false; + }; + fcntl_add_seals(&fd, SealFlags::SEAL).is_ok() +} + +pub fn probe(request: &ProbeRequest) -> Facts { + let mut facts = Facts { + os: std::env::consts::OS.to_owned(), + arch: std::env::consts::ARCH.to_owned(), + root: rustix::process::geteuid().is_root(), + hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), + lab_holder: lab_holder_running(), + ..Facts::default() + }; + facts.wsl = is_wsl(&read("/proc/version")); + facts.memory = parse_meminfo(&read("/proc/meminfo")); + facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max")); + facts.systemd_system = Path::new("/run/systemd/system").is_dir(); + facts.proc_fd = Path::new("/proc/self/fd").is_dir(); + facts.memfd_ok = memfd_works(); + + let smi = which( + "nvidia-smi", + &["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"], + ); + match smi { + None => { + facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into()); + } + Some(smi) => { + facts.nvidia_smi_found = true; + match Command::new(smi) + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", + "--format=csv,noheader,nounits", + ]) + .output() + { + Ok(output) if output.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); + } + Ok(output) => { + // compute_cap is unknown to old drivers: retry without it. + let retry = Command::new("nvidia-smi") + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free", + "--format=csv,noheader,nounits", + ]) + .output(); + match retry { + Ok(second) if second.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); + } + _ => { + let text = String::from_utf8_lossy(&output.stderr); + facts.nvidia_smi_error = Some( + text.lines() + .next() + .unwrap_or("nvidia-smi failed") + .to_owned(), + ); + } + } + } + Err(error) => facts.nvidia_smi_error = Some(error.to_string()), + } + } + } + + let ldconfig = Command::new("ldconfig") + .arg("-p") + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) + .unwrap_or_default(); + let mut library_dirs: Vec = request.extra_library_dirs.clone(); + if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") { + library_dirs.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); + } + for fixed in [ + "/usr/lib/wsl/lib", + "/usr/local/cuda/lib64", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib64", + ] { + library_dirs.push(PathBuf::from(fixed)); + } + for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] { + facts.libs.insert( + soname.to_owned(), + find_library(soname, &library_dirs, &ldconfig), + ); + } + + for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { + facts.tools.insert( + tool.to_owned(), + which(tool, &["/usr/sbin", "/sbin"]).is_some(), + ); + } + + let mounts = read("/proc/mounts"); + for (key, path) in &request.dirs { + facts.dirs.insert( + key.clone(), + DirFact { + path: path.clone(), + free_bytes: free_bytes(path), + fs_type: fs_type_for(&mounts, &nearest_existing(path)), + }, + ); + } + for port in &request.ports { + if TcpListener::bind(("127.0.0.1", *port)).is_err() { + facts.busy_ports.push(*port); + } + } + if let Some(dir) = &request.binary_dir { + for name in &request.binaries { + facts + .binaries + .insert(name.clone(), is_executable(&dir.join(name))); + } + } + facts +} + +fn is_executable(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + path.metadata() + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} diff --git a/crates/deploy/src/facts/windows.rs b/crates/deploy/src/facts/windows.rs new file mode 100644 index 00000000..e8997190 --- /dev/null +++ b/crates/deploy/src/facts/windows.rs @@ -0,0 +1,123 @@ +//! Windows probe of the host facts: nvidia-smi, memory, ports and the CUDA libraries on PATH. + +use super::*; +use leleka_memory::{ProcSource, RealProc}; +use std::{net::TcpListener, process::Command}; + +fn nvidia_smi() -> Option { + let path = std::env::var_os("PATH").unwrap_or_default(); + let mut dirs: Vec = std::env::split_paths(&path).collect(); + dirs.extend(WINDOWS_NVIDIA_SMI_DIRS.iter().map(PathBuf::from)); + find_in_dirs("nvidia-smi.exe", &dirs) +} + +fn query(smi: &Path, columns: &str) -> std::io::Result { + Command::new(smi) + .args([ + &format!("--query-gpu={columns}"), + "--format=csv,noheader,nounits", + ]) + .output() +} + +pub fn probe(request: &ProbeRequest) -> Facts { + let mut facts = Facts { + os: "windows".to_owned(), + arch: std::env::consts::ARCH.to_owned(), + hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), + ..Facts::default() + }; + // The memory governor's Win32 view, rendered as /proc/meminfo: available = available physical memory, + // swap = commit limit - RAM (`leleka-memory/src/winproc.rs`). + facts.memory = RealProc + .read("/proc/meminfo") + .map(|text| parse_meminfo(&text)) + .unwrap_or_default(); + facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + facts.cpu_physical_cores = crate::winsys::physical_cores().unwrap_or(0); + + match nvidia_smi() { + None => { + facts.nvidia_smi_error = Some("nvidia-smi.exe was not found in PATH or System32".into()) + } + Some(smi) => { + facts.nvidia_smi_found = true; + match query( + &smi, + "index,name,driver_version,memory.total,memory.free,compute_cap", + ) { + Ok(output) if output.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); + } + Ok(output) => { + match query(&smi, "index,name,driver_version,memory.total,memory.free") { + Ok(second) if second.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); + } + _ => { + let text = String::from_utf8_lossy(&output.stderr); + facts.nvidia_smi_error = Some( + text.lines() + .next() + .unwrap_or("nvidia-smi failed") + .to_owned(), + ); + } + } + } + Err(error) => facts.nvidia_smi_error = Some(error.to_string()), + } + } + } + + let mut library_dirs: Vec = request.extra_library_dirs.clone(); + if let Some(binary_dir) = &request.binary_dir { + library_dirs.push(binary_dir.clone()); + } + // Where `scripts/windows/fetch-cublas.ps1` puts the two cuBLAS DLLs. + // LOCALAPPDATA is not set in every kind of terminal or service session: fall back to the profile folder. + let local = std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .or_else(|| { + std::env::var_os("USERPROFILE") + .map(|home| PathBuf::from(home).join("AppData").join("Local")) + }); + if let Some(local) = local { + library_dirs.push(local.join("leleka").join("cublas").join("bin")); + } + if let Some(paths) = std::env::var_os("PATH") { + library_dirs.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); + } + if let Some(root) = std::env::var_os("SystemRoot") { + library_dirs.push(PathBuf::from(root).join("System32")); + } + for (soname, dll) in WINDOWS_LIBRARIES { + facts + .libs + .insert(soname.to_owned(), find_in_dirs(dll, &library_dirs)); + } + + for (key, path) in &request.dirs { + facts.dirs.insert( + key.clone(), + DirFact { + path: path.clone(), + free_bytes: crate::winsys::free_bytes(path), + fs_type: None, + }, + ); + } + for port in &request.ports { + if TcpListener::bind(("127.0.0.1", *port)).is_err() { + facts.busy_ports.push(*port); + } + } + if let Some(dir) = &request.binary_dir { + for name in &request.binaries { + facts + .binaries + .insert(name.clone(), dir.join(name).is_file()); + } + } + facts +} diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index e0d8a951..d7e28cb7 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -42,50 +42,6 @@ pub enum UnitScopeTag { User, } -impl UnitScopeTag { - pub fn scope(self) -> UnitScope { - match self { - UnitScopeTag::System => UnitScope::System, - UnitScopeTag::User => UnitScope::User, - } - } -} - -impl Mode { - pub fn label(self) -> &'static str { - match self { - Mode::Systemd(UnitScopeTag::System) => "systemd (system unit)", - Mode::Systemd(UnitScopeTag::User) => "systemd (user unit)", - Mode::Foreground => "foreground", - Mode::None => "prepare only", - } - } -} - -/// `--mode auto`: root with systemd gets a system unit, a user with a systemd user session a user unit, everything -/// else (WSL without systemd, containers) runs in the foreground. -pub fn resolve_mode(choice: ModeChoice, facts: &Facts, user_session: bool) -> Mode { - match choice { - ModeChoice::System => Mode::Systemd(UnitScopeTag::System), - ModeChoice::User => Mode::Systemd(UnitScopeTag::User), - ModeChoice::Foreground => Mode::Foreground, - ModeChoice::None => Mode::None, - ModeChoice::Auto => { - if facts.systemd_system && facts.tool("systemctl") { - if facts.root { - Mode::Systemd(UnitScopeTag::System) - } else if user_session { - Mode::Systemd(UnitScopeTag::User) - } else { - Mode::Foreground - } - } else { - Mode::Foreground - } - } - } -} - #[derive(Debug)] pub struct Context { pub opts: UpOptions, @@ -101,246 +57,6 @@ pub struct Context { pub needs: Needs, } -fn current_bin_dir() -> PathBuf { - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(Path::to_path_buf)) - .unwrap_or_else(|| PathBuf::from(".")) -} - -pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option { - use crate::expert_profile::{FileState, expected_digest, file_state}; - let relative = profile.expert_profile.as_ref()?; - Some( - match file_state(&assets.join(relative), expected_digest(profile)) { - FileState::Absent => ExpertProfileState::Absent, - FileState::Valid => ExpertProfileState::Valid, - FileState::WrongDigest { .. } => ExpertProfileState::WrongDigest, - }, - ) -} - -pub fn sha256_hex(bytes: &[u8]) -> String { - use sha2::{Digest, Sha256}; - hex::encode(Sha256::digest(bytes)) -} - -/// Is the supervisor of this state directory alive? (`run/status.json` names its pid.) -pub fn service_running(paths: &Paths) -> bool { - let Ok(text) = std::fs::read_to_string(paths.status_file()) else { - return false; - }; - let Ok(value) = serde_json::from_str::(&text) else { - return false; - }; - let pid = value.get("supervisor_pid").and_then(|v| v.as_u64()); - let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or(""); - matches!(pid, Some(pid) if process_alive(pid)) && !matches!(phase, "stopped" | "failed") -} - -#[cfg(not(windows))] -fn process_alive(pid: u64) -> bool { - Path::new(&format!("/proc/{pid}")).exists() -} - -#[cfg(windows)] -fn process_alive(pid: u64) -> bool { - u32::try_from(pid).is_ok_and(crate::winsys::process_alive) -} - -fn user_session_available(var: &dyn Fn(&str) -> Option) -> bool { - var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists()) -} - -pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context { - let paths = opts.dirs.paths(); - let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir); - let installed = paths.bin_dir(); - // Probe the source of the binaries, or the installed copy when the source has none (re-run after install). - let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { - bin_src.clone() - } else { - installed.clone() - }; - let mut extra_library_dirs: Vec = Vec::new(); - if let Some(dir) = &opts.cublas_dir { - extra_library_dirs.push(dir.clone()); - } else { - extra_library_dirs.push(paths.cublas_dir()); - } - let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] - .iter() - .filter_map(|p| p.rsplit(':').next()?.parse().ok()) - .collect(); - let request = ProbeRequest { - dirs: vec![ - ("assets".into(), opts.dirs.assets.clone()), - ("state".into(), opts.dirs.state.clone()), - ("prefix".into(), opts.dirs.prefix.clone()), - ], - ports, - binary_dir: Some(binary_dir.clone()), - binaries: BINARIES.iter().map(|b| b.to_string()).collect(), - extra_library_dirs, - }; - let facts = probe(&request); - let manifest = Manifest::find(&binary_dir); - let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu); - let mut profile = resolve(opts.profile.as_deref(), gpu); - if let Ok(p) = &mut profile { - if let Some(gib) = opts.gpu_budget_gib { - p.gpu_budget_bytes = gib << 30; - } - if let Some(tokens) = opts.context_tokens { - p.context_tokens = tokens; - } - if let Err(message) = p.validate() { - profile = Err(message); - } - } - let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { - ModeChoice::Foreground - } else { - opts.mode - }; - let mode = resolve_mode(choice, &facts, user_session_available(var)); - let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { - opts.service_user - .clone() - .unwrap_or_else(|| "leleka".to_owned()) - } else { - var("USER") - .or_else(|| var("LOGNAME")) - .unwrap_or_else(|| "root".to_owned()) - }; - let (shards, kar) = missing_asset_bytes(&paths); - let installed_same_dir = same_dir(&bin_src, &installed); - let mut needs = Needs { - gpu_index: opts.gpu, - assets_dir: opts.dirs.assets.clone(), - state_dir: opts.dirs.state.clone(), - prefix_dir: opts.dirs.prefix.clone(), - // Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not). - shard_bytes_missing: if opts.fetch && facts.os != "windows" { - shards - } else { - 0 - }, - kar_bytes_missing: if opts.fetch && facts.os != "windows" { - kar - } else { - 0 - }, - install_binaries: !installed_same_dir, - may_install_cublas: opts.install_cublas - && opts.cublas_dir.is_none() - && facts.os != "windows", - cublas_download_bytes: CUBLAS_BYTES, - wants_systemd: matches!(mode, Mode::Systemd(_)), - service_ports: vec![ - ("api".into(), port_of(&opts.ports.api)), - ("engine".into(), port_of(&opts.ports.engine)), - ("gateway".into(), port_of(&opts.ports.daemon)), - ], - require_binaries: true, - binary_has_sm86: manifest - .as_ref() - .and_then(|m| m.as_ref().ok()) - .map(Manifest::has_sm86), - service_running: service_running(&paths), - kar_fd_inherited: opts.kar_fd.is_some(), - api_bind_open: crate::config::probe_address(&opts.ports.api) - .is_some_and(|a| !a.ip().is_loopback()), - expert_profile: None, - resources: None, - }; - let (config, report) = match &mut profile { - Ok(p) => { - // `kar_source: none` never needs the archive (and never builds it) - if p.kar_source == KarSource::None { - needs.kar_bytes_missing = 0; - } - needs.expert_profile = if opts.no_expert_tier && p.expert_profile.is_some() { - Some(ExpertProfileState::OptedOut) - } else { - expert_profile_state(p, &opts.dirs.assets) - }; - let mut engine_env = BTreeMap::new(); - let base_profile = p.clone(); - // An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. - let planned_host = if opts.kar_fd.is_some() { - crate::resources::with_resident_bytes(&facts, p.memfd_bytes()) - } else { - facts.clone() - }; - let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); - crate::resources::apply( - &resources, - p, - &mut engine_env, - opts.gpu_budget_gib.is_some(), - ); - needs.resources = Some(resources); - // The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is - // provisioned by the `expert-profile` step, which runs before the configuration is written and blocks `up` - // when it cannot succeed. At every start the supervisor re-checks the digest (`expert_profile::start_environment`). - if needs.expert_profile != Some(ExpertProfileState::OptedOut) - && let Some(relative) = &p.expert_profile - { - engine_env.insert( - crate::expert_profile::SLOTS_ENV.to_owned(), - "auto".to_owned(), - ); - engine_env.insert( - crate::expert_profile::PROFILE_ENV.to_owned(), - opts.dirs.assets.join(relative).display().to_string(), - ); - } - let mut config = RunConfig::new( - &opts.dirs, - opts.ports.clone(), - opts.gpu, - p.clone(), - engine_env, - ); - config.preset = opts.preset; - config.expert_tier = !opts.no_expert_tier; - config.base_profile = Some(base_profile); - let report = evaluate(&facts, p, &needs); - (Some(config), Some(report)) - } - Err(_) => (None, None), - }; - Context { - opts: opts.clone(), - facts, - paths, - bin_src, - manifest, - profile, - mode, - service_user, - config, - report, - needs, - } -} - -fn port_of(address: &str) -> u16 { - address - .rsplit(':') - .next() - .and_then(|p| p.parse().ok()) - .unwrap_or(0) -} - -fn same_dir(a: &Path, b: &Path) -> bool { - match (a.canonicalize(), b.canonicalize()) { - (Ok(a), Ok(b)) => a == b, - _ => a == b, - } -} - /// What exists on disk now, reduced to the facts the plan needs. #[derive(Clone, Debug, Default)] pub struct FsState { @@ -369,25 +85,6 @@ pub enum StepState { Blocked(String), } -impl StepState { - pub fn tag(&self) -> &'static str { - match self { - StepState::Done(_) => "done", - StepState::Todo(_) => "todo", - StepState::Skip(_) => "skip", - StepState::Blocked(_) => "BLOCKED", - } - } - pub fn why(&self) -> &str { - match self { - StepState::Done(s) - | StepState::Todo(s) - | StepState::Skip(s) - | StepState::Blocked(s) => s, - } - } -} - #[derive(Clone, Debug, Serialize)] pub struct Step { pub id: &'static str, @@ -397,1087 +94,31 @@ pub struct Step { pub commands: Vec, } -fn step(id: &'static str, title: &str, state: StepState, commands: Vec) -> Step { - Step { - id, - title: title.to_owned(), - state, - commands, - } -} - -pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { - let paths = &ctx.paths; - let opts = &ctx.opts; - let sn = paths.bin("strata-next").display().to_string(); - let manifest_name = MANIFEST; - let windows = ctx.facts.os == "windows"; - let mut steps = Vec::new(); - - let pre_state = match &ctx.report { - Some(report) if report.failed() => StepState::Blocked(format!( - "{} check(s) failed", - report.count(crate::preflight::Level::Fail) - )), - Some(report) => StepState::Todo(format!( - "{} warning(s)", - report.count(crate::preflight::Level::Warn) - )), - None => StepState::Blocked(ctx.profile.as_ref().err().cloned().unwrap_or_default()), - }; - steps.push(step( - "preflight", - "host checks", - pre_state, - vec![if windows { - "nvidia-smi.exe, GlobalMemoryStatusEx, GetDiskFreeSpaceEx, DLL search, loopback ports" - .into() - } else { - "nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create".into() - }], - )); - - steps.push(step( - "layout", - "create directories", - if fs.dirs_exist { - StepState::Done("present".into()) - } else { - StepState::Todo("create state (0700), logs, run, stamps, assets".into()) - }, - vec![format!( - "mkdir -p {} {} {}", - opts.dirs.prefix.display(), - opts.dirs.state.display(), - opts.dirs.assets.display() - )], - )); - - steps.push(step( - "binaries", - "install the six runtime binaries", - if !fs.binaries_source_ok { - StepState::Blocked(format!( - "not all of {} are in {} or {}", - BINARIES.join(", "), - ctx.bin_src.display(), - paths.bin_dir().display() - )) - } else if fs.binaries_current { - StepState::Done(format!("{} is current", paths.bin_dir().display())) - } else { - StepState::Todo(format!( - "copy from {} (SHA-256 checked against MANIFEST.json when present)", - ctx.bin_src.display() - )) - }, - vec![format!( - "install {{{}}} -> {}", - BINARIES.join(","), - paths.bin_dir().display() - )], - )); - - steps.push(expert_profile_step(ctx)); - - let cublas_cmd = vec![ - format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"), - format!( - "tar -xJf libcublas-{CUBLAS_VERSION}.tar.xz -> {}", - paths.cublas_dir().display() - ), - ]; - steps.push(step( - "cublas", - "CUDA 12 cuBLAS for the PLE batch GEMM", - if fs.cublas_ready { - StepState::Done(if windows { - "cublas64_12.dll and cublasLt64_12.dll found".into() - } else { - "libcublas.so.12 and libcublasLt.so.12 found".into() - }) - } else if windows { - StepState::Blocked( - "cublas64_12.dll and cublasLt64_12.dll (CUDA 12.x) were not found; pass --cublas-dir DIR that holds them (a CUDA 12 toolkit's bin folder, or the NVIDIA cuBLAS 12 redistributable)".into(), - ) - } else if opts.cublas_dir.is_some() { - StepState::Blocked( - "--cublas-dir does not contain libcublas.so.12 and libcublasLt.so.12".into(), - ) - } else if opts.install_cublas { - StepState::Todo(format!( - "download the pinned {CUBLAS_VERSION} redistributable ({} MiB)", - CUBLAS_BYTES >> 20 - )) - } else { - StepState::Blocked("missing and --no-install-cublas was given".into()) - }, - if windows { Vec::new() } else { cublas_cmd }, - )); - - steps.push(step( - "secrets", - "service tokens and API key", - if fs.secrets_present { - StepState::Done("runtime.env and api-key exist (never rotated)".into()) - } else { - StepState::Todo("generate two tokens (0600) and run `strata-next api-key init`".into()) - }, - vec![format!( - "{sn} api-key init --file {}", - paths.api_key().display() - )], - )); - - let trusted = opts.trust_archive && fs.kar_present; - let kar_unused = ctx - .profile - .as_ref() - .is_ok_and(|p| p.kar_source == KarSource::None); - let kar_state = if kar_unused { - StepState::Skip( - "kar_source none (experimental): no archive is used, the PLE rows are read from the GGUF shard".into(), - ) - } else if windows { - if fs.kar_present { - StepState::Done(format!( - "{} bytes with its provenance file (the engine checks SHA-256 and CRCs at each load)", - ARCHIVE_BYTES - )) - } else { - StepState::Blocked(format!( - "{} (pinned length {ARCHIVE_BYTES}) and its .provenance.json must already be on the model volume; the Windows tool does not build the archive (build it in WSL and copy it, see docs/windows.md)", - paths.kar().display() - )) - } - } else if fs.kar_stamp_ok && !opts.reverify { - StepState::Done(format!("{} bytes, verified earlier", ARCHIVE_BYTES)) - } else if trusted { - StepState::Todo( - "accept the existing archive without the strict re-derivation (--trust-archive); the engine verifies its SHA-256 and every CRC at each load" - .into(), - ) - } else if !opts.fetch { - StepState::Blocked("--no-fetch given but the archive is missing or unverified".into()) - } else { - StepState::Todo( - "build the level-2 KAR archive (bounded memory, hours on a first run) or re-verify the existing one (strict, tens of minutes), then stamp it" - .into(), - ) - }; - let kar_runs_tool = matches!(kar_state, StepState::Todo(_)) && !trusted; - - let model_cmds = vec![ - format!( - "{sn} model fetch {manifest_name} --output {}", - paths.model_dir().display() - ), - format!( - "{sn} model verify {manifest_name} --output {}", - paths.model_dir().display() - ), - ]; - steps.push(step( - "model", - "fetch and verify the two IQ3_S GGUF shards", - if windows { - if ctx.needs.shard_bytes_missing == 0 && windows_shards_present(paths) { - StepState::Done("both shards are present with the pinned sizes (the engine hashes them at each load, or skips it with a verification stamp)".into()) - } else { - StepState::Blocked(format!( - "the two shards must already be in {} with their pinned sizes (the Windows tool does not download or build; copy them from the WSL volume, see docs/windows.md)", - paths.model_dir().display() - )) - } - } else if fs.shards_stamp_ok && !opts.reverify { - StepState::Done( - "verified earlier; sizes and mtimes unchanged (--reverify hashes again)".into(), - ) - } else if kar_runs_tool { - StepState::Todo( - "downloaded and verified inside the archive step (ensure-sharded-streamed fetches and verifies the shards first)" - .into(), - ) - } else if !opts.fetch { - if fs.shards_stamp_ok { - StepState::Todo("--no-fetch: verify only".into()) - } else { - StepState::Blocked( - "--no-fetch given but the shards are not verified yet; run without --no-fetch" - .into(), - ) - } - } else { - StepState::Todo(format!( - "{} still to download; resumable, SHA-256 of 83.6 GB", - gib_text(ctx.needs.shard_bytes_missing) - )) - }, - if windows { Vec::new() } else { model_cmds }, - )); - - let kar_cmd = vec![format!( - "{sn} model ensure-sharded-streamed {manifest_name} --source-dir {} --output {} --levels 2", - paths.model_dir().display(), - paths.kar().display() - )]; - steps.push(step( - "kar", - "KAR level-2 archive (+ provenance)", - kar_state, - if windows { Vec::new() } else { kar_cmd }, - )); - - steps.push(step( - "mtp-pack", - "MTP draft pack (data/mtp-rt)", - if let Some(src) = &opts.mtp_pack { - if fs.mtp_present { StepState::Done("present; --mtp-pack ignored".into()) } else { StepState::Todo(format!("import from {}", src.display())) } - } else if fs.mtp_present { - StepState::Done(format!("{} present", paths.mtp_pack().display())) - } else { - StepState::Blocked(format!("{} is missing and no --mtp-pack was given; the pack ({}) has no automated producer yet", paths.mtp_pack().display(), MTP_FILES.join(", "))) - }, - vec![format!("copy/unpack -> {}", paths.mtp_pack().display())], - )); - - steps.push(step( - "tokenizer", - "tokenizer assets for the API", - if fs.tokenizer_present { - StepState::Done("present".into()) - } else { - StepState::Todo("extract from shard 1".into()) - }, - vec![format!( - "{sn} model extract-tokenizer {} --output {}", - paths.shard(0).display(), - paths.tokenizer_root().display() - )], - )); - - steps.push(step( - "config", - "run configuration, gateway and API configs, environment file", - if fs.configs_current { - StepState::Done("up to date".into()) - } else { - StepState::Todo( - "write leleka.json, daemon.json, strata.json, profile.json, runtime.env".into(), - ) - }, - vec![format!( - "write {}/{{leleka,daemon,strata,profile}}.json runtime.env", - opts.dirs.state.display() - )], - )); - - match ctx.mode { - Mode::Systemd(scope) => { - steps.push(step( - "service", - "systemd unit", - if fs.unit_current { - StepState::Done("installed and enabled".into()) - } else { - StepState::Todo(format!( - "write {} unit, daemon-reload, enable", - if scope == UnitScopeTag::System { - "system" - } else { - "user" - } - )) - }, - vec![format!( - "systemctl {}enable {}", - if scope == UnitScopeTag::User { - "--user " - } else { - "" - }, - paths.unit_name() - )], - )); - steps.push(step( - "start", - "start the service", - if fs.service_ready { - StepState::Done("already ready".into()) - } else { - StepState::Todo( - "systemctl start (first start copies the archive and loads the model)" - .into(), - ) - }, - vec![format!( - "systemctl {}start {}", - if scope == UnitScopeTag::User { - "--user " - } else { - "" - }, - paths.unit_name() - )], - )); - } - Mode::Foreground => { - steps.push(step( - "service", - "systemd unit", - StepState::Skip("foreground mode".into()), - vec![], - )); - steps.push(step( - "start", - "run the supervisor in this terminal", - if fs.service_ready { - StepState::Done("a supervisor is already ready".into()) - } else { - StepState::Todo("leleka run (Ctrl-C drains and stops)".into()) - }, - vec![format!( - "{} run --config {}", - paths.bin("leleka").display(), - paths.run_config().display() - )], - )); - } - Mode::None => { - steps.push(step( - "service", - "systemd unit", - StepState::Skip("--mode none".into()), - vec![], - )); - steps.push(step( - "start", - "start the service", - StepState::Skip("--mode none".into()), - vec![], - )); - } - } - steps.push(step( - "ready", - "wait for readiness", - if matches!(ctx.mode, Mode::None) { - StepState::Skip("--mode none".into()) - } else if fs.service_ready { - StepState::Done("ready".into()) - } else { - StepState::Todo(format!( - "poll {} /ready for up to {} s", - opts.ports.api, opts.timeout_s - )) - }, - vec![format!("GET http://{}/ready", opts.ports.api)], - )); - steps -} - -/// The `expert-profile` step: the ranked VRAM expert tier's table is fetched (or installed from `--expert-profile-file`) and -/// verified before any large download, so that a failure costs seconds and the configuration is never written without it. -fn expert_profile_step(ctx: &Context) -> Step { - use crate::expert_profile::{ - PINNED_BYTES, PINNED_SHA256, SOURCES, expected_digest, short_digest, - }; - let id = "expert-profile"; - let title = "ranked VRAM expert profile (data/expert-profile.bin)"; - let opts = &ctx.opts; - let Ok(profile) = &ctx.profile else { - return step(id, title, StepState::Skip("no profile".into()), vec![]); - }; - let Some(relative) = &profile.expert_profile else { - return step( - id, - title, - StepState::Skip(format!("profile {} has no VRAM expert tier", profile.name)), - vec![], - ); - }; - let dest = opts.dirs.assets.join(relative); - let expected = expected_digest(profile); - let shown = short_digest(expected); - let embedded = crate::expert_profile::embedded_for(expected); - let flag_hint = "pass --expert-profile-file PATH (a copy of the upstream data/expert-profile.bin) or --no-expert-tier"; - let state = match &ctx.needs.expert_profile { - Some(ExpertProfileState::OptedOut) => StepState::Skip("--no-expert-tier: the VRAM expert tier is OFF (explicit opt-out; decode is much slower)".into()), - Some(ExpertProfileState::Valid) => StepState::Done(format!("{} has sha256 {shown}, tier ON", dest.display())), - Some(other) => { - let wrong = *other == ExpertProfileState::WrongDigest; - if let Some(file) = &opts.expert_profile_file { - StepState::Todo(format!( - "install {} (sha256 checked){}", - file.display(), - if wrong { "; the file in the way is moved aside, not deleted" } else { "" } - )) - } else if wrong { - StepState::Blocked(format!( - "{} does not have the expected sha256 {shown} and is not used. Move it aside and rerun (`up` then installs the pinned table), or {flag_hint}. A table of your own needs a profile with its own expert_profile_sha256 and a quality gate", - dest.display() - )) - } else if let Some(bytes) = embedded { - StepState::Todo(format!("install the {}-byte table embedded in this binary (sha256 {shown} checked; no network needed)", bytes.len())) - } else if !opts.fetch { - StepState::Blocked(format!("{} is missing and --no-fetch was given; {flag_hint}", dest.display())) - } else if expected != PINNED_SHA256 { - StepState::Blocked(format!("{} is missing and this profile pins another digest ({shown}), which has no download source; copy the file there or {flag_hint}", dest.display())) - } else if ctx.facts.os != "windows" && !ctx.facts.tool("curl") && !ctx.facts.tool("wget") { - StepState::Blocked(format!("{} is missing and neither curl nor wget is installed (apt install curl); {flag_hint}", dest.display())) - } else { - StepState::Todo(format!("download the {PINNED_BYTES}-byte table from the pinned upstream commit and check sha256 {shown}")) - } - } - None => StepState::Skip("no expert profile".into()), - }; - step( - id, - title, - state, - vec![if embedded.is_some() { - format!( - "write {0}.part from the embedded table, check sha256 {1}, rename to {0}", - dest.display(), - expected - ) - } else { - format!( - "curl -fsSL --proto =https -o {}.part {} (sha256 {})", - dest.display(), - SOURCES[0], - expected - ) - }], - ) -} - -/// Both shards exist with their pinned sizes. -fn windows_shards_present(paths: &Paths) -> bool { - crate::profile::SHARD_BYTES - .iter() - .enumerate() - .all(|(index, expected)| { - std::fs::metadata(paths.shard(index)).is_ok_and(|m| m.len() == *expected) - }) -} - -fn gib_text(bytes: u64) -> String { - format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) -} - -/// A human rendering of the plan, with the engine command the service will run. -pub fn render_plan(ctx: &Context, steps: &[Step]) -> String { - let mut out = String::new(); - out.push_str("plan:\n"); - for (index, step) in steps.iter().enumerate() { - out.push_str(&format!( - " {:>2}. [{:7}] {} - {}\n", - index + 1, - step.state.tag(), - step.title, - step.state.why() - )); - if matches!(step.state, StepState::Todo(_) | StepState::Blocked(_)) { - for command in &step.commands { - out.push_str(&format!(" $ {command}\n")); - } - } - } - if let Some(config) = &ctx.config { - let kar = match config.profile.kar_source { - KarSource::Memfd => KarArg::Fd, - KarSource::File => KarArg::File, - KarSource::None => KarArg::None, - }; - out.push_str(&format!( - "engine command the service runs:\n {} {}\n", - ctx.paths.bin("leleka-inference").display(), - config.engine_args(kar).join(" ") - )); - out.push_str(&format!( - " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", - config.profile.name, - config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, - config.profile.context_tokens, - config.profile.kar_source.as_str() - )); - let env = config.engine_environment(); - if !env.is_empty() { - out.push_str(&format!( - " engine environment: {}\n", - env.iter() - .map(|(k, v)| format!("{k}={v}")) - .collect::>() - .join(" ") - )); - } - } - out -} - #[cfg(test)] -mod tests { - use super::*; - use crate::{ - cli::{Command, Environment, parse}, - facts::{Gpu, Memory}, - layout::Dirs, - }; +mod tests; - fn options(extra: &[&str]) -> UpOptions { - let var = |_: &str| None; - let mut args: Vec = vec![ - "up".into(), - "--assets".into(), - "/data/leleka".into(), - "--state-dir".into(), - "/var/lib/leleka/state".into(), - "--prefix".into(), - "/opt/leleka".into(), - ]; - args.extend(extra.iter().map(|s| s.to_string())); - match parse( - &args, - &Environment { - root: true, - home: None, - var: &var, - }, - ) - .unwrap() - { - Command::Up(options) => options, - _ => unreachable!(), - } - } +mod expert_table_step; +mod gather_state; +mod host_steps; +mod model_steps; +mod render; +mod scope; +mod service_steps; +mod step_plan; +mod step_state; - fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { - let paths = opts.dirs.paths(); - let gpu = Gpu { - index: 0, - name: gpu_name.into(), - driver: "595.99.02".into(), - vram_total_mib: if sm == 120 { 32607 } else { 16384 }, - vram_free_mib: if sm == 120 { 32000 } else { 15500 }, - sm: Some(sm), - }; - let mut facts = Facts { - os: "linux".into(), - arch: "x86_64".into(), - gpus: vec![gpu.clone()], - memory: Memory { - total: 128 << 30, - available: 100 << 30, - swap_total: 0, - }, - root: true, - systemd_system: true, - proc_fd: true, - memfd_ok: true, - ..Facts::default() - }; - facts - .libs - .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("/x/libcublasLt.so.12".into()), - ); - facts - .libs - .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); - for tool in ["curl", "tar", "xz", "systemctl"] { - facts.tools.insert(tool.into(), true); - } - for name in BINARIES { - facts.binaries.insert(name.into(), true); - } - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - crate::facts::DirFact { - path: format!("/{key}").into(), - free_bytes: Some(2 << 40), - fs_type: Some("ext4".into()), - }, - ); - } - let profile = resolve(opts.profile.as_deref(), Some(&gpu)); - // A finished host by default: the pinned table is in place (tests of the other states set `needs.expert_profile`). - let expert_profile = profile - .as_ref() - .ok() - .filter(|p| p.expert_profile.is_some()) - .map(|_| { - if opts.no_expert_tier { - ExpertProfileState::OptedOut - } else { - ExpertProfileState::Valid - } - }); - let needs = Needs { - shard_bytes_missing: 83_617_662_656, - kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, - expert_profile, - ..Needs::default() - }; - let config = profile.as_ref().ok().map(|p| { - RunConfig::new( - &opts.dirs, - opts.ports.clone(), - 0, - p.clone(), - BTreeMap::new(), - ) - }); - let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs)); - Context { - service_user: "leleka".into(), - bin_src: "/src/bin".into(), - manifest: None, - profile, - mode, - facts, - paths, - config, - report, - needs, - opts, - } - } +pub use gather_state::{expert_profile_state, gather, service_running, sha256_hex}; +pub use render::render_plan; +pub use scope::resolve_mode; +pub use step_plan::plan_steps; - fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState { - &steps.iter().find(|s| s.id == id).unwrap().state - } - - #[test] - fn fresh_server_plans_every_step() { - let mut ctx = context( - options(&[]), - Mode::Systemd(UnitScopeTag::System), - "NVIDIA GeForce RTX 5090", - 120, - ); - ctx.needs.expert_profile = Some(ExpertProfileState::Absent); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - mtp_present: true, - ..FsState::default() - }, - ); - for id in [ - "layout", - "binaries", - "expert-profile", - "secrets", - "model", - "kar", - "tokenizer", - "config", - "service", - "start", - "ready", - ] { - assert!( - matches!(state_of(&steps, id), StepState::Todo(_)), - "{id}: {:?}", - state_of(&steps, id) - ); - } - let text = render_plan(&ctx, &steps).replace('\\', "/"); - assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}"); - assert!(text.contains("--kar-archive-fd {FD}"), "{text}"); - } - - #[test] - fn finished_deployment_is_done_except_nothing_to_do() { - let ctx = context( - options(&[]), - Mode::Systemd(UnitScopeTag::System), - "NVIDIA GeForce RTX 5090", - 120, - ); - let fs = FsState { - dirs_exist: true, - binaries_current: true, - binaries_source_ok: true, - cublas_ready: true, - secrets_present: true, - shards_stamp_ok: true, - kar_stamp_ok: true, - kar_present: true, - mtp_present: true, - tokenizer_present: true, - configs_current: true, - unit_current: true, - service_ready: true, - }; - let steps = plan_steps(&ctx, &fs); - for step in &steps { - if step.id != "preflight" { - assert!( - matches!(step.state, StepState::Done(_)), - "{} is {:?}", - step.id, - step.state - ); - } - } - // The plan of a finished deployment prints no commands (nothing will run). - assert!(!render_plan(&ctx, &steps[1..]).contains("$ ")); - } - - fn expert_step(extra: &[&str], state: ExpertProfileState) -> StepState { - let mut ctx = context( - options(extra), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - ctx.needs.expert_profile = Some(state); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - state_of(&steps, "expert-profile").clone() - } - - #[test] - fn the_expert_profile_is_planned_before_the_big_downloads() { - let ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let ids: Vec<&str> = plan_steps(&ctx, &FsState::default()) - .iter() - .map(|s| s.id) - .collect(); - let at = |id: &str| ids.iter().position(|i| *i == id).unwrap(); - assert!( - at("expert-profile") < at("model") - && at("expert-profile") < at("kar") - && at("expert-profile") < at("config"), - "{ids:?}" - ); - } - - #[test] - fn the_expert_profile_step_covers_every_state_and_never_stays_silent() { - // present with the pinned digest: nothing to do - assert!( - matches!(expert_step(&[], ExpertProfileState::Valid), StepState::Done(why) if why.contains("8f59b4aa...388975baf")) - ); - // missing: the table embedded in the binary is installed, with or without network - for extra in [&[][..], &["--no-fetch"]] { - let embedded = expert_step(extra, ExpertProfileState::Absent); - assert!( - matches!(&embedded, StepState::Todo(why) if why.contains("196632-byte table embedded") && why.contains("no network")), - "{embedded:?}" - ); - } - // the offline route installs from the local file - let local = expert_step( - &[ - "--no-fetch", - "--expert-profile-file", - "/mnt/usb/expert-profile.bin", - ], - ExpertProfileState::Absent, - ); - assert!( - matches!(&local, StepState::Todo(why) if why.contains("/mnt/usb/expert-profile.bin")), - "{local:?}" - ); - // a file with another digest is never used silently: blocked, or replaced (moved aside) on request - let wrong = expert_step(&[], ExpertProfileState::WrongDigest); - assert!( - matches!(&wrong, StepState::Blocked(why) if why.contains("is not used") && why.contains("Move it aside")), - "{wrong:?}" - ); - let replace = expert_step( - &["--expert-profile-file", "/x/p.bin"], - ExpertProfileState::WrongDigest, - ); - assert!( - matches!(&replace, StepState::Todo(why) if why.contains("moved aside")), - "{replace:?}" - ); - // the explicit opt-out is a Skip that says OFF - let off = expert_step(&["--no-expert-tier"], ExpertProfileState::OptedOut); - assert!( - matches!(&off, StepState::Skip(why) if why.contains("OFF")), - "{off:?}" - ); - } - - #[test] - fn only_a_profile_with_another_digest_needs_a_download_or_a_file() { - let mut ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - // no curl or wget: the embedded table does not need them - ctx.facts.tools.insert("curl".into(), false); - ctx.needs.expert_profile = Some(ExpertProfileState::Absent); - let steps = plan_steps(&ctx, &FsState::default()); - assert!( - matches!(state_of(&steps, "expert-profile"), StepState::Todo(why) if why.contains("embedded in this binary")) - ); - // a profile that pins another digest has no embedded table and no download source: blocked with both ways out - ctx.profile.as_mut().unwrap().expert_profile_sha256 = Some("ab".repeat(32)); - let steps = plan_steps(&ctx, &FsState::default()); - assert!( - matches!(state_of(&steps, "expert-profile"), StepState::Blocked(why) if why.contains("--expert-profile-file") && why.contains("--no-expert-tier")), - "{:?}", - state_of(&steps, "expert-profile") - ); - ctx.opts.expert_profile_file = Some("/x/p.bin".into()); - let steps = plan_steps(&ctx, &FsState::default()); - assert!(matches!( - state_of(&steps, "expert-profile"), - StepState::Todo(_) - )); - } - - #[test] - fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() { - let dir = std::env::temp_dir().join(format!("leleka-expert-gather-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let gathered = |extra: &[&str]| { - let mut args = vec!["--profile", "rtx5090-32g"]; - args.extend_from_slice(extra); - let mut opts = options(&args); - opts.dirs.assets = dir.clone(); - gather(&opts, &|_| None) - }; - // The table is absent: the configuration still names it (the step provisions it before the configuration is written). - let with_tier = gathered(&[]); - let config = with_tier.config.as_ref().unwrap(); - assert!( - config.expert_tier - && config - .engine_env - .contains_key(crate::expert_profile::PROFILE_ENV) - ); - assert_eq!( - with_tier.needs.expert_profile, - Some(ExpertProfileState::Absent) - ); - // The opt-out leaves the switches out and is recorded, so `status` can say "explicit opt-out". - let without = gathered(&["--no-expert-tier"]); - let config = without.config.as_ref().unwrap(); - assert!( - !config.expert_tier - && !config - .engine_env - .contains_key(crate::expert_profile::PROFILE_ENV) - ); - assert_eq!( - without.needs.expert_profile, - Some(ExpertProfileState::OptedOut) - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn missing_pieces_block_with_the_reason() { - let ctx = context( - options(&["--no-fetch", "--no-install-cublas"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps(&ctx, &FsState::default()); - assert!(matches!( - state_of(&steps, "binaries"), - StepState::Blocked(_) - )); - assert!(matches!(state_of(&steps, "cublas"), StepState::Blocked(_))); - assert!(matches!(state_of(&steps, "model"), StepState::Blocked(_))); - assert!(matches!(state_of(&steps, "kar"), StepState::Blocked(_))); - let mtp = state_of(&steps, "mtp-pack"); - assert!( - matches!(mtp, StepState::Blocked(_)) && mtp.why().contains("no automated producer"), - "{mtp:?}" - ); - assert!(matches!(state_of(&steps, "service"), StepState::Skip(_))); - } - - #[test] - fn the_archive_step_covers_the_shards_and_trust_archive_does_not() { - let ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!( - state_of(&steps, "model") - .why() - .contains("inside the archive step") - ); - let trusted = context( - options(&["--trust-archive"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &trusted, - &FsState { - binaries_source_ok: true, - kar_present: true, - ..FsState::default() - }, - ); - assert!( - !state_of(&steps, "model") - .why() - .contains("inside the archive step") - ); - assert!(state_of(&steps, "kar").why().contains("--trust-archive")); - // Trusting needs an archive to trust. - let steps = plan_steps( - &trusted, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!(!state_of(&steps, "kar").why().contains("--trust-archive")); - } - - #[test] - fn mtp_pack_import_is_a_todo_when_given() { - let ctx = context( - options(&["--mtp-pack", "/tmp/mtp-rt.tar.gz"]), - Mode::None, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!(matches!(state_of(&steps, "mtp-pack"), StepState::Todo(_))); - assert!(matches!(state_of(&steps, "start"), StepState::Skip(_))); - } - - #[test] - fn reverify_replans_verified_assets() { - let ctx = context( - options(&["--reverify"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - shards_stamp_ok: true, - kar_stamp_ok: true, - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!( - matches!(state_of(&steps, "model"), StepState::Todo(_)) - && matches!(state_of(&steps, "kar"), StepState::Todo(_)) - ); - } - - #[test] - fn laptop_plan_uses_the_file_engine_command() { - let ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 3080 Laptop GPU", - 86, - ); - let steps = plan_steps(&ctx, &FsState::default()); - let text = render_plan(&ctx, &steps).replace('\\', "/"); - assert!( - text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar") - && text.contains("--context-tokens 262144"), - "{text}" - ); - assert!(text.contains("rtx3080-16g")); - } - - #[test] - fn mode_resolution() { - let mut facts = Facts { - root: true, - systemd_system: true, - ..Facts::default() - }; - facts.tools.insert("systemctl".into(), true); - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, false), - Mode::Systemd(UnitScopeTag::System) - ); - facts.root = false; - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, true), - Mode::Systemd(UnitScopeTag::User) - ); - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, false), - Mode::Foreground - ); - facts.systemd_system = false; - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, true), - Mode::Foreground - ); - assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None); - let _ = Dirs { - prefix: "/".into(), - state: "/".into(), - assets: "/".into(), - }; - } - - #[test] - fn expert_profile_needs_the_pinned_digest() { - let dir = std::env::temp_dir().join(format!("leleka-expert-{}", std::process::id())); - std::fs::create_dir_all(dir.join("data")).unwrap(); - let profile = Profile::builtin("rtx3080-16g").unwrap(); - assert_eq!( - expert_profile_state(&profile, &dir), - Some(ExpertProfileState::Absent) - ); - std::fs::write(dir.join("data/expert-profile.bin"), b"not the profile").unwrap(); - assert_eq!( - expert_profile_state(&profile, &dir), - Some(ExpertProfileState::WrongDigest) - ); - // the server profile names the same shipped routing profile (default digest) - assert_eq!( - expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir), - Some(ExpertProfileState::WrongDigest) - ); - std::fs::remove_dir_all(dir).unwrap(); - } -} +use expert_table_step::expert_profile_step; +use host_steps::{ + binaries_step, cublas_step, layout_step, preflight_step, secrets_step, strata_next, +}; +use model_steps::{ + config_step, kar_state, kar_step, model_step, mtp_pack_step, tokenizer_step, trusts_archive, +}; +use service_steps::{ready_step, service_steps}; +use step_plan::{gib_text, windows_shards_present}; +use step_state::step; diff --git a/crates/deploy/src/plan/expert_table_step.rs b/crates/deploy/src/plan/expert_table_step.rs new file mode 100644 index 00000000..728c67fc --- /dev/null +++ b/crates/deploy/src/plan/expert_table_step.rs @@ -0,0 +1,132 @@ +//! The `expert-profile` step: the ranked VRAM expert tier's table is fetched (or installed from +//! `--expert-profile-file`) and verified before any large download, so that a failure costs seconds and the +//! configuration is never written without it. + +use super::*; +use crate::expert_profile::{ + PINNED_BYTES, PINNED_SHA256, SOURCES, embedded_for, expected_digest, short_digest, +}; +use std::path::Path; + +const ID: &str = "expert-profile"; +const TITLE: &str = "ranked VRAM expert profile (data/expert-profile.bin)"; +const FLAG_HINT: &str = "pass --expert-profile-file PATH (a copy of the upstream data/expert-profile.bin) \ + or --no-expert-tier"; + +pub(super) fn expert_profile_step(ctx: &Context) -> Step { + let Ok(profile) = &ctx.profile else { + return step(ID, TITLE, StepState::Skip("no profile".into()), vec![]); + }; + let Some(relative) = &profile.expert_profile else { + let why = format!("profile {} has no VRAM expert tier", profile.name); + return step(ID, TITLE, StepState::Skip(why), vec![]); + }; + let dest = ctx.opts.dirs.assets.join(relative); + let expected = expected_digest(profile); + let embedded = embedded_for(expected); + let state = tier_state(ctx, &dest, expected, embedded); + step( + ID, + TITLE, + state, + vec![install_command(&dest, expected, embedded.is_some())], + ) +} + +fn tier_state(ctx: &Context, dest: &Path, expected: &str, embedded: Option<&[u8]>) -> StepState { + let shown = short_digest(expected); + match &ctx.needs.expert_profile { + Some(ExpertProfileState::OptedOut) => StepState::Skip( + "--no-expert-tier: the VRAM expert tier is OFF (explicit opt-out; decode is much slower)".into(), + ), + Some(ExpertProfileState::Valid) => { + StepState::Done(format!("{} has sha256 {shown}, tier ON", dest.display())) + } + Some(other) => { + let wrong = *other == ExpertProfileState::WrongDigest; + missing_table_state(ctx, dest, (expected, &shown), embedded, wrong) + } + None => StepState::Skip("no expert profile".into()), + } +} + +/// The table is absent or has the wrong digest; `digests` is the expected digest and its short form. +fn missing_table_state( + ctx: &Context, + dest: &Path, + digests: (&str, &str), + embedded: Option<&[u8]>, + wrong: bool, +) -> StepState { + let opts = &ctx.opts; + let (expected, shown) = digests; + if let Some(file) = &opts.expert_profile_file { + let aside = if wrong { + "; the file in the way is moved aside, not deleted" + } else { + "" + }; + StepState::Todo(format!( + "install {} (sha256 checked){aside}", + file.display() + )) + } else if wrong { + wrong_digest_state(dest, shown) + } else if let Some(bytes) = embedded { + StepState::Todo(format!( + "install the {}-byte table embedded in this binary (sha256 {shown} checked; no network needed)", + bytes.len() + )) + } else { + download_state(ctx, dest, expected, shown) + } +} + +fn wrong_digest_state(dest: &Path, shown: &str) -> StepState { + StepState::Blocked(format!( + "{} does not have the expected sha256 {shown} and is not used. Move it aside and rerun \ + (`up` then installs the pinned table), or {FLAG_HINT}. A table of your own needs a profile with \ + its own expert_profile_sha256 and a quality gate", + dest.display() + )) +} + +/// No file and no embedded table: what is left is a download, if one is possible. +fn download_state(ctx: &Context, dest: &Path, expected: &str, shown: &str) -> StepState { + let path = dest.display(); + if !ctx.opts.fetch { + StepState::Blocked(format!( + "{path} is missing and --no-fetch was given; {FLAG_HINT}" + )) + } else if expected != PINNED_SHA256 { + StepState::Blocked(format!( + "{path} is missing and this profile pins another digest ({shown}), which has no download source; \ + copy the file there or {FLAG_HINT}" + )) + } else if ctx.facts.os != "windows" && !ctx.facts.tool("curl") && !ctx.facts.tool("wget") { + StepState::Blocked(format!( + "{path} is missing and neither curl nor wget is installed (apt install curl); {FLAG_HINT}" + )) + } else { + StepState::Todo(format!( + "download the {PINNED_BYTES}-byte table from the pinned upstream commit and check sha256 {shown}" + )) + } +} + +fn install_command(dest: &Path, expected: &str, embedded: bool) -> String { + if embedded { + format!( + "write {0}.part from the embedded table, check sha256 {1}, rename to {0}", + dest.display(), + expected + ) + } else { + format!( + "curl -fsSL --proto =https -o {}.part {} (sha256 {})", + dest.display(), + SOURCES[0], + expected + ) + } +} diff --git a/crates/deploy/src/plan/gather_state.rs b/crates/deploy/src/plan/gather_state.rs new file mode 100644 index 00000000..e650fc38 --- /dev/null +++ b/crates/deploy/src/plan/gather_state.rs @@ -0,0 +1,244 @@ +//! Read the host state (installed files, service, expert profile) into the planning context. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn current_bin_dir() -> PathBuf { + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)) + .unwrap_or_else(|| PathBuf::from(".")) +} + +pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option { + use crate::expert_profile::{FileState, expected_digest, file_state}; + let relative = profile.expert_profile.as_ref()?; + Some( + match file_state(&assets.join(relative), expected_digest(profile)) { + FileState::Absent => ExpertProfileState::Absent, + FileState::Valid => ExpertProfileState::Valid, + FileState::WrongDigest { .. } => ExpertProfileState::WrongDigest, + }, + ) +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(bytes)) +} + +/// Is the supervisor of this state directory alive? (`run/status.json` names its pid.) +pub fn service_running(paths: &Paths) -> bool { + let Ok(text) = std::fs::read_to_string(paths.status_file()) else { + return false; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return false; + }; + let pid = value.get("supervisor_pid").and_then(|v| v.as_u64()); + let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or(""); + matches!(pid, Some(pid) if process_alive(pid)) && !matches!(phase, "stopped" | "failed") +} + +#[cfg(not(windows))] +pub(super) fn process_alive(pid: u64) -> bool { + Path::new(&format!("/proc/{pid}")).exists() +} + +#[cfg(windows)] +pub(super) fn process_alive(pid: u64) -> bool { + u32::try_from(pid).is_ok_and(crate::winsys::process_alive) +} + +pub(super) fn user_session_available(var: &dyn Fn(&str) -> Option) -> bool { + var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists()) +} + +pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context { + let paths = opts.dirs.paths(); + let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir); + let installed = paths.bin_dir(); + // Probe the source of the binaries, or the installed copy when the source has none (re-run after install). + let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { + bin_src.clone() + } else { + installed.clone() + }; + let mut extra_library_dirs: Vec = Vec::new(); + if let Some(dir) = &opts.cublas_dir { + extra_library_dirs.push(dir.clone()); + } else { + extra_library_dirs.push(paths.cublas_dir()); + } + let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] + .iter() + .filter_map(|p| p.rsplit(':').next()?.parse().ok()) + .collect(); + let request = ProbeRequest { + dirs: vec![ + ("assets".into(), opts.dirs.assets.clone()), + ("state".into(), opts.dirs.state.clone()), + ("prefix".into(), opts.dirs.prefix.clone()), + ], + ports, + binary_dir: Some(binary_dir.clone()), + binaries: BINARIES.iter().map(|b| b.to_string()).collect(), + extra_library_dirs, + }; + let facts = probe(&request); + let manifest = Manifest::find(&binary_dir); + let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu); + let mut profile = resolve(opts.profile.as_deref(), gpu); + if let Ok(p) = &mut profile { + if let Some(gib) = opts.gpu_budget_gib { + p.gpu_budget_bytes = gib << 30; + } + if let Some(tokens) = opts.context_tokens { + p.context_tokens = tokens; + } + if let Err(message) = p.validate() { + profile = Err(message); + } + } + let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { + ModeChoice::Foreground + } else { + opts.mode + }; + let mode = resolve_mode(choice, &facts, user_session_available(var)); + let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { + opts.service_user + .clone() + .unwrap_or_else(|| "leleka".to_owned()) + } else { + var("USER") + .or_else(|| var("LOGNAME")) + .unwrap_or_else(|| "root".to_owned()) + }; + let (shards, kar) = missing_asset_bytes(&paths); + let installed_same_dir = same_dir(&bin_src, &installed); + let mut needs = Needs { + gpu_index: opts.gpu, + assets_dir: opts.dirs.assets.clone(), + state_dir: opts.dirs.state.clone(), + prefix_dir: opts.dirs.prefix.clone(), + // Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not). + shard_bytes_missing: if opts.fetch && facts.os != "windows" { + shards + } else { + 0 + }, + kar_bytes_missing: if opts.fetch && facts.os != "windows" { + kar + } else { + 0 + }, + install_binaries: !installed_same_dir, + may_install_cublas: opts.install_cublas + && opts.cublas_dir.is_none() + && facts.os != "windows", + cublas_download_bytes: CUBLAS_BYTES, + wants_systemd: matches!(mode, Mode::Systemd(_)), + service_ports: vec![ + ("api".into(), port_of(&opts.ports.api)), + ("engine".into(), port_of(&opts.ports.engine)), + ("gateway".into(), port_of(&opts.ports.daemon)), + ], + require_binaries: true, + binary_has_sm86: manifest + .as_ref() + .and_then(|m| m.as_ref().ok()) + .map(Manifest::has_sm86), + service_running: service_running(&paths), + kar_fd_inherited: opts.kar_fd.is_some(), + api_bind_open: crate::config::probe_address(&opts.ports.api) + .is_some_and(|a| !a.ip().is_loopback()), + expert_profile: None, + resources: None, + }; + let (config, report) = match &mut profile { + Ok(p) => { + // `kar_source: none` never needs the archive (and never builds it) + if p.kar_source == KarSource::None { + needs.kar_bytes_missing = 0; + } + needs.expert_profile = if opts.no_expert_tier && p.expert_profile.is_some() { + Some(ExpertProfileState::OptedOut) + } else { + expert_profile_state(p, &opts.dirs.assets) + }; + let mut engine_env = BTreeMap::new(); + let base_profile = p.clone(); + // An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. + let planned_host = if opts.kar_fd.is_some() { + crate::resources::with_resident_bytes(&facts, p.memfd_bytes()) + } else { + facts.clone() + }; + let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); + crate::resources::apply( + &resources, + p, + &mut engine_env, + opts.gpu_budget_gib.is_some(), + ); + needs.resources = Some(resources); + // The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is + // provisioned by the `expert-profile` step, which runs before the configuration is written and blocks `up` + // when it cannot succeed. At every start the supervisor re-checks the digest (`expert_profile::start_environment`). + if needs.expert_profile != Some(ExpertProfileState::OptedOut) + && let Some(relative) = &p.expert_profile + { + engine_env.insert( + crate::expert_profile::SLOTS_ENV.to_owned(), + "auto".to_owned(), + ); + engine_env.insert( + crate::expert_profile::PROFILE_ENV.to_owned(), + opts.dirs.assets.join(relative).display().to_string(), + ); + } + let mut config = RunConfig::new( + &opts.dirs, + opts.ports.clone(), + opts.gpu, + p.clone(), + engine_env, + ); + config.preset = opts.preset; + config.expert_tier = !opts.no_expert_tier; + config.base_profile = Some(base_profile); + let report = evaluate(&facts, p, &needs); + (Some(config), Some(report)) + } + Err(_) => (None, None), + }; + Context { + opts: opts.clone(), + facts, + paths, + bin_src, + manifest, + profile, + mode, + service_user, + config, + report, + needs, + } +} + +pub(super) fn port_of(address: &str) -> u16 { + address + .rsplit(':') + .next() + .and_then(|p| p.parse().ok()) + .unwrap_or(0) +} + +pub(super) fn same_dir(a: &Path, b: &Path) -> bool { + match (a.canonicalize(), b.canonicalize()) { + (Ok(a), Ok(b)) => a == b, + _ => a == b, + } +} diff --git a/crates/deploy/src/plan/host_steps.rs b/crates/deploy/src/plan/host_steps.rs new file mode 100644 index 00000000..4ac4f920 --- /dev/null +++ b/crates/deploy/src/plan/host_steps.rs @@ -0,0 +1,147 @@ +//! The plan steps that prepare the host: checks, directories, binaries, cuBLAS and the secrets. + +use super::*; + +pub(super) fn preflight_step(ctx: &Context) -> Step { + let state = match &ctx.report { + Some(report) if report.failed() => StepState::Blocked(format!( + "{} check(s) failed", + report.count(crate::preflight::Level::Fail) + )), + Some(report) => StepState::Todo(format!( + "{} warning(s)", + report.count(crate::preflight::Level::Warn) + )), + None => StepState::Blocked(ctx.profile.as_ref().err().cloned().unwrap_or_default()), + }; + let probes = if ctx.facts.os == "windows" { + "nvidia-smi.exe, GlobalMemoryStatusEx, GetDiskFreeSpaceEx, DLL search, loopback ports" + } else { + "nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create" + }; + step("preflight", "host checks", state, vec![probes.into()]) +} + +pub(super) fn layout_step(ctx: &Context, fs: &FsState) -> Step { + let dirs = &ctx.opts.dirs; + let state = if fs.dirs_exist { + StepState::Done("present".into()) + } else { + StepState::Todo("create state (0700), logs, run, stamps, assets".into()) + }; + step( + "layout", + "create directories", + state, + vec![format!( + "mkdir -p {} {} {}", + dirs.prefix.display(), + dirs.state.display(), + dirs.assets.display() + )], + ) +} + +pub(super) fn binaries_step(ctx: &Context, fs: &FsState) -> Step { + let bin_dir = ctx.paths.bin_dir(); + let state = if !fs.binaries_source_ok { + StepState::Blocked(format!( + "not all of {} are in {} or {}", + BINARIES.join(", "), + ctx.bin_src.display(), + bin_dir.display() + )) + } else if fs.binaries_current { + StepState::Done(format!("{} is current", bin_dir.display())) + } else { + StepState::Todo(format!( + "copy from {} (SHA-256 checked against MANIFEST.json when present)", + ctx.bin_src.display() + )) + }; + step( + "binaries", + "install the six runtime binaries", + state, + vec![format!( + "install {{{}}} -> {}", + BINARIES.join(","), + bin_dir.display() + )], + ) +} + +pub(super) fn cublas_step(ctx: &Context, fs: &FsState) -> Step { + let windows = ctx.facts.os == "windows"; + let commands = if windows { + Vec::new() + } else { + vec![ + format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"), + format!( + "tar -xJf libcublas-{CUBLAS_VERSION}.tar.xz -> {}", + ctx.paths.cublas_dir().display() + ), + ] + }; + step( + "cublas", + "CUDA 12 cuBLAS for the PLE batch GEMM", + cublas_state(ctx, fs, windows), + commands, + ) +} + +fn cublas_state(ctx: &Context, fs: &FsState, windows: bool) -> StepState { + let opts = &ctx.opts; + if fs.cublas_ready { + StepState::Done( + if windows { + "cublas64_12.dll and cublasLt64_12.dll found" + } else { + "libcublas.so.12 and libcublasLt.so.12 found" + } + .into(), + ) + } else if windows { + StepState::Blocked( + "cublas64_12.dll and cublasLt64_12.dll (CUDA 12.x) were not found; pass --cublas-dir DIR that holds \ + them (a CUDA 12 toolkit's bin folder, or the NVIDIA cuBLAS 12 redistributable)" + .into(), + ) + } else if opts.cublas_dir.is_some() { + StepState::Blocked( + "--cublas-dir does not contain libcublas.so.12 and libcublasLt.so.12".into(), + ) + } else if opts.install_cublas { + StepState::Todo(format!( + "download the pinned {CUBLAS_VERSION} redistributable ({} MiB)", + CUBLAS_BYTES >> 20 + )) + } else { + StepState::Blocked("missing and --no-install-cublas was given".into()) + } +} + +pub(super) fn secrets_step(ctx: &Context, fs: &FsState) -> Step { + let state = if fs.secrets_present { + StepState::Done("runtime.env and api-key exist (never rotated)".into()) + } else { + StepState::Todo("generate two tokens (0600) and run `strata-next api-key init`".into()) + }; + step( + "secrets", + "service tokens and API key", + state, + vec![format!( + "{} api-key init --file {}", + strata_next(ctx), + ctx.paths.api_key().display() + )], + ) +} + +/// The path of the `strata-next` binary as the plan prints it in commands. +pub(super) fn strata_next(ctx: &Context) -> String { + ctx.paths.bin("strata-next").display().to_string() +} diff --git a/crates/deploy/src/plan/model_steps.rs b/crates/deploy/src/plan/model_steps.rs new file mode 100644 index 00000000..698d60fa --- /dev/null +++ b/crates/deploy/src/plan/model_steps.rs @@ -0,0 +1,209 @@ +//! The plan steps that bring the model in: the shards, the KAR archive, the MTP pack, the tokenizer and the configs. + +use super::*; + +/// The archive is accepted as it is (`--trust-archive`): the engine verifies it at each load. +pub(super) fn trusts_archive(ctx: &Context, fs: &FsState) -> bool { + ctx.opts.trust_archive && fs.kar_present +} + +pub(super) fn model_step(ctx: &Context, fs: &FsState, kar_runs_tool: bool) -> Step { + let windows = ctx.facts.os == "windows"; + let paths = &ctx.paths; + let manifest = MANIFEST; + let sn = strata_next(ctx); + let commands = if windows { + Vec::new() + } else { + vec![ + format!( + "{sn} model fetch {manifest} --output {}", + paths.model_dir().display() + ), + format!( + "{sn} model verify {manifest} --output {}", + paths.model_dir().display() + ), + ] + }; + step( + "model", + "fetch and verify the two IQ3_S GGUF shards", + model_state(ctx, fs, kar_runs_tool), + commands, + ) +} + +fn model_state(ctx: &Context, fs: &FsState, kar_runs_tool: bool) -> StepState { + let opts = &ctx.opts; + if ctx.facts.os == "windows" { + windows_model_state(ctx) + } else if fs.shards_stamp_ok && !opts.reverify { + StepState::Done( + "verified earlier; sizes and mtimes unchanged (--reverify hashes again)".into(), + ) + } else if kar_runs_tool { + StepState::Todo( + "downloaded and verified inside the archive step \ + (ensure-sharded-streamed fetches and verifies the shards first)" + .into(), + ) + } else if !opts.fetch { + no_fetch_model_state(fs) + } else { + StepState::Todo(format!( + "{} still to download; resumable, SHA-256 of 83.6 GB", + gib_text(ctx.needs.shard_bytes_missing) + )) + } +} + +fn windows_model_state(ctx: &Context) -> StepState { + if ctx.needs.shard_bytes_missing == 0 && windows_shards_present(&ctx.paths) { + StepState::Done( + "both shards are present with the pinned sizes \ + (the engine hashes them at each load, or skips it with a verification stamp)" + .into(), + ) + } else { + StepState::Blocked(format!( + "the two shards must already be in {} with their pinned sizes \ + (the Windows tool does not download or build; copy them from the WSL volume, see docs/windows.md)", + ctx.paths.model_dir().display() + )) + } +} + +fn no_fetch_model_state(fs: &FsState) -> StepState { + if fs.shards_stamp_ok { + StepState::Todo("--no-fetch: verify only".into()) + } else { + StepState::Blocked( + "--no-fetch given but the shards are not verified yet; run without --no-fetch".into(), + ) + } +} + +/// The state of the `kar` step; `trusted` is [`trusts_archive`]. +pub(super) fn kar_state(ctx: &Context, fs: &FsState, trusted: bool) -> StepState { + let opts = &ctx.opts; + let kar_unused = ctx + .profile + .as_ref() + .is_ok_and(|p| p.kar_source == KarSource::None); + if kar_unused { + StepState::Skip( + "kar_source none (experimental): no archive is used, the PLE rows are read from the GGUF shard".into(), + ) + } else if ctx.facts.os == "windows" { + windows_kar_state(ctx, fs) + } else if fs.kar_stamp_ok && !opts.reverify { + StepState::Done(format!("{ARCHIVE_BYTES} bytes, verified earlier")) + } else if trusted { + StepState::Todo( + "accept the existing archive without the strict re-derivation (--trust-archive); \ + the engine verifies its SHA-256 and every CRC at each load" + .into(), + ) + } else if !opts.fetch { + StepState::Blocked("--no-fetch given but the archive is missing or unverified".into()) + } else { + StepState::Todo( + "build the level-2 KAR archive (bounded memory, hours on a first run) \ + or re-verify the existing one (strict, tens of minutes), then stamp it" + .into(), + ) + } +} + +fn windows_kar_state(ctx: &Context, fs: &FsState) -> StepState { + if fs.kar_present { + StepState::Done(format!( + "{ARCHIVE_BYTES} bytes with its provenance file (the engine checks SHA-256 and CRCs at each load)" + )) + } else { + StepState::Blocked(format!( + "{} (pinned length {ARCHIVE_BYTES}) and its .provenance.json must already be on the model volume; \ + the Windows tool does not build the archive (build it in WSL and copy it, see docs/windows.md)", + ctx.paths.kar().display() + )) + } +} + +pub(super) fn kar_step(ctx: &Context, state: StepState) -> Step { + let paths = &ctx.paths; + let commands = if ctx.facts.os == "windows" { + Vec::new() + } else { + vec![format!( + "{} model ensure-sharded-streamed {MANIFEST} --source-dir {} --output {} --levels 2", + strata_next(ctx), + paths.model_dir().display(), + paths.kar().display() + )] + }; + step("kar", "KAR level-2 archive (+ provenance)", state, commands) +} + +pub(super) fn mtp_pack_step(ctx: &Context, fs: &FsState) -> Step { + let pack = ctx.paths.mtp_pack(); + let state = if let Some(src) = &ctx.opts.mtp_pack { + if fs.mtp_present { + StepState::Done("present; --mtp-pack ignored".into()) + } else { + StepState::Todo(format!("import from {}", src.display())) + } + } else if fs.mtp_present { + StepState::Done(format!("{} present", pack.display())) + } else { + StepState::Blocked(format!( + "{} is missing and no --mtp-pack was given; the pack ({}) has no automated producer yet", + pack.display(), + MTP_FILES.join(", ") + )) + }; + step( + "mtp-pack", + "MTP draft pack (data/mtp-rt)", + state, + vec![format!("copy/unpack -> {}", pack.display())], + ) +} + +pub(super) fn tokenizer_step(ctx: &Context, fs: &FsState) -> Step { + let state = if fs.tokenizer_present { + StepState::Done("present".into()) + } else { + StepState::Todo("extract from shard 1".into()) + }; + step( + "tokenizer", + "tokenizer assets for the API", + state, + vec![format!( + "{} model extract-tokenizer {} --output {}", + strata_next(ctx), + ctx.paths.shard(0).display(), + ctx.paths.tokenizer_root().display() + )], + ) +} + +pub(super) fn config_step(ctx: &Context, fs: &FsState) -> Step { + let state = if fs.configs_current { + StepState::Done("up to date".into()) + } else { + StepState::Todo( + "write leleka.json, daemon.json, strata.json, profile.json, runtime.env".into(), + ) + }; + step( + "config", + "run configuration, gateway and API configs, environment file", + state, + vec![format!( + "write {}/{{leleka,daemon,strata,profile}}.json runtime.env", + ctx.opts.dirs.state.display() + )], + ) +} diff --git a/crates/deploy/src/plan/render.rs b/crates/deploy/src/plan/render.rs new file mode 100644 index 00000000..f7e4c9cb --- /dev/null +++ b/crates/deploy/src/plan/render.rs @@ -0,0 +1,54 @@ +//! The text of a plan for `--dry-run` and `preflight`. + +#[allow(unused_imports)] +use super::*; + +/// A human rendering of the plan, with the engine command the service will run. +pub fn render_plan(ctx: &Context, steps: &[Step]) -> String { + let mut out = String::new(); + out.push_str("plan:\n"); + for (index, step) in steps.iter().enumerate() { + out.push_str(&format!( + " {:>2}. [{:7}] {} - {}\n", + index + 1, + step.state.tag(), + step.title, + step.state.why() + )); + if matches!(step.state, StepState::Todo(_) | StepState::Blocked(_)) { + for command in &step.commands { + out.push_str(&format!(" $ {command}\n")); + } + } + } + if let Some(config) = &ctx.config { + let kar = match config.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + KarSource::None => KarArg::None, + }; + out.push_str(&format!( + "engine command the service runs:\n {} {}\n", + ctx.paths.bin("leleka-inference").display(), + config.engine_args(kar).join(" ") + )); + out.push_str(&format!( + " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", + config.profile.name, + config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, + config.profile.context_tokens, + config.profile.kar_source.as_str() + )); + let env = config.engine_environment(); + if !env.is_empty() { + out.push_str(&format!( + " engine environment: {}\n", + env.iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join(" ") + )); + } + } + out +} diff --git a/crates/deploy/src/plan/scope.rs b/crates/deploy/src/plan/scope.rs new file mode 100644 index 00000000..c3959a80 --- /dev/null +++ b/crates/deploy/src/plan/scope.rs @@ -0,0 +1,47 @@ +//! Unit scope and run mode: how the mode follows from the options and the host. + +#[allow(unused_imports)] +use super::*; + +impl UnitScopeTag { + pub fn scope(self) -> UnitScope { + match self { + UnitScopeTag::System => UnitScope::System, + UnitScopeTag::User => UnitScope::User, + } + } +} +impl Mode { + pub fn label(self) -> &'static str { + match self { + Mode::Systemd(UnitScopeTag::System) => "systemd (system unit)", + Mode::Systemd(UnitScopeTag::User) => "systemd (user unit)", + Mode::Foreground => "foreground", + Mode::None => "prepare only", + } + } +} + +/// `--mode auto`: root with systemd gets a system unit, a user with a systemd user session a user unit, everything +/// else (WSL without systemd, containers) runs in the foreground. +pub fn resolve_mode(choice: ModeChoice, facts: &Facts, user_session: bool) -> Mode { + match choice { + ModeChoice::System => Mode::Systemd(UnitScopeTag::System), + ModeChoice::User => Mode::Systemd(UnitScopeTag::User), + ModeChoice::Foreground => Mode::Foreground, + ModeChoice::None => Mode::None, + ModeChoice::Auto => { + if facts.systemd_system && facts.tool("systemctl") { + if facts.root { + Mode::Systemd(UnitScopeTag::System) + } else if user_session { + Mode::Systemd(UnitScopeTag::User) + } else { + Mode::Foreground + } + } else { + Mode::Foreground + } + } + } +} diff --git a/crates/deploy/src/plan/service_steps.rs b/crates/deploy/src/plan/service_steps.rs new file mode 100644 index 00000000..d3f3b8b3 --- /dev/null +++ b/crates/deploy/src/plan/service_steps.rs @@ -0,0 +1,125 @@ +//! The plan steps that run the service: the unit, the start and the readiness wait. + +use super::*; + +/// The `service` and `start` steps of the chosen mode. +pub(super) fn service_steps(ctx: &Context, fs: &FsState) -> [Step; 2] { + match ctx.mode { + Mode::Systemd(scope) => [ + unit_step(ctx, fs, scope), + systemd_start_step(ctx, fs, scope), + ], + Mode::Foreground => [ + skipped_unit_step("foreground mode"), + foreground_start_step(ctx, fs), + ], + Mode::None => [ + skipped_unit_step("--mode none"), + step( + "start", + "start the service", + StepState::Skip("--mode none".into()), + vec![], + ), + ], + } +} + +fn skipped_unit_step(why: &str) -> Step { + step( + "service", + "systemd unit", + StepState::Skip(why.into()), + vec![], + ) +} + +/// `--user ` for a user unit, nothing for a system unit. +fn user_flag(scope: UnitScopeTag) -> &'static str { + if scope == UnitScopeTag::User { + "--user " + } else { + "" + } +} + +fn unit_step(ctx: &Context, fs: &FsState, scope: UnitScopeTag) -> Step { + let state = if fs.unit_current { + StepState::Done("installed and enabled".into()) + } else { + let which = if scope == UnitScopeTag::System { + "system" + } else { + "user" + }; + StepState::Todo(format!("write {which} unit, daemon-reload, enable")) + }; + step( + "service", + "systemd unit", + state, + vec![format!( + "systemctl {}enable {}", + user_flag(scope), + ctx.paths.unit_name() + )], + ) +} + +fn systemd_start_step(ctx: &Context, fs: &FsState, scope: UnitScopeTag) -> Step { + let state = if fs.service_ready { + StepState::Done("already ready".into()) + } else { + StepState::Todo( + "systemctl start (first start copies the archive and loads the model)".into(), + ) + }; + step( + "start", + "start the service", + state, + vec![format!( + "systemctl {}start {}", + user_flag(scope), + ctx.paths.unit_name() + )], + ) +} + +fn foreground_start_step(ctx: &Context, fs: &FsState) -> Step { + let state = if fs.service_ready { + StepState::Done("a supervisor is already ready".into()) + } else { + StepState::Todo("leleka run (Ctrl-C drains and stops)".into()) + }; + step( + "start", + "run the supervisor in this terminal", + state, + vec![format!( + "{} run --config {}", + ctx.paths.bin("leleka").display(), + ctx.paths.run_config().display() + )], + ) +} + +pub(super) fn ready_step(ctx: &Context, fs: &FsState) -> Step { + let opts = &ctx.opts; + let state = if matches!(ctx.mode, Mode::None) { + StepState::Skip("--mode none".into()) + } else if fs.service_ready { + StepState::Done("ready".into()) + } else { + StepState::Todo(format!( + "poll {} /ready for up to {} s", + opts.ports.api, opts.timeout_s + )) + }; + step( + "ready", + "wait for readiness", + state, + vec![format!("GET http://{}/ready", opts.ports.api)], + ) +} diff --git a/crates/deploy/src/plan/step_plan.rs b/crates/deploy/src/plan/step_plan.rs new file mode 100644 index 00000000..2b065ae4 --- /dev/null +++ b/crates/deploy/src/plan/step_plan.rs @@ -0,0 +1,39 @@ +//! The ordered install plan: every step the `up` command may run, with its state. + +use super::*; + +pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { + let mut steps = vec![ + preflight_step(ctx), + layout_step(ctx, fs), + binaries_step(ctx, fs), + expert_profile_step(ctx), + cublas_step(ctx, fs), + secrets_step(ctx, fs), + ]; + let trusted = trusts_archive(ctx, fs); + let kar_state = kar_state(ctx, fs, trusted); + let kar_runs_tool = matches!(kar_state, StepState::Todo(_)) && !trusted; + steps.push(model_step(ctx, fs, kar_runs_tool)); + steps.push(kar_step(ctx, kar_state)); + steps.push(mtp_pack_step(ctx, fs)); + steps.push(tokenizer_step(ctx, fs)); + steps.push(config_step(ctx, fs)); + steps.extend(service_steps(ctx, fs)); + steps.push(ready_step(ctx, fs)); + steps +} + +/// Both shards exist with their pinned sizes. +pub(super) fn windows_shards_present(paths: &Paths) -> bool { + crate::profile::SHARD_BYTES + .iter() + .enumerate() + .all(|(index, expected)| { + std::fs::metadata(paths.shard(index)).is_ok_and(|m| m.len() == *expected) + }) +} + +pub(super) fn gib_text(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) +} diff --git a/crates/deploy/src/plan/step_state.rs b/crates/deploy/src/plan/step_state.rs new file mode 100644 index 00000000..52ba2b86 --- /dev/null +++ b/crates/deploy/src/plan/step_state.rs @@ -0,0 +1,32 @@ +//! The state of one plan step and the constructor of a step. + +#[allow(unused_imports)] +use super::*; + +impl StepState { + pub fn tag(&self) -> &'static str { + match self { + StepState::Done(_) => "done", + StepState::Todo(_) => "todo", + StepState::Skip(_) => "skip", + StepState::Blocked(_) => "BLOCKED", + } + } + pub fn why(&self) -> &str { + match self { + StepState::Done(s) + | StepState::Todo(s) + | StepState::Skip(s) + | StepState::Blocked(s) => s, + } + } +} + +pub(super) fn step(id: &'static str, title: &str, state: StepState, commands: Vec) -> Step { + Step { + id, + title: title.to_owned(), + state, + commands, + } +} diff --git a/crates/deploy/src/plan/tests.rs b/crates/deploy/src/plan/tests.rs new file mode 100644 index 00000000..491cd600 --- /dev/null +++ b/crates/deploy/src/plan/tests.rs @@ -0,0 +1,156 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::{ + cli::{Command, Environment, parse}, + facts::{Gpu, Memory}, + layout::Dirs, +}; + +fn options(extra: &[&str]) -> UpOptions { + let var = |_: &str| None; + let mut args: Vec = vec![ + "up".into(), + "--assets".into(), + "/data/leleka".into(), + "--state-dir".into(), + "/var/lib/leleka/state".into(), + "--prefix".into(), + "/opt/leleka".into(), + ]; + args.extend(extra.iter().map(|s| s.to_string())); + match parse( + &args, + &Environment { + root: true, + home: None, + var: &var, + }, + ) + .unwrap() + { + Command::Up(options) => options, + _ => unreachable!(), + } +} + +fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { + let paths = opts.dirs.paths(); + let gpu = Gpu { + index: 0, + name: gpu_name.into(), + driver: "595.99.02".into(), + vram_total_mib: if sm == 120 { 32607 } else { 16384 }, + vram_free_mib: if sm == 120 { 32000 } else { 15500 }, + sm: Some(sm), + }; + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + gpus: vec![gpu.clone()], + memory: Memory { + total: 128 << 30, + available: 100 << 30, + swap_total: 0, + }, + root: true, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + facts + .libs + .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/x/libcublasLt.so.12".into()), + ); + facts + .libs + .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for name in BINARIES { + facts.binaries.insert(name.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + crate::facts::DirFact { + path: format!("/{key}").into(), + free_bytes: Some(2 << 40), + fs_type: Some("ext4".into()), + }, + ); + } + let profile = resolve(opts.profile.as_deref(), Some(&gpu)); + // A finished host by default: the pinned table is in place (tests of the other states set `needs.expert_profile`). + let expert_profile = profile + .as_ref() + .ok() + .filter(|p| p.expert_profile.is_some()) + .map(|_| { + if opts.no_expert_tier { + ExpertProfileState::OptedOut + } else { + ExpertProfileState::Valid + } + }); + let needs = Needs { + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + expert_profile, + ..Needs::default() + }; + let config = profile.as_ref().ok().map(|p| { + RunConfig::new( + &opts.dirs, + opts.ports.clone(), + 0, + p.clone(), + BTreeMap::new(), + ) + }); + let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs)); + Context { + service_user: "leleka".into(), + bin_src: "/src/bin".into(), + manifest: None, + profile, + mode, + facts, + paths, + config, + report, + needs, + opts, + } +} + +fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState { + &steps.iter().find(|s| s.id == id).unwrap().state +} + +fn expert_step(extra: &[&str], state: ExpertProfileState) -> StepState { + let mut ctx = context( + options(extra), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + ctx.needs.expert_profile = Some(state); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + state_of(&steps, "expert-profile").clone() +} + +mod expert_profile_steps; +mod install_steps; +mod mode_resolution; diff --git a/crates/deploy/src/plan/tests/expert_profile_steps.rs b/crates/deploy/src/plan/tests/expert_profile_steps.rs new file mode 100644 index 00000000..0d2f0378 --- /dev/null +++ b/crates/deploy/src/plan/tests/expert_profile_steps.rs @@ -0,0 +1,168 @@ +//! The expert-profile step: its place in the plan, its states and the digest that decides a download. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_expert_profile_is_planned_before_the_big_downloads() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let ids: Vec<&str> = plan_steps(&ctx, &FsState::default()) + .iter() + .map(|s| s.id) + .collect(); + let at = |id: &str| ids.iter().position(|i| *i == id).unwrap(); + assert!( + at("expert-profile") < at("model") + && at("expert-profile") < at("kar") + && at("expert-profile") < at("config"), + "{ids:?}" + ); +} + +#[test] +fn the_expert_profile_step_covers_every_state_and_never_stays_silent() { + // present with the pinned digest: nothing to do + assert!( + matches!(expert_step(&[], ExpertProfileState::Valid), StepState::Done(why) if why.contains("8f59b4aa...388975baf")) + ); + // missing: the table embedded in the binary is installed, with or without network + for extra in [&[][..], &["--no-fetch"]] { + let embedded = expert_step(extra, ExpertProfileState::Absent); + assert!( + matches!(&embedded, StepState::Todo(why) if why.contains("196632-byte table embedded") && why.contains("no network")), + "{embedded:?}" + ); + } + // the offline route installs from the local file + let local = expert_step( + &[ + "--no-fetch", + "--expert-profile-file", + "/mnt/usb/expert-profile.bin", + ], + ExpertProfileState::Absent, + ); + assert!( + matches!(&local, StepState::Todo(why) if why.contains("/mnt/usb/expert-profile.bin")), + "{local:?}" + ); + // a file with another digest is never used silently: blocked, or replaced (moved aside) on request + let wrong = expert_step(&[], ExpertProfileState::WrongDigest); + assert!( + matches!(&wrong, StepState::Blocked(why) if why.contains("is not used") && why.contains("Move it aside")), + "{wrong:?}" + ); + let replace = expert_step( + &["--expert-profile-file", "/x/p.bin"], + ExpertProfileState::WrongDigest, + ); + assert!( + matches!(&replace, StepState::Todo(why) if why.contains("moved aside")), + "{replace:?}" + ); + // the explicit opt-out is a Skip that says OFF + let off = expert_step(&["--no-expert-tier"], ExpertProfileState::OptedOut); + assert!( + matches!(&off, StepState::Skip(why) if why.contains("OFF")), + "{off:?}" + ); +} + +#[test] +fn only_a_profile_with_another_digest_needs_a_download_or_a_file() { + let mut ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + // no curl or wget: the embedded table does not need them + ctx.facts.tools.insert("curl".into(), false); + ctx.needs.expert_profile = Some(ExpertProfileState::Absent); + let steps = plan_steps(&ctx, &FsState::default()); + assert!( + matches!(state_of(&steps, "expert-profile"), StepState::Todo(why) if why.contains("embedded in this binary")) + ); + // a profile that pins another digest has no embedded table and no download source: blocked with both ways out + ctx.profile.as_mut().unwrap().expert_profile_sha256 = Some("ab".repeat(32)); + let steps = plan_steps(&ctx, &FsState::default()); + assert!( + matches!(state_of(&steps, "expert-profile"), StepState::Blocked(why) if why.contains("--expert-profile-file") && why.contains("--no-expert-tier")), + "{:?}", + state_of(&steps, "expert-profile") + ); + ctx.opts.expert_profile_file = Some("/x/p.bin".into()); + let steps = plan_steps(&ctx, &FsState::default()); + assert!(matches!( + state_of(&steps, "expert-profile"), + StepState::Todo(_) + )); +} + +#[test] +fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() { + let dir = std::env::temp_dir().join(format!("leleka-expert-gather-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let gathered = |extra: &[&str]| { + let mut args = vec!["--profile", "rtx5090-32g"]; + args.extend_from_slice(extra); + let mut opts = options(&args); + opts.dirs.assets = dir.clone(); + gather(&opts, &|_| None) + }; + // The table is absent: the configuration still names it (the step provisions it before the configuration is written). + let with_tier = gathered(&[]); + let config = with_tier.config.as_ref().unwrap(); + assert!( + config.expert_tier + && config + .engine_env + .contains_key(crate::expert_profile::PROFILE_ENV) + ); + assert_eq!( + with_tier.needs.expert_profile, + Some(ExpertProfileState::Absent) + ); + // The opt-out leaves the switches out and is recorded, so `status` can say "explicit opt-out". + let without = gathered(&["--no-expert-tier"]); + let config = without.config.as_ref().unwrap(); + assert!( + !config.expert_tier + && !config + .engine_env + .contains_key(crate::expert_profile::PROFILE_ENV) + ); + assert_eq!( + without.needs.expert_profile, + Some(ExpertProfileState::OptedOut) + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn expert_profile_needs_the_pinned_digest() { + let dir = std::env::temp_dir().join(format!("leleka-expert-{}", std::process::id())); + std::fs::create_dir_all(dir.join("data")).unwrap(); + let profile = Profile::builtin("rtx3080-16g").unwrap(); + assert_eq!( + expert_profile_state(&profile, &dir), + Some(ExpertProfileState::Absent) + ); + std::fs::write(dir.join("data/expert-profile.bin"), b"not the profile").unwrap(); + assert_eq!( + expert_profile_state(&profile, &dir), + Some(ExpertProfileState::WrongDigest) + ); + // the server profile names the same shipped routing profile (default digest) + assert_eq!( + expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir), + Some(ExpertProfileState::WrongDigest) + ); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/deploy/src/plan/tests/install_steps.rs b/crates/deploy/src/plan/tests/install_steps.rs new file mode 100644 index 00000000..653e9b58 --- /dev/null +++ b/crates/deploy/src/plan/tests/install_steps.rs @@ -0,0 +1,218 @@ +//! Which steps a fresh, finished, blocked or re-verified deployment plans, and with what command. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn fresh_server_plans_every_step() { + let mut ctx = context( + options(&[]), + Mode::Systemd(UnitScopeTag::System), + "NVIDIA GeForce RTX 5090", + 120, + ); + ctx.needs.expert_profile = Some(ExpertProfileState::Absent); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + mtp_present: true, + ..FsState::default() + }, + ); + for id in [ + "layout", + "binaries", + "expert-profile", + "secrets", + "model", + "kar", + "tokenizer", + "config", + "service", + "start", + "ready", + ] { + assert!( + matches!(state_of(&steps, id), StepState::Todo(_)), + "{id}: {:?}", + state_of(&steps, id) + ); + } + let text = render_plan(&ctx, &steps).replace('\\', "/"); + assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}"); + assert!(text.contains("--kar-archive-fd {FD}"), "{text}"); +} + +#[test] +fn finished_deployment_is_done_except_nothing_to_do() { + let ctx = context( + options(&[]), + Mode::Systemd(UnitScopeTag::System), + "NVIDIA GeForce RTX 5090", + 120, + ); + let fs = FsState { + dirs_exist: true, + binaries_current: true, + binaries_source_ok: true, + cublas_ready: true, + secrets_present: true, + shards_stamp_ok: true, + kar_stamp_ok: true, + kar_present: true, + mtp_present: true, + tokenizer_present: true, + configs_current: true, + unit_current: true, + service_ready: true, + }; + let steps = plan_steps(&ctx, &fs); + for step in &steps { + if step.id != "preflight" { + assert!( + matches!(step.state, StepState::Done(_)), + "{} is {:?}", + step.id, + step.state + ); + } + } + // The plan of a finished deployment prints no commands (nothing will run). + assert!(!render_plan(&ctx, &steps[1..]).contains("$ ")); +} + +#[test] +fn missing_pieces_block_with_the_reason() { + let ctx = context( + options(&["--no-fetch", "--no-install-cublas"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps(&ctx, &FsState::default()); + assert!(matches!( + state_of(&steps, "binaries"), + StepState::Blocked(_) + )); + assert!(matches!(state_of(&steps, "cublas"), StepState::Blocked(_))); + assert!(matches!(state_of(&steps, "model"), StepState::Blocked(_))); + assert!(matches!(state_of(&steps, "kar"), StepState::Blocked(_))); + let mtp = state_of(&steps, "mtp-pack"); + assert!( + matches!(mtp, StepState::Blocked(_)) && mtp.why().contains("no automated producer"), + "{mtp:?}" + ); + assert!(matches!(state_of(&steps, "service"), StepState::Skip(_))); +} + +#[test] +fn the_archive_step_covers_the_shards_and_trust_archive_does_not() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!( + state_of(&steps, "model") + .why() + .contains("inside the archive step") + ); + let trusted = context( + options(&["--trust-archive"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &trusted, + &FsState { + binaries_source_ok: true, + kar_present: true, + ..FsState::default() + }, + ); + assert!( + !state_of(&steps, "model") + .why() + .contains("inside the archive step") + ); + assert!(state_of(&steps, "kar").why().contains("--trust-archive")); + // Trusting needs an archive to trust. + let steps = plan_steps( + &trusted, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!(!state_of(&steps, "kar").why().contains("--trust-archive")); +} + +#[test] +fn mtp_pack_import_is_a_todo_when_given() { + let ctx = context( + options(&["--mtp-pack", "/tmp/mtp-rt.tar.gz"]), + Mode::None, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!(matches!(state_of(&steps, "mtp-pack"), StepState::Todo(_))); + assert!(matches!(state_of(&steps, "start"), StepState::Skip(_))); +} + +#[test] +fn reverify_replans_verified_assets() { + let ctx = context( + options(&["--reverify"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + shards_stamp_ok: true, + kar_stamp_ok: true, + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!( + matches!(state_of(&steps, "model"), StepState::Todo(_)) + && matches!(state_of(&steps, "kar"), StepState::Todo(_)) + ); +} + +#[test] +fn laptop_plan_uses_the_file_engine_command() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 3080 Laptop GPU", + 86, + ); + let steps = plan_steps(&ctx, &FsState::default()); + let text = render_plan(&ctx, &steps).replace('\\', "/"); + assert!( + text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar") + && text.contains("--context-tokens 262144"), + "{text}" + ); + assert!(text.contains("rtx3080-16g")); +} diff --git a/crates/deploy/src/plan/tests/mode_resolution.rs b/crates/deploy/src/plan/tests/mode_resolution.rs new file mode 100644 index 00000000..0d50daec --- /dev/null +++ b/crates/deploy/src/plan/tests/mode_resolution.rs @@ -0,0 +1,38 @@ +//! Run mode resolution. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn mode_resolution() { + let mut facts = Facts { + root: true, + systemd_system: true, + ..Facts::default() + }; + facts.tools.insert("systemctl".into(), true); + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, false), + Mode::Systemd(UnitScopeTag::System) + ); + facts.root = false; + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, true), + Mode::Systemd(UnitScopeTag::User) + ); + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, false), + Mode::Foreground + ); + facts.systemd_system = false; + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, true), + Mode::Foreground + ); + assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None); + let _ = Dirs { + prefix: "/".into(), + state: "/".into(), + assets: "/".into(), + }; +} diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index 1e124d03..553582ff 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -79,13 +79,19 @@ const GIB: u64 = 1 << 30; #[cfg(test)] mod tests; -mod impl_report; +mod cuda_libraries; +mod disk; +mod download_hints; +mod evaluation; +mod gpu; +mod kar_source; +mod memory; +mod platform; +mod report; +mod resource_preset; +mod service_host; +mod wsl_filesystem; + +pub use evaluation::evaluate; #[allow(unused_imports)] -use impl_report::check; -#[allow(unused_imports)] -use impl_report::gib; -#[allow(unused_imports)] -use impl_report::pass; -mod evaluate_fn; -#[allow(unused_imports)] -pub use evaluate_fn::evaluate; +use report::{check, gib, pass}; diff --git a/crates/deploy/src/preflight/cuda_libraries.rs b/crates/deploy/src/preflight/cuda_libraries.rs new file mode 100644 index 00000000..437f7cb4 --- /dev/null +++ b/crates/deploy/src/preflight/cuda_libraries.rs @@ -0,0 +1,107 @@ +//! The CUDA libraries: cuBLAS 12 (found, downloadable or missing) and the driver library. + +use super::*; + +/// The file names the engine loads on this OS: (cuBLAS, cuBLASLt, CUDA driver library). +fn library_names(windows: bool) -> (&'static str, &'static str, &'static str) { + if windows { + ("cublas64_12.dll", "cublasLt64_12.dll", "nvcuda.dll") + } else { + ("libcublas.so.12", "libcublasLt.so.12", "libcuda.so.1") + } +} + +pub(super) fn check_cublas(facts: &Facts, needs: &Needs, checks: &mut Vec) { + let windows = facts.os == "windows"; + let (blas_name, blas_lt_name, _) = library_names(windows); + let blas = facts.lib("libcublas.so.12"); + let blas_lt = facts.lib("libcublasLt.so.12"); + checks.push(match (blas, blas_lt) { + (Some(path), Some(_)) => pass( + "cublas", + "cuBLAS 12", + format!("{blas_name} and {blas_lt_name} found ({})", path.display()), + ), + _ if needs.may_install_cublas => { + cublas_download(facts, needs, windows, (blas.is_none(), blas_lt.is_none())) + } + _ => cublas_missing(windows), + }); +} + +/// cuBLAS is missing but the pinned redistributable will be downloaded; `absent` is (cuBLAS, cuBLASLt). +fn cublas_download(facts: &Facts, needs: &Needs, windows: bool, absent: (bool, bool)) -> Check { + let (blas_name, blas_lt_name, _) = library_names(windows); + let missing: Vec<&str> = [(absent.0, blas_name), (absent.1, blas_lt_name)] + .into_iter() + .filter_map(|(is_absent, name)| is_absent.then_some(name)) + .collect(); + let tools_ok = + (facts.tool("curl") || facts.tool("wget")) && facts.tool("tar") && facts.tool("xz"); + let tools_note = if tools_ok { + "" + } else { + ", but curl/wget, tar and xz are required for that" + }; + let fix = "apt install curl xz-utils (or pass --cublas-dir DIR with CUDA 12 cuBLAS), \ + or --no-install-cublas to supply it yourself"; + check( + "cublas", + if tools_ok { Level::Warn } else { Level::Fail }, + "cuBLAS 12", + format!( + "{} not found; the pinned NVIDIA redistributable (~{} MiB) will be downloaded into the prefix{tools_note}", + missing.join(", "), + needs.cublas_download_bytes / (1 << 20), + ), + Some(fix.into()), + ) +} + +fn cublas_missing(windows: bool) -> Check { + let (blas_name, blas_lt_name, _) = library_names(windows); + let fix = if windows { + "pass --cublas-dir DIR with the two CUDA 12 cuBLAS DLLs (from a CUDA 12.x toolkit's bin folder or the NVIDIA \ + libcublas 12.9.1.4 windows-x86_64 redistributable zip, docs/windows.md); \ + `leleka run` makes the engine's loader search that directory" + } else { + "pass --cublas-dir DIR (CUDA 12 cuBLAS), drop --no-install-cublas to let `up` download the pinned 12.9.1.4 \ + redistributable, or apt install libcublas12" + }; + check( + "cublas", + Level::Fail, + "cuBLAS 12", + format!("{blas_name} / {blas_lt_name} not found; leleka-inference loads them by name"), + Some(fix.into()), + ) +} + +pub(super) fn check_libcuda(facts: &Facts, checks: &mut Vec) { + let windows = facts.os == "windows"; + let (_, _, cuda_name) = library_names(windows); + checks.push(match facts.lib("libcuda.so.1") { + Some(path) => pass( + "libcuda", + "CUDA driver library", + format!("{}", path.display()), + ), + None => check( + "libcuda", + Level::Warn, + "CUDA driver library", + format!("{cuda_name} was not found by the library search (the engine loads it)"), + Some(libcuda_fix(facts, windows).into()), + ), + }); +} + +fn libcuda_fix(facts: &Facts, windows: bool) -> &'static str { + if windows { + "install the NVIDIA display driver (nvcuda.dll comes with it)" + } else if facts.wsl { + "WSL2 provides it in /usr/lib/wsl/lib; make sure that directory is not removed from the loader path" + } else { + "install the NVIDIA driver's libcuda (nvidia-utils / libnvidia-compute packages)" + } +} diff --git a/crates/deploy/src/preflight/disk.rs b/crates/deploy/src/preflight/disk.rs new file mode 100644 index 00000000..0693a66b --- /dev/null +++ b/crates/deploy/src/preflight/disk.rs @@ -0,0 +1,81 @@ +//! The disk space check: what the first run needs on the assets, state and prefix volumes. + +use super::*; + +/// One volume: its label, the bytes the run needs there and the bytes free. +type Volume = (String, u64, u64); + +pub(super) fn check_disk(facts: &Facts, needs: &Needs, checks: &mut Vec) { + let (by_volume, notes) = volumes(facts, needs); + let problems: Vec = by_volume + .iter() + .filter(|(_, need, free)| free < need) + .map(|(label, need, free)| format!("{label}: {} free, {} needed", gib(*free), gib(*need))) + .collect(); + if problems.is_empty() { + let summary: Vec = by_volume + .iter() + .map(|(label, need, free)| { + format!("{label}: {} free (need {})", gib(*free), gib(*need)) + }) + .collect(); + checks.push(pass( + "disk", + "disk space", + [summary, notes].concat().join("; "), + )); + } else { + checks.push(check( + "disk", + Level::Fail, + "disk space", + problems.join("; "), + Some(disk_fix(needs)), + )); + } +} + +fn disk_fix(needs: &Needs) -> String { + format!( + "the first run needs about {} on the model volume (shards {}, archive {}); \ + point --assets at a larger volume. Nothing was downloaded yet", + gib(needs.shard_bytes_missing + needs.kar_bytes_missing), + gib(needs.shard_bytes_missing), + gib(needs + .kar_bytes_missing + .min(ARCHIVE_BYTES + ARCHIVE_BYTES / 5)) + ) +} + +/// The volumes whose free space is known, and a note for each one whose free space cannot be read. +fn volumes(facts: &Facts, needs: &Needs) -> (Vec, Vec) { + let mut by_volume = Vec::new(); + let mut notes = Vec::new(); + for (key, need) in volume_needs(facts, needs) { + let Some(dir) = facts.dirs.get(key) else { + continue; + }; + match dir.free_bytes { + Some(free) => by_volume.push((format!("{key} {}", dir.path.display()), need, free)), + None => notes.push(format!("cannot read free space of {}", dir.path.display())), + } + } + (by_volume, notes) +} + +fn volume_needs(facts: &Facts, needs: &Needs) -> [(&'static str, u64); 3] { + let cublas_download = needs.may_install_cublas && facts.lib("libcublas.so.12").is_none(); + let prefix_need = if needs.install_binaries || needs.may_install_cublas { + GIB + if cublas_download { 2 * GIB } else { 0 } + } else { + 0 + }; + [ + ( + "assets", + needs.shard_bytes_missing + needs.kar_bytes_missing + 2 * GIB, + ), + ("state", 2 * GIB), + ("prefix", prefix_need), + ] +} diff --git a/crates/deploy/src/preflight/download_hints.rs b/crates/deploy/src/preflight/download_hints.rs new file mode 100644 index 00000000..b403eba0 --- /dev/null +++ b/crates/deploy/src/preflight/download_hints.rs @@ -0,0 +1,69 @@ +//! Hints about what the first run downloads: the Hugging Face token and the VRAM expert tier. + +use super::*; + +pub(super) fn check_hf_token(facts: &Facts, needs: &Needs, checks: &mut Vec) { + if needs.shard_bytes_missing > 0 && !facts.hf_token_set { + checks.push(check( + "hf-token", + Level::Warn, + "Hugging Face token", + "HF_TOKEN is not set; the pinned shard repository is fetched anonymously".into(), + Some( + "if the download answers 401/403, export HF_TOKEN=... \ + (it is only sent to https://huggingface.co and never printed)" + .into(), + ), + )); + } +} + +pub(super) fn check_expert_tier(profile: &Profile, needs: &Needs, checks: &mut Vec) { + let Some(relative) = profile.expert_profile.as_deref() else { + return; + }; + let pinned = + crate::expert_profile::short_digest(crate::expert_profile::expected_digest(profile)); + let path = needs.assets_dir.join(relative).display().to_string(); + checks.extend(expert_tier(needs.expert_profile.as_ref(), &path, &pinned)); +} + +const WAY_OUT: &str = "run `leleka up` (it installs the pinned table that is embedded in the binary, or downloads it, \ + and checks the digest), or pass --expert-profile-file PATH offline; \ + --no-expert-tier accepts the slower decode"; + +fn expert_tier(state: Option<&ExpertProfileState>, path: &str, pinned: &str) -> Option { + Some(match state? { + ExpertProfileState::Valid => tier( + Level::Pass, + format!("ON: {path} has the pinned sha256 {pinned}"), + None, + ), + ExpertProfileState::Absent => tier_off( + format!( + "OFF until installed: {path} is not in the assets directory; \ + without the ranked table the engine runs without the VRAM expert tier (much slower)" + ), + Some(WAY_OUT.into()), + ), + ExpertProfileState::WrongDigest => tier_off( + format!( + "OFF: {path} does not have the pinned sha256 {pinned}; it will not be used (much slower)" + ), + Some(format!("move that file aside, then {WAY_OUT}")), + ), + ExpertProfileState::OptedOut => tier_off( + "OFF: --no-expert-tier was given; decode is much slower than with the ranked table" + .into(), + None, + ), + }) +} + +fn tier(level: Level, detail: String, fix: Option) -> Check { + check("expert-profile", level, "VRAM expert tier", detail, fix) +} + +fn tier_off(detail: String, fix: Option) -> Check { + tier(Level::Warn, detail, fix) +} diff --git a/crates/deploy/src/preflight/evaluate_fn.rs b/crates/deploy/src/preflight/evaluate_fn.rs deleted file mode 100644 index 893eb845..00000000 --- a/crates/deploy/src/preflight/evaluate_fn.rs +++ /dev/null @@ -1,670 +0,0 @@ -//! Moved out of the parent module by STRA-338: fn evaluate. - -#[allow(unused_imports)] -use super::*; - -pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { - let mut checks = Vec::new(); - - // 1. platform - let windows = facts.os == "windows"; - if (facts.os == "linux" || windows) && facts.arch == "x86_64" { - checks.push(pass( - "platform", - "platform", - if windows { - "windows x86_64 (native engine)" - } else { - "linux x86_64" - } - .into(), - )); - } else { - checks.push(check( - "platform", - Level::Fail, - "platform", - format!( - "{}/{} is not supported; the CUDA runtime is Linux x86_64 (or WSL2) and Windows x86_64 only", - facts.os, facts.arch - ), - Some("run on a Linux or Windows x86_64 host".into()), - )); - // Nothing else can be judged on another OS. - return Report { - profile: profile.name.clone(), - checks, - }; - } - - // 2. GPU, driver, architecture, VRAM - let gpu: Option<&Gpu> = facts.gpus.iter().find(|g| g.index == needs.gpu_index); - match gpu { - None => { - let reason = if !facts.nvidia_smi_found { - "nvidia-smi was not found".to_owned() - } else if let Some(error) = &facts.nvidia_smi_error { - format!("nvidia-smi failed: {error}") - } else { - format!( - "GPU {} is not present (found {} GPU(s))", - needs.gpu_index, - facts.gpus.len() - ) - }; - checks.push(check( - "gpu", - Level::Fail, - "NVIDIA GPU", - reason, - Some(if facts.wsl { - "WSL2: install the NVIDIA Windows driver (not a Linux driver inside WSL) and run `wsl --shutdown` once; nvidia-smi must work inside the distribution".into() - } else { - "install the NVIDIA driver (>= 595) and make sure `nvidia-smi` lists the GPU; choose another device with --gpu N".into() - }), - )); - } - Some(gpu) => { - checks.push(pass( - "gpu", - "NVIDIA GPU", - format!( - "{} (GPU {}, sm_{}, {} MiB, {} MiB free)", - gpu.name, - gpu.index, - gpu.sm.map_or("?".into(), |sm| sm.to_string()), - gpu.vram_total_mib, - gpu.vram_free_mib - ), - )); - // driver - match gpu.driver_major() { - Some(major) if major >= profile.min_driver_major => checks.push(pass( - "driver", - "driver version", - format!("{} (>= {})", gpu.driver, profile.min_driver_major), - )), - Some(_) => checks.push(check( - "driver", - Level::Fail, - "driver version", - format!( - "{} is older than {}; the sealed PTX needs ISA 9.2 (CUDA 13.2)", - gpu.driver, profile.min_driver_major - ), - Some(format!( - "update the NVIDIA driver to {} or newer ({})", - profile.min_driver_major, - if facts.wsl { - "the Windows driver on the host" - } else { - "e.g. the nvidia-driver-595 package" - } - )), - )), - None => checks.push(check( - "driver", - Level::Fail, - "driver version", - format!("cannot parse driver version {:?}", gpu.driver), - None, - )), - } - // architecture -> which sealed PTX serves this card - match gpu.sm { - Some(sm) if (120..130).contains(&sm) => checks.push(pass( - "arch", - "architecture", - format!("sm_{sm}: the sealed sm_120 PTX is used as is"), - )), - Some(sm) if (86..120).contains(&sm) => { - let (level, extra, fix) = match needs.binary_has_sm86 { - Some(true) => (Level::Pass, "binaries built with the sm86 feature".to_owned(), None), - Some(false) => ( - Level::Fail, - "these binaries were built WITHOUT the sm86 feature and cannot load on this card".to_owned(), - Some("use a release built with `--features sm86` (every release made by scripts/package-release.sh is)".into()), - ), - None => ( - Level::Warn, - "cannot tell whether the binaries carry the sm86 companions (no MANIFEST.json next to them)".to_owned(), - Some("run from an unpacked release tarball, or build with `--features sm86`".into()), - ), - }; - checks.push(check( - "arch", - level, - "architecture", - format!( - "sm_{sm}: sealed sm_86 companion PTX are selected at load; {extra}" - ), - fix, - )); - } - Some(sm) => checks.push(check( - "arch", - Level::Fail, - "architecture", - format!("sm_{sm} is below sm_86; no sealed PTX exists for it"), - Some("use an RTX 30-series or newer GPU".into()), - )), - None => checks.push(check( - "arch", - Level::Warn, - "architecture", - "compute capability unknown (old nvidia-smi); assuming the profile fits".into(), - Some("upgrade the driver so `nvidia-smi --query-gpu=compute_cap` works".into()), - )), - } - // VRAM - if gpu.vram_total_mib < profile.min_vram_total_mib { - checks.push(check( - "vram", - Level::Fail, - "GPU memory", - format!( - "{} MiB total is below the {} MiB the profile {} needs", - gpu.vram_total_mib, profile.min_vram_total_mib, profile.name - ), - Some("use a larger GPU or a smaller profile (--profile FILE)".into()), - )); - } else { - let budget_mib = profile.gpu_budget_bytes / (1 << 20); - let need_mib = profile.min_vram_free_mib.unwrap_or(budget_mib); - if gpu.vram_free_mib < need_mib { - checks.push(check( - "vram", - Level::Fail, - "GPU memory", - format!( - "{} MiB free but the engine needs {} MiB (budget {}); another process holds {} MiB", - gpu.vram_free_mib, - need_mib, - gib(profile.gpu_budget_bytes), - gpu.vram_total_mib.saturating_sub(gpu.vram_free_mib) - ), - Some(if facts.lab_holder { - "the lab KAR holder (kar_holder*.py) is running and its jobs use the GPU: the service and the lab queue exclude each other (docs/unattended.md, \"Lab mode\"); stop the holder (touch STOP in its jobs directory) or run the lab jobs instead".into() - } else { - "stop the other GPU users (`nvidia-smi` lists them), or lower the budget with --gpu-budget-gib N".into() - }), - )); - } else { - checks.push(pass( - "vram", - "GPU memory", - format!("{} MiB free, budget {} MiB", gpu.vram_free_mib, budget_mib), - )); - } - } - } - } - - // 2b. resource preset - if let Some(plan) = &needs.resources { - if plan.problems.is_empty() { - checks.push(pass( - "resources", - "resource preset", - format!( - "{}: {} CPU workers, VRAM budget {} MiB", - plan.preset.as_str(), - plan.cpu_workers - .map_or("default".to_owned(), |w| w.to_string()), - plan.gpu_budget_bytes / (1 << 20) - ), - )); - } else { - for problem in &plan.problems { - checks.push(check( - "resources", - Level::Fail, - "resource preset", - problem.clone(), - Some("rerun with --preset dedicated, or free the resource named above".into()), - )); - } - } - for warning in &plan.warnings { - checks.push(check( - "resources", - Level::Warn, - "resource preset", - warning.clone(), - None, - )); - } - } - - // 3. RAM - let ram = &facts.memory; - // An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains. - let min_available = if needs.kar_fd_inherited { - profile - .min_ram_available() - .saturating_sub(profile.memfd_bytes()) - .max(4 * GIB) - } else { - profile.min_ram_available() - }; - if ram.available == 0 && ram.total == 0 { - checks.push(check( - "ram", - Level::Fail, - "memory", - "cannot read /proc/meminfo".into(), - Some("mount /proc".into()), - )); - } else { - let mut level = Level::Pass; - let mut problems = Vec::new(); - if ram.total < profile.min_ram_total_bytes { - level = Level::Fail; - problems.push(format!( - "{} total is below the {} the profile needs", - gib(ram.total), - gib(profile.min_ram_total_bytes) - )); - } - if ram.available < min_available { - level = Level::Fail; - problems.push(format!( - "{} available is below the {} needed to start (kar_source={})", - gib(ram.available), - gib(min_available), - profile.kar_source.as_str() - )); - } - if let Some(limit) = facts.cgroup_memory_max - && limit < min_available - { - level = Level::Fail; - problems.push(format!( - "the cgroup memory limit {} is below the {} needed", - gib(limit), - gib(min_available) - )); - } - let fix = if level == Level::Fail { - Some(if facts.wsl { - let want = profile.wsl_memory_gib.unwrap_or(32); - format!( - "WSL2 gives this VM only {} of RAM. In %UserProfile%\\.wslconfig put:\n[wsl2]\nmemory={want}GB\nswap=8GB\nthen run `wsl --shutdown` from Windows and start the distribution again", - gib(ram.total) - ) - } else if profile.kar_source == KarSource::Memfd { - "free memory (the sealed archive copy needs the whole archive in RAM), or use the file-backed profile --profile rtx3080-16g if the GPU fits it".into() - } else { - "free memory or add RAM".into() - }) - } else { - None - }; - if problems.is_empty() { - problems.push(format!( - "{} total, {} available", - gib(ram.total), - gib(ram.available) - )); - } - checks.push(check("ram", level, "memory", problems.join("; "), fix)); - } - - // 4. KAR source prerequisites - if windows { - if profile.kar_source == KarSource::Memfd { - checks.push(check( - "memfd", - Level::Fail, - "KAR source", - format!("the profile {} holds the archive in a sealed memfd, which Windows does not have", profile.name), - Some("use a profile with kar_source=file (rtx3080-16g), or the WSL2 route".into()), - )); - } else { - checks.push(pass( - "memfd", - "KAR file mode", - "the archive is opened read-only (shared for reading only) from the model volume" - .into(), - )); - } - if profile.expert_source == ExpertSource::Resident { - checks.push(check( - "expert-source", - Level::Fail, - "expert source", - format!("the profile {} copies the experts into locked RAM; the Windows engine serves them from memory-mapped shards only", profile.name), - Some("use a profile with expert_source=mapped (rtx3080-16g)".into()), - )); - } - } else if profile.kar_source == KarSource::Memfd { - if facts.proc_fd && facts.memfd_ok { - checks.push(pass( - "memfd", - "sealed memfd", - "memfd_create with sealing works and /proc/self/fd is mounted".into(), - )); - } else { - checks.push(check( - "memfd", - Level::Fail, - "sealed memfd", - format!( - "{}{}", - if facts.proc_fd { "" } else { "/proc/self/fd is not mounted; " }, - if facts.memfd_ok { "" } else { "memfd_create with F_SEAL_* failed (kernel < 3.17 or a seccomp filter)" } - ), - Some("run on a host kernel with memfd sealing; in a container allow memfd_create (default Docker seccomp does) and mount /proc".into()), - )); - } - } else if facts.proc_fd { - checks.push(pass( - "memfd", - "KAR file mode", - "the archive is opened read-only from the model volume".into(), - )); - } else { - checks.push(check( - "memfd", - Level::Warn, - "KAR file mode", - "/proc/self/fd is not mounted".into(), - Some("mount /proc".into()), - )); - } - - // 5. cuBLAS 12 - let blas = facts.lib("libcublas.so.12"); - let blas_lt = facts.lib("libcublasLt.so.12"); - let (blas_name, blas_lt_name, cuda_name) = if windows { - ("cublas64_12.dll", "cublasLt64_12.dll", "nvcuda.dll") - } else { - ("libcublas.so.12", "libcublasLt.so.12", "libcuda.so.1") - }; - match (blas, blas_lt) { - (Some(path), Some(_)) => checks.push(pass( - "cublas", - "cuBLAS 12", - format!("{blas_name} and {blas_lt_name} found ({})", path.display()), - )), - _ if needs.may_install_cublas => { - let mut missing = Vec::new(); - if blas.is_none() { - missing.push(blas_name); - } - if blas_lt.is_none() { - missing.push(blas_lt_name); - } - let tools_ok = (facts.tool("curl") || facts.tool("wget")) && facts.tool("tar") && facts.tool("xz"); - checks.push(check( - "cublas", - if tools_ok { Level::Warn } else { Level::Fail }, - "cuBLAS 12", - format!( - "{} not found; the pinned NVIDIA redistributable (~{} MiB) will be downloaded into the prefix{}", - missing.join(", "), - needs.cublas_download_bytes / (1 << 20), - if tools_ok { "" } else { ", but curl/wget, tar and xz are required for that" } - ), - Some("apt install curl xz-utils (or pass --cublas-dir DIR with CUDA 12 cuBLAS), or --no-install-cublas to supply it yourself".into()), - )); - } - _ => checks.push(check( - "cublas", - Level::Fail, - "cuBLAS 12", - format!("{blas_name} / {blas_lt_name} not found; leleka-inference loads them by name"), - Some(if windows { - "pass --cublas-dir DIR with the two CUDA 12 cuBLAS DLLs (from a CUDA 12.x toolkit's bin folder or the NVIDIA libcublas 12.9.1.4 windows-x86_64 redistributable zip, docs/windows.md); `leleka run` makes the engine's loader search that directory".into() - } else { - "pass --cublas-dir DIR (CUDA 12 cuBLAS), drop --no-install-cublas to let `up` download the pinned 12.9.1.4 redistributable, or apt install libcublas12".into() - }), - )), - } - match facts.lib("libcuda.so.1") { - Some(path) => checks.push(pass("libcuda", "CUDA driver library", format!("{}", path.display()))), - None => checks.push(check( - "libcuda", - Level::Warn, - "CUDA driver library", - format!("{cuda_name} was not found by the library search (the engine loads it)"), - Some(if windows { - "install the NVIDIA display driver (nvcuda.dll comes with it)".into() - } else if facts.wsl { - "WSL2 provides it in /usr/lib/wsl/lib; make sure that directory is not removed from the loader path".into() - } else { - "install the NVIDIA driver's libcuda (nvidia-utils / libnvidia-compute packages)".into() - }), - )), - } - - // 6. WSL specifics - if facts.wsl { - let slow: Vec = ["assets", "state", "prefix"] - .iter() - .filter_map(|key| facts.dirs.get(*key)) - .filter(|dir| dir.fs_type.as_deref().is_some_and(is_slow_foreign_fs)) - .map(|dir| { - format!( - "{} ({})", - dir.path.display(), - dir.fs_type.as_deref().unwrap_or("?") - ) - }) - .collect(); - if slow.is_empty() { - checks.push(pass( - "wsl", - "WSL2", - "model volume is on the Linux file system".into(), - )); - } else { - checks.push(check( - "wsl", - Level::Fail, - "WSL2 file system", - format!("{} is on a Windows/network mount; mapped and direct reads are far too slow there", slow.join(", ")), - Some("put --assets (and --state-dir) on the WSL ext4 disk, e.g. under ~/leleka, not under /mnt/c".into()), - )); - } - } - - // 7. disk space - let mut disk_problems = Vec::new(); - let mut disk_notes = Vec::new(); - let mut by_volume: Vec<(String, u64, u64)> = Vec::new(); // (label, need, free) - let assets_need = needs.shard_bytes_missing + needs.kar_bytes_missing + 2 * GIB; - let state_need = 2 * GIB; - let prefix_need = if needs.install_binaries || needs.may_install_cublas { - GIB + if needs.may_install_cublas && blas.is_none() { - 2 * GIB - } else { - 0 - } - } else { - 0 - }; - for (key, need) in [ - ("assets", assets_need), - ("state", state_need), - ("prefix", prefix_need), - ] { - if let Some(dir) = facts.dirs.get(key) { - match dir.free_bytes { - Some(free) => by_volume.push((format!("{key} {}", dir.path.display()), need, free)), - None => { - disk_notes.push(format!("cannot read free space of {}", dir.path.display())) - } - } - } - } - for (label, need, free) in &by_volume { - if free < need { - disk_problems.push(format!( - "{label}: {} free, {} needed", - gib(*free), - gib(*need) - )); - } - } - if disk_problems.is_empty() { - let summary: Vec = by_volume - .iter() - .map(|(label, need, free)| { - format!("{label}: {} free (need {})", gib(*free), gib(*need)) - }) - .collect(); - checks.push(pass( - "disk", - "disk space", - [summary, disk_notes].concat().join("; "), - )); - } else { - checks.push(check( - "disk", - Level::Fail, - "disk space", - disk_problems.join("; "), - Some(format!( - "the first run needs about {} on the model volume (shards {}, archive {}); point --assets at a larger volume. Nothing was downloaded yet", - gib(needs.shard_bytes_missing + needs.kar_bytes_missing), - gib(needs.shard_bytes_missing), - gib(needs.kar_bytes_missing.min(ARCHIVE_BYTES + ARCHIVE_BYTES / 5)) - )), - )); - } - - // 8. tools and service manager - if needs.wants_systemd { - if facts.systemd_system && facts.tool("systemctl") { - checks.push(pass( - "systemd", - "systemd", - "systemd is PID 1 and systemctl is available".into(), - )); - } else { - checks.push(check( - "systemd", - Level::Fail, - "systemd", - "systemd is not running as the service manager here".into(), - Some(if facts.wsl { - "WSL2: add `[boot]\\nsystemd=true` to /etc/wsl.conf and `wsl --shutdown`, or run with --foreground".into() - } else { - "use --foreground to run the service in this terminal".into() - }), - )); - } - } - - // 9. ports - let busy: Vec = needs - .service_ports - .iter() - .filter(|(_, port)| facts.busy_ports.contains(port)) - .map(|(name, port)| format!("{name} {port}")) - .collect(); - if busy.is_empty() { - checks.push(pass("ports", "loopback ports", "free".into())); - } else if needs.service_running { - checks.push(pass( - "ports", - "loopback ports", - format!("{} in use by the running Leleka service", busy.join(", ")), - )); - } else { - checks.push(check( - "ports", - Level::Fail, - "loopback ports", - format!("already in use: {}", busy.join(", ")), - Some("stop the other listener or pick other ports with --api-port / --engine-port / --daemon-port".into()), - )); - } - - if needs.api_bind_open { - checks.push(check( - "api-bind", - Level::Warn, - "API listen address", - "the API is bound beyond the loopback interface; the bearer key is its only protection and there is no TLS".into(), - Some("publish the port to 127.0.0.1 only (docker run -p 127.0.0.1:8081:8081) or put a TLS proxy / SSH tunnel in front".into()), - )); - } - - // 10. binaries - if needs.require_binaries { - let missing: Vec<&String> = facts - .binaries - .iter() - .filter(|(_, ok)| !**ok) - .map(|(name, _)| name) - .collect(); - if missing.is_empty() { - checks.push(pass( - "binaries", - "binaries", - "all six runtime binaries are present".into(), - )); - } else { - checks.push(check( - "binaries", - Level::Fail, - "binaries", - format!("missing or not executable: {}", missing.iter().map(|s| s.as_str()).collect::>().join(", ")), - Some("run `leleka up` from the unpacked release tarball (bin/), or pass --bin-src DIR".into()), - )); - } - } - - // 11. gated assets / credentials hints - if (needs.shard_bytes_missing > 0) && !facts.hf_token_set { - checks.push(check( - "hf-token", - Level::Warn, - "Hugging Face token", - "HF_TOKEN is not set; the pinned shard repository is fetched anonymously".into(), - Some("if the download answers 401/403, export HF_TOKEN=... (it is only sent to https://huggingface.co and never printed)".into()), - )); - } - if let Some(relative) = profile.expert_profile.as_deref() { - let pinned = - crate::expert_profile::short_digest(crate::expert_profile::expected_digest(profile)); - let path = needs.assets_dir.join(relative).display().to_string(); - let way_out = "run `leleka up` (it installs the pinned table that is embedded in the binary, or downloads it, and checks the digest), or pass --expert-profile-file PATH offline; --no-expert-tier accepts the slower decode"; - match &needs.expert_profile { - Some(ExpertProfileState::Valid) => checks.push(pass( - "expert-profile", - "VRAM expert tier", - format!("ON: {path} has the pinned sha256 {pinned}"), - )), - Some(ExpertProfileState::Absent) => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - format!("OFF until installed: {path} is not in the assets directory; without the ranked table the engine runs without the VRAM expert tier (much slower)"), - Some(way_out.into()), - )), - Some(ExpertProfileState::WrongDigest) => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - format!("OFF: {path} does not have the pinned sha256 {pinned}; it will not be used (much slower)"), - Some(format!("move that file aside, then {way_out}")), - )), - Some(ExpertProfileState::OptedOut) => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - "OFF: --no-expert-tier was given; decode is much slower than with the ranked table".into(), - None, - )), - None => {} - } - } - - Report { - profile: profile.name.clone(), - checks, - } -} diff --git a/crates/deploy/src/preflight/evaluation.rs b/crates/deploy/src/preflight/evaluation.rs new file mode 100644 index 00000000..0988d8e9 --- /dev/null +++ b/crates/deploy/src/preflight/evaluation.rs @@ -0,0 +1,32 @@ +//! The preflight run: every check in order, over the host facts, the profile and what the plan needs. + +use super::*; + +pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { + let mut checks = Vec::new(); + // Nothing else can be judged on another OS. + if platform::check_platform(facts, &mut checks) { + run_checks(facts, profile, needs, &mut checks); + } + Report { + profile: profile.name.clone(), + checks, + } +} + +fn run_checks(facts: &Facts, profile: &Profile, needs: &Needs, checks: &mut Vec) { + gpu::check_gpu(facts, profile, needs, checks); + resource_preset::check_resource_preset(needs, checks); + memory::check_ram(facts, profile, needs, checks); + kar_source::check_kar_source(facts, profile, checks); + cuda_libraries::check_cublas(facts, needs, checks); + cuda_libraries::check_libcuda(facts, checks); + wsl_filesystem::check_wsl_filesystem(facts, checks); + disk::check_disk(facts, needs, checks); + service_host::check_systemd(facts, needs, checks); + service_host::check_ports(facts, needs, checks); + service_host::check_api_bind(needs, checks); + service_host::check_binaries(facts, needs, checks); + download_hints::check_hf_token(facts, needs, checks); + download_hints::check_expert_tier(profile, needs, checks); +} diff --git a/crates/deploy/src/preflight/gpu.rs b/crates/deploy/src/preflight/gpu.rs new file mode 100644 index 00000000..d29b725f --- /dev/null +++ b/crates/deploy/src/preflight/gpu.rs @@ -0,0 +1,193 @@ +//! The GPU checks: presence, driver version, architecture and memory. + +use super::*; + +/// Pushes the GPU check and, when the GPU is there, the driver, architecture and memory checks. +pub(super) fn check_gpu(facts: &Facts, profile: &Profile, needs: &Needs, checks: &mut Vec) { + match facts.gpus.iter().find(|g| g.index == needs.gpu_index) { + None => checks.push(missing_gpu(facts, needs)), + Some(gpu) => { + checks.push(found_gpu(gpu)); + checks.push(driver_check(facts, profile, gpu)); + checks.push(arch_check(needs, gpu)); + checks.push(vram_check(facts, profile, gpu)); + } + } +} + +fn missing_gpu(facts: &Facts, needs: &Needs) -> Check { + let reason = if !facts.nvidia_smi_found { + "nvidia-smi was not found".to_owned() + } else if let Some(error) = &facts.nvidia_smi_error { + format!("nvidia-smi failed: {error}") + } else { + format!( + "GPU {} is not present (found {} GPU(s))", + needs.gpu_index, + facts.gpus.len() + ) + }; + let fix = if facts.wsl { + "WSL2: install the NVIDIA Windows driver (not a Linux driver inside WSL) and run `wsl --shutdown` once; \ + nvidia-smi must work inside the distribution" + } else { + "install the NVIDIA driver (>= 595) and make sure `nvidia-smi` lists the GPU; \ + choose another device with --gpu N" + }; + check("gpu", Level::Fail, "NVIDIA GPU", reason, Some(fix.into())) +} + +fn found_gpu(gpu: &Gpu) -> Check { + pass( + "gpu", + "NVIDIA GPU", + format!( + "{} (GPU {}, sm_{}, {} MiB, {} MiB free)", + gpu.name, + gpu.index, + gpu.sm.map_or("?".into(), |sm| sm.to_string()), + gpu.vram_total_mib, + gpu.vram_free_mib + ), + ) +} + +fn driver_check(facts: &Facts, profile: &Profile, gpu: &Gpu) -> Check { + match gpu.driver_major() { + Some(major) if major >= profile.min_driver_major => pass( + "driver", + "driver version", + format!("{} (>= {})", gpu.driver, profile.min_driver_major), + ), + Some(_) => driver_too_old(facts, profile, gpu), + None => check( + "driver", + Level::Fail, + "driver version", + format!("cannot parse driver version {:?}", gpu.driver), + None, + ), + } +} + +fn driver_too_old(facts: &Facts, profile: &Profile, gpu: &Gpu) -> Check { + let source = if facts.wsl { + "the Windows driver on the host" + } else { + "e.g. the nvidia-driver-595 package" + }; + check( + "driver", + Level::Fail, + "driver version", + format!( + "{} is older than {}; the sealed PTX needs ISA 9.2 (CUDA 13.2)", + gpu.driver, profile.min_driver_major + ), + Some(format!( + "update the NVIDIA driver to {} or newer ({source})", + profile.min_driver_major + )), + ) +} + +/// Which sealed PTX serves this card. +fn arch_check(needs: &Needs, gpu: &Gpu) -> Check { + match gpu.sm { + Some(sm) if (120..130).contains(&sm) => pass( + "arch", + "architecture", + format!("sm_{sm}: the sealed sm_120 PTX is used as is"), + ), + Some(sm) if (86..120).contains(&sm) => sm86_check(sm, needs.binary_has_sm86), + Some(sm) => check( + "arch", + Level::Fail, + "architecture", + format!("sm_{sm} is below sm_86; no sealed PTX exists for it"), + Some("use an RTX 30-series or newer GPU".into()), + ), + None => check( + "arch", + Level::Warn, + "architecture", + "compute capability unknown (old nvidia-smi); assuming the profile fits".into(), + Some("upgrade the driver so `nvidia-smi --query-gpu=compute_cap` works".into()), + ), + } +} + +fn sm86_check(sm: u32, binary_has_sm86: Option) -> Check { + let (level, extra, fix) = match binary_has_sm86 { + Some(true) => (Level::Pass, "binaries built with the sm86 feature".to_owned(), None), + Some(false) => ( + Level::Fail, + "these binaries were built WITHOUT the sm86 feature and cannot load on this card".to_owned(), + Some( + "use a release built with `--features sm86` \ + (every release made by scripts/package-release.sh is)" + .into(), + ), + ), + None => ( + Level::Warn, + "cannot tell whether the binaries carry the sm86 companions (no MANIFEST.json next to them)".to_owned(), + Some("run from an unpacked release tarball, or build with `--features sm86`".into()), + ), + }; + check( + "arch", + level, + "architecture", + format!("sm_{sm}: sealed sm_86 companion PTX are selected at load; {extra}"), + fix, + ) +} + +fn vram_check(facts: &Facts, profile: &Profile, gpu: &Gpu) -> Check { + if gpu.vram_total_mib < profile.min_vram_total_mib { + return check( + "vram", + Level::Fail, + "GPU memory", + format!( + "{} MiB total is below the {} MiB the profile {} needs", + gpu.vram_total_mib, profile.min_vram_total_mib, profile.name + ), + Some("use a larger GPU or a smaller profile (--profile FILE)".into()), + ); + } + let budget_mib = profile.gpu_budget_bytes / (1 << 20); + let need_mib = profile.min_vram_free_mib.unwrap_or(budget_mib); + if gpu.vram_free_mib < need_mib { + return vram_taken(facts, profile, gpu, need_mib); + } + pass( + "vram", + "GPU memory", + format!("{} MiB free, budget {} MiB", gpu.vram_free_mib, budget_mib), + ) +} + +fn vram_taken(facts: &Facts, profile: &Profile, gpu: &Gpu, need_mib: u64) -> Check { + let fix = if facts.lab_holder { + "the lab KAR holder (kar_holder*.py) is running and its jobs use the GPU: the service and the lab queue \ + exclude each other (docs/unattended.md, \"Lab mode\"); stop the holder (touch STOP in its jobs directory) \ + or run the lab jobs instead" + } else { + "stop the other GPU users (`nvidia-smi` lists them), or lower the budget with --gpu-budget-gib N" + }; + check( + "vram", + Level::Fail, + "GPU memory", + format!( + "{} MiB free but the engine needs {} MiB (budget {}); another process holds {} MiB", + gpu.vram_free_mib, + need_mib, + gib(profile.gpu_budget_bytes), + gpu.vram_total_mib.saturating_sub(gpu.vram_free_mib) + ), + Some(fix.into()), + ) +} diff --git a/crates/deploy/src/preflight/kar_source.rs b/crates/deploy/src/preflight/kar_source.rs new file mode 100644 index 00000000..067bcb90 --- /dev/null +++ b/crates/deploy/src/preflight/kar_source.rs @@ -0,0 +1,102 @@ +//! The KAR source prerequisites: a sealed memfd on Linux, a read-only archive file elsewhere. + +use super::*; + +pub(super) fn check_kar_source(facts: &Facts, profile: &Profile, checks: &mut Vec) { + if facts.os == "windows" { + checks.push(windows_memfd(profile)); + checks.extend(windows_expert_source(profile)); + } else if profile.kar_source == KarSource::Memfd { + checks.push(sealed_memfd(facts)); + } else { + checks.push(file_mode(facts)); + } +} + +fn windows_memfd(profile: &Profile) -> Check { + if profile.kar_source != KarSource::Memfd { + return pass( + "memfd", + "KAR file mode", + "the archive is opened read-only (shared for reading only) from the model volume" + .into(), + ); + } + check( + "memfd", + Level::Fail, + "KAR source", + format!( + "the profile {} holds the archive in a sealed memfd, which Windows does not have", + profile.name + ), + Some("use a profile with kar_source=file (rtx3080-16g), or the WSL2 route".into()), + ) +} + +fn windows_expert_source(profile: &Profile) -> Option { + if profile.expert_source != ExpertSource::Resident { + return None; + } + Some(check( + "expert-source", + Level::Fail, + "expert source", + format!( + "the profile {} copies the experts into locked RAM; \ + the Windows engine serves them from memory-mapped shards only", + profile.name + ), + Some("use a profile with expert_source=mapped (rtx3080-16g)".into()), + )) +} + +fn sealed_memfd(facts: &Facts) -> Check { + if facts.proc_fd && facts.memfd_ok { + return pass( + "memfd", + "sealed memfd", + "memfd_create with sealing works and /proc/self/fd is mounted".into(), + ); + } + let fix = "run on a host kernel with memfd sealing; in a container allow memfd_create \ + (default Docker seccomp does) and mount /proc"; + check( + "memfd", + Level::Fail, + "sealed memfd", + memfd_failure(facts), + Some(fix.into()), + ) +} + +fn memfd_failure(facts: &Facts) -> String { + let proc = if facts.proc_fd { + "" + } else { + "/proc/self/fd is not mounted; " + }; + let seals = if facts.memfd_ok { + "" + } else { + "memfd_create with F_SEAL_* failed (kernel < 3.17 or a seccomp filter)" + }; + format!("{proc}{seals}") +} + +fn file_mode(facts: &Facts) -> Check { + if facts.proc_fd { + return pass( + "memfd", + "KAR file mode", + "the archive is opened read-only from the model volume".into(), + ); + } + check( + "memfd", + Level::Warn, + "KAR file mode", + "/proc/self/fd is not mounted".into(), + Some("mount /proc".into()), + ) +} diff --git a/crates/deploy/src/preflight/memory.rs b/crates/deploy/src/preflight/memory.rs new file mode 100644 index 00000000..978a6833 --- /dev/null +++ b/crates/deploy/src/preflight/memory.rs @@ -0,0 +1,88 @@ +//! The RAM check: the total, the available memory and the cgroup limit against what the profile needs to start. + +use super::*; + +pub(super) fn check_ram(facts: &Facts, profile: &Profile, needs: &Needs, checks: &mut Vec) { + let ram = &facts.memory; + if ram.available == 0 && ram.total == 0 { + checks.push(check( + "ram", + Level::Fail, + "memory", + "cannot read /proc/meminfo".into(), + Some("mount /proc".into()), + )); + return; + } + let mut problems = ram_problems(facts, profile, min_available(profile, needs)); + let (level, fix) = if problems.is_empty() { + problems.push(format!( + "{} total, {} available", + gib(ram.total), + gib(ram.available) + )); + (Level::Pass, None) + } else { + (Level::Fail, Some(ram_fix(facts, profile))) + }; + checks.push(check("ram", level, "memory", problems.join("; "), fix)); +} + +/// An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains. +fn min_available(profile: &Profile, needs: &Needs) -> u64 { + if needs.kar_fd_inherited { + profile + .min_ram_available() + .saturating_sub(profile.memfd_bytes()) + .max(4 * GIB) + } else { + profile.min_ram_available() + } +} + +fn ram_problems(facts: &Facts, profile: &Profile, min_available: u64) -> Vec { + let ram = &facts.memory; + let mut problems = Vec::new(); + if ram.total < profile.min_ram_total_bytes { + problems.push(format!( + "{} total is below the {} the profile needs", + gib(ram.total), + gib(profile.min_ram_total_bytes) + )); + } + if ram.available < min_available { + problems.push(format!( + "{} available is below the {} needed to start (kar_source={})", + gib(ram.available), + gib(min_available), + profile.kar_source.as_str() + )); + } + if let Some(limit) = facts.cgroup_memory_max + && limit < min_available + { + problems.push(format!( + "the cgroup memory limit {} is below the {} needed", + gib(limit), + gib(min_available) + )); + } + problems +} + +fn ram_fix(facts: &Facts, profile: &Profile) -> String { + if facts.wsl { + let want = profile.wsl_memory_gib.unwrap_or(32); + format!( + "WSL2 gives this VM only {} of RAM. In %UserProfile%\\.wslconfig put:\n[wsl2]\nmemory={want}GB\nswap=8GB\n\ + then run `wsl --shutdown` from Windows and start the distribution again", + gib(facts.memory.total) + ) + } else if profile.kar_source == KarSource::Memfd { + "free memory (the sealed archive copy needs the whole archive in RAM), or use the file-backed profile \ + --profile rtx3080-16g if the GPU fits it" + .into() + } else { + "free memory or add RAM".into() + } +} diff --git a/crates/deploy/src/preflight/platform.rs b/crates/deploy/src/preflight/platform.rs new file mode 100644 index 00000000..4224f832 --- /dev/null +++ b/crates/deploy/src/preflight/platform.rs @@ -0,0 +1,28 @@ +//! The platform check: the CUDA runtime runs on Linux x86_64 (or WSL2) and on Windows x86_64 only. + +use super::*; + +/// Pushes the platform check; `false` when nothing else can be judged on this OS. +pub(super) fn check_platform(facts: &Facts, checks: &mut Vec) -> bool { + let windows = facts.os == "windows"; + if (facts.os == "linux" || windows) && facts.arch == "x86_64" { + let detail = if windows { + "windows x86_64 (native engine)" + } else { + "linux x86_64" + }; + checks.push(pass("platform", "platform", detail.into())); + return true; + } + checks.push(check( + "platform", + Level::Fail, + "platform", + format!( + "{}/{} is not supported; the CUDA runtime is Linux x86_64 (or WSL2) and Windows x86_64 only", + facts.os, facts.arch + ), + Some("run on a Linux or Windows x86_64 host".into()), + )); + false +} diff --git a/crates/deploy/src/preflight/impl_report.rs b/crates/deploy/src/preflight/report.rs similarity index 94% rename from crates/deploy/src/preflight/impl_report.rs rename to crates/deploy/src/preflight/report.rs index 1ead21e3..fe863f9f 100644 --- a/crates/deploy/src/preflight/impl_report.rs +++ b/crates/deploy/src/preflight/report.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl Report, fn gib, fn check, fn pass. +//! The preflight report: its text rendering and the constructors of a check. #[allow(unused_imports)] use super::*; diff --git a/crates/deploy/src/preflight/resource_preset.rs b/crates/deploy/src/preflight/resource_preset.rs new file mode 100644 index 00000000..f45e648c --- /dev/null +++ b/crates/deploy/src/preflight/resource_preset.rs @@ -0,0 +1,46 @@ +//! The resource preset: its numbers, and its shortfalls and warnings as checks. + +use super::*; +use crate::resources::ResourcePlan; + +pub(super) fn check_resource_preset(needs: &Needs, checks: &mut Vec) { + let Some(plan) = &needs.resources else { + return; + }; + if plan.problems.is_empty() { + checks.push(preset_summary(plan)); + } + for problem in &plan.problems { + checks.push(check( + "resources", + Level::Fail, + "resource preset", + problem.clone(), + Some("rerun with --preset dedicated, or free the resource named above".into()), + )); + } + for warning in &plan.warnings { + checks.push(check( + "resources", + Level::Warn, + "resource preset", + warning.clone(), + None, + )); + } +} + +fn preset_summary(plan: &ResourcePlan) -> Check { + let workers = plan + .cpu_workers + .map_or("default".to_owned(), |w| w.to_string()); + pass( + "resources", + "resource preset", + format!( + "{}: {workers} CPU workers, VRAM budget {} MiB", + plan.preset.as_str(), + plan.gpu_budget_bytes / (1 << 20) + ), + ) +} diff --git a/crates/deploy/src/preflight/service_host.rs b/crates/deploy/src/preflight/service_host.rs new file mode 100644 index 00000000..2b7be8b1 --- /dev/null +++ b/crates/deploy/src/preflight/service_host.rs @@ -0,0 +1,103 @@ +//! The service host: systemd, the loopback ports, the API bind address and the runtime binaries. + +use super::*; + +pub(super) fn check_systemd(facts: &Facts, needs: &Needs, checks: &mut Vec) { + if !needs.wants_systemd { + return; + } + if facts.systemd_system && facts.tool("systemctl") { + checks.push(pass( + "systemd", + "systemd", + "systemd is PID 1 and systemctl is available".into(), + )); + return; + } + let fix = if facts.wsl { + "WSL2: add `[boot]\\nsystemd=true` to /etc/wsl.conf and `wsl --shutdown`, or run with --foreground" + } else { + "use --foreground to run the service in this terminal" + }; + checks.push(check( + "systemd", + Level::Fail, + "systemd", + "systemd is not running as the service manager here".into(), + Some(fix.into()), + )); +} + +pub(super) fn check_ports(facts: &Facts, needs: &Needs, checks: &mut Vec) { + let busy: Vec = needs + .service_ports + .iter() + .filter(|(_, port)| facts.busy_ports.contains(port)) + .map(|(name, port)| format!("{name} {port}")) + .collect(); + if busy.is_empty() { + checks.push(pass("ports", "loopback ports", "free".into())); + } else if needs.service_running { + checks.push(pass( + "ports", + "loopback ports", + format!("{} in use by the running Leleka service", busy.join(", ")), + )); + } else { + checks.push(check( + "ports", + Level::Fail, + "loopback ports", + format!("already in use: {}", busy.join(", ")), + Some("stop the other listener or pick other ports with --api-port / --engine-port / --daemon-port".into()), + )); + } +} + +pub(super) fn check_api_bind(needs: &Needs, checks: &mut Vec) { + if !needs.api_bind_open { + return; + } + checks.push(check( + "api-bind", + Level::Warn, + "API listen address", + "the API is bound beyond the loopback interface; the bearer key is its only protection and there is no TLS" + .into(), + Some( + "publish the port to 127.0.0.1 only (docker run -p 127.0.0.1:8081:8081) \ + or put a TLS proxy / SSH tunnel in front" + .into(), + ), + )); +} + +pub(super) fn check_binaries(facts: &Facts, needs: &Needs, checks: &mut Vec) { + if !needs.require_binaries { + return; + } + let missing: Vec<&str> = facts + .binaries + .iter() + .filter(|(_, ok)| !**ok) + .map(|(name, _)| name.as_str()) + .collect(); + if missing.is_empty() { + checks.push(pass( + "binaries", + "binaries", + "all six runtime binaries are present".into(), + )); + } else { + checks.push(check( + "binaries", + Level::Fail, + "binaries", + format!("missing or not executable: {}", missing.join(", ")), + Some( + "run `leleka up` from the unpacked release tarball (bin/), or pass --bin-src DIR" + .into(), + ), + )); + } +} diff --git a/crates/deploy/src/preflight/tests.rs b/crates/deploy/src/preflight/tests.rs index 56299314..c2721d44 100644 --- a/crates/deploy/src/preflight/tests.rs +++ b/crates/deploy/src/preflight/tests.rs @@ -77,399 +77,8 @@ fn level_of(report: &Report, id: &str) -> Level { .level } -#[test] -fn the_expert_tier_is_always_reported_on_or_off() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let report_for = |state: Option| { - let mut n = needs(); - n.expert_profile = state; - evaluate(&server_facts(), &profile, &n) - }; - let report = report_for(Some(ExpertProfileState::Valid)); - assert_eq!(level_of(&report, "expert-profile"), Level::Pass); - assert!(report.render().contains("ON:") && report.render().contains("8f59b4aa...388975baf")); - for (state, needle) in [ - (ExpertProfileState::Absent, "OFF until installed"), - ( - ExpertProfileState::WrongDigest, - "does not have the pinned sha256", - ), - (ExpertProfileState::OptedOut, "--no-expert-tier was given"), - ] { - let report = report_for(Some(state)); - assert_eq!(level_of(&report, "expert-profile"), Level::Warn); - let text = report.render(); - assert!(text.contains("OFF") && text.contains(needle), "{text}"); - } - // an absent table names the way out - assert!( - report_for(Some(ExpertProfileState::Absent)) - .render() - .contains("--expert-profile-file") - ); -} - -#[test] -fn healthy_server_passes_everything() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let report = evaluate(&server_facts(), &profile, &needs()); - assert!(!report.failed(), "{}", report.render()); - assert_eq!(level_of(&report, "arch"), Level::Pass); - assert_eq!(level_of(&report, "memfd"), Level::Pass); -} - -#[test] -fn old_driver_and_busy_gpu_fail_with_actionable_text() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].driver = "580.65.06".into(); - facts.gpus[0].vram_free_mib = 9000; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "driver"), Level::Fail); - assert_eq!(level_of(&report, "vram"), Level::Fail); - let text = report.render(); - assert!(text.contains("580.65.06 is older than 595"), "{text}"); - assert!(text.contains("--gpu-budget-gib"), "{text}"); -} - -#[test] -fn a_running_lab_holder_is_named_as_the_reason_the_gpu_is_taken() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].vram_free_mib = 1200; - facts.lab_holder = true; - let text = evaluate(&facts, &profile, &needs()).render(); - assert!( - text.contains("kar_holder") && text.contains("Lab mode"), - "{text}" - ); - facts.lab_holder = false; - let text = evaluate(&facts, &profile, &needs()).render(); - assert!( - !text.contains("kar_holder") && text.contains("--gpu-budget-gib"), - "{text}" - ); -} - -#[test] -fn no_gpu_names_the_wsl_remedy_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus.clear(); - facts.nvidia_smi_found = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "gpu"), Level::Fail); - assert!(report.render().contains("Windows driver")); -} - -#[test] -fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.gpus[0] = Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15234, - sm: Some(86), - }; - facts.memory = Memory { - total: 12 * GIB, - available: 9 * GIB, - swap_total: 0, - }; - let mut n = needs(); - n.binary_has_sm86 = Some(true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "ram"), Level::Fail); - let text = report.render(); - assert!( - text.contains(".wslconfig") - && text.contains("memory=32GB") - && text.contains("wsl --shutdown"), - "{text}" - ); - assert_eq!(level_of(&report, "arch"), Level::Pass); - // 24 GB as WSL2 gives by default passes. - facts.memory = Memory { - total: 24_447_308 * 1024, - available: 22 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &profile, &n); - assert!(!report.failed(), "{}", report.render()); -} - -#[test] -fn sm86_card_needs_binaries_with_the_companion_feature() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].sm = Some(86); - facts.gpus[0].vram_total_mib = 16384; - facts.gpus[0].vram_free_mib = 15000; - let mut n = needs(); - n.binary_has_sm86 = Some(false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Fail - ); - n.binary_has_sm86 = None; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Warn - ); -} - -#[test] -fn model_volume_on_a_windows_mount_is_refused_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "wsl"), Level::Fail); - assert!(report.render().contains("/mnt/c")); -} - -#[test] -fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.libs.insert("libcublas.so.12".into(), None); - facts.libs.insert("libcublasLt.so.12".into(), None); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Warn - ); - facts.tools.insert("xz".into(), false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Fail - ); - let mut n = needs(); - n.may_install_cublas = false; - facts.tools.insert("xz".into(), true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "cublas"), Level::Fail); - assert!(report.render().contains("--cublas-dir")); -} - -#[test] -fn low_disk_reports_the_volume_before_anything_is_downloaded() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "disk"), Level::Fail); - let text = report.render(); - assert!( - text.contains("assets /data/assets: 53.0 GiB free"), - "{text}" - ); - assert!(text.contains("Nothing was downloaded yet"), "{text}"); - // With the model already present the same volume is fine. - let mut n = needs(); - n.shard_bytes_missing = 0; - n.kar_bytes_missing = 0; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "disk"), - Level::Pass - ); -} - -#[test] -fn memory_is_judged_by_the_profile_kar_source() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.memory = Memory { - total: 64 * GIB, - available: 40 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &server, &needs()); - assert_eq!(level_of(&report, "ram"), Level::Fail); - assert!( - report - .render() - .contains("sealed archive copy needs the whole archive in RAM") - ); - facts.memory = Memory { - total: 128 * GIB, - available: 100 * GIB, - swap_total: 0, - }; - facts.cgroup_memory_max = Some(32 * GIB); - assert_eq!( - level_of(&evaluate(&facts, &server, &needs()), "ram"), - Level::Fail - ); -} - -#[test] -fn an_inherited_sealed_archive_is_not_counted_twice() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memfd_extents = crate::profile::MemfdExtents::Full; // the full 55 GB copy; the shipped `ple_only` form needs about 39 GB less - let mut facts = server_facts(); - // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the - // parent already holds the sealed archive. - facts.memory = Memory { - total: 121 * GIB, - available: 70 * GIB, - swap_total: 0, - }; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ram"), - Level::Fail - ); - let mut n = needs(); - n.kar_fd_inherited = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Pass - ); - facts.memory.available = 20 * GIB; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Fail - ); -} - -#[test] -fn a_running_service_owns_its_ports_and_a_stranger_does_not() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.busy_ports = vec![8081]; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ports"), - Level::Fail - ); - let mut n = needs(); - n.service_running = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ports"), - Level::Pass - ); -} - -#[test] -fn other_platforms_stop_at_the_first_check() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let facts = Facts { - os: "macos".into(), - arch: "aarch64".into(), - ..Facts::default() - }; - let report = evaluate(&facts, &profile, &needs()); - assert!(report.failed()); - assert_eq!(report.checks.len(), 1); -} - -/// The RTX 3080 laptop as `facts::probe` sees it natively on Windows (nvidia-smi.exe, Win32 memory, DLL search). -fn windows_laptop() -> Facts { - let mut facts = Facts { - os: "windows".into(), - arch: "x86_64".into(), - gpus: vec![Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15234, - sm: Some(86), - }], - memory: crate::facts::Memory { - total: 48 << 30, - available: 30 << 30, - swap_total: 8 << 30, - }, - cpu_cores: 16, - nvidia_smi_found: true, - ..Facts::default() - }; - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - crate::facts::DirFact { - path: format!("C:/{key}").into(), - free_bytes: Some(1 << 40), - fs_type: None, - }, - ); - } - for name in crate::layout::BINARIES { - facts.binaries.insert(name.into(), true); - } - facts -} - -#[test] -fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = windows_laptop(); - let mut needs = needs(); - needs.binary_has_sm86 = Some(true); - needs.may_install_cublas = false; - ( - needs.wants_systemd, - needs.shard_bytes_missing, - needs.kar_bytes_missing, - ) = (false, 0, 0); - // cuBLAS DLLs missing: a failure that names the DLLs and the remedy, never a download of the Linux tarball. - let report = evaluate(&facts, &profile, &needs); - let cublas = report.checks.iter().find(|c| c.id == "cublas").unwrap(); - assert_eq!(cublas.level, Level::Fail); - assert!( - cublas.detail.contains("cublas64_12.dll") - && cublas.fix.as_deref().unwrap().contains("--cublas-dir"), - "{cublas:?}" - ); - assert_eq!(level_of(&report, "platform"), Level::Pass); - assert_eq!(level_of(&report, "gpu"), Level::Pass); - assert_eq!(level_of(&report, "memfd"), Level::Pass); - facts.libs.insert( - "libcublas.so.12".into(), - Some("C:/cuda/cublas64_12.dll".into()), - ); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("C:/cuda/cublasLt64_12.dll".into()), - ); - facts.libs.insert( - "libcuda.so.1".into(), - Some("C:/Windows/System32/nvcuda.dll".into()), - ); - let report = evaluate(&facts, &profile, &needs); - assert!(!report.failed(), "{}", report.render()); - // The server profile holds the archive in a sealed memfd: refused with the reason. - let server = Profile::builtin("rtx5090-32g").unwrap(); - let report = evaluate(&facts, &server, &needs); - assert_eq!(level_of(&report, "memfd"), Level::Fail); - assert!( - report - .checks - .iter() - .any(|c| c.id == "expert-source" && c.level == Level::Fail) - ); -} - -#[test] -fn no_systemd_points_at_foreground_mode() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.systemd_system = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "systemd"), Level::Fail); - assert!(report.render().contains("--foreground")); - let mut n = needs(); - n.wants_systemd = false; - assert!( - !evaluate(&facts, &profile, &n) - .checks - .iter() - .any(|c| c.id == "systemd") - ); -} +mod gpu_and_driver; +mod host_resources; +mod windows_host; +#[allow(unused_imports)] +use windows_host::windows_laptop; diff --git a/crates/deploy/src/preflight/tests/gpu_and_driver.rs b/crates/deploy/src/preflight/tests/gpu_and_driver.rs new file mode 100644 index 00000000..375f243a --- /dev/null +++ b/crates/deploy/src/preflight/tests/gpu_and_driver.rs @@ -0,0 +1,133 @@ +//! The GPU, driver, binaries and CUDA library checks of a healthy and an unhealthy server. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_expert_tier_is_always_reported_on_or_off() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report_for = |state: Option| { + let mut n = needs(); + n.expert_profile = state; + evaluate(&server_facts(), &profile, &n) + }; + let report = report_for(Some(ExpertProfileState::Valid)); + assert_eq!(level_of(&report, "expert-profile"), Level::Pass); + assert!(report.render().contains("ON:") && report.render().contains("8f59b4aa...388975baf")); + for (state, needle) in [ + (ExpertProfileState::Absent, "OFF until installed"), + ( + ExpertProfileState::WrongDigest, + "does not have the pinned sha256", + ), + (ExpertProfileState::OptedOut, "--no-expert-tier was given"), + ] { + let report = report_for(Some(state)); + assert_eq!(level_of(&report, "expert-profile"), Level::Warn); + let text = report.render(); + assert!(text.contains("OFF") && text.contains(needle), "{text}"); + } + // an absent table names the way out + assert!( + report_for(Some(ExpertProfileState::Absent)) + .render() + .contains("--expert-profile-file") + ); +} + +#[test] +fn healthy_server_passes_everything() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report = evaluate(&server_facts(), &profile, &needs()); + assert!(!report.failed(), "{}", report.render()); + assert_eq!(level_of(&report, "arch"), Level::Pass); + assert_eq!(level_of(&report, "memfd"), Level::Pass); +} + +#[test] +fn old_driver_and_busy_gpu_fail_with_actionable_text() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].driver = "580.65.06".into(); + facts.gpus[0].vram_free_mib = 9000; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "driver"), Level::Fail); + assert_eq!(level_of(&report, "vram"), Level::Fail); + let text = report.render(); + assert!(text.contains("580.65.06 is older than 595"), "{text}"); + assert!(text.contains("--gpu-budget-gib"), "{text}"); +} + +#[test] +fn a_running_lab_holder_is_named_as_the_reason_the_gpu_is_taken() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].vram_free_mib = 1200; + facts.lab_holder = true; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!( + text.contains("kar_holder") && text.contains("Lab mode"), + "{text}" + ); + facts.lab_holder = false; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!( + !text.contains("kar_holder") && text.contains("--gpu-budget-gib"), + "{text}" + ); +} + +#[test] +fn no_gpu_names_the_wsl_remedy_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus.clear(); + facts.nvidia_smi_found = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "gpu"), Level::Fail); + assert!(report.render().contains("Windows driver")); +} + +#[test] +fn sm86_card_needs_binaries_with_the_companion_feature() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].sm = Some(86); + facts.gpus[0].vram_total_mib = 16384; + facts.gpus[0].vram_free_mib = 15000; + let mut n = needs(); + n.binary_has_sm86 = Some(false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Fail + ); + n.binary_has_sm86 = None; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Warn + ); +} + +#[test] +fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.libs.insert("libcublas.so.12".into(), None); + facts.libs.insert("libcublasLt.so.12".into(), None); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Warn + ); + facts.tools.insert("xz".into(), false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Fail + ); + let mut n = needs(); + n.may_install_cublas = false; + facts.tools.insert("xz".into(), true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "cublas"), Level::Fail); + assert!(report.render().contains("--cublas-dir")); +} diff --git a/crates/deploy/src/preflight/tests/host_resources.rs b/crates/deploy/src/preflight/tests/host_resources.rs new file mode 100644 index 00000000..7865ad0b --- /dev/null +++ b/crates/deploy/src/preflight/tests/host_resources.rs @@ -0,0 +1,184 @@ +//! Memory, disk, ports, WSL and systemd checks. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.gpus[0] = Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15234, + sm: Some(86), + }; + facts.memory = Memory { + total: 12 * GIB, + available: 9 * GIB, + swap_total: 0, + }; + let mut n = needs(); + n.binary_has_sm86 = Some(true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "ram"), Level::Fail); + let text = report.render(); + assert!( + text.contains(".wslconfig") + && text.contains("memory=32GB") + && text.contains("wsl --shutdown"), + "{text}" + ); + assert_eq!(level_of(&report, "arch"), Level::Pass); + // 24 GB as WSL2 gives by default passes. + facts.memory = Memory { + total: 24_447_308 * 1024, + available: 22 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &profile, &n); + assert!(!report.failed(), "{}", report.render()); +} + +#[test] +fn model_volume_on_a_windows_mount_is_refused_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "wsl"), Level::Fail); + assert!(report.render().contains("/mnt/c")); +} + +#[test] +fn low_disk_reports_the_volume_before_anything_is_downloaded() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "disk"), Level::Fail); + let text = report.render(); + assert!( + text.contains("assets /data/assets: 53.0 GiB free"), + "{text}" + ); + assert!(text.contains("Nothing was downloaded yet"), "{text}"); + // With the model already present the same volume is fine. + let mut n = needs(); + n.shard_bytes_missing = 0; + n.kar_bytes_missing = 0; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "disk"), + Level::Pass + ); +} + +#[test] +fn memory_is_judged_by_the_profile_kar_source() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.memory = Memory { + total: 64 * GIB, + available: 40 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &server, &needs()); + assert_eq!(level_of(&report, "ram"), Level::Fail); + assert!( + report + .render() + .contains("sealed archive copy needs the whole archive in RAM") + ); + facts.memory = Memory { + total: 128 * GIB, + available: 100 * GIB, + swap_total: 0, + }; + facts.cgroup_memory_max = Some(32 * GIB); + assert_eq!( + level_of(&evaluate(&facts, &server, &needs()), "ram"), + Level::Fail + ); +} + +#[test] +fn an_inherited_sealed_archive_is_not_counted_twice() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; // the full 55 GB copy; the shipped `ple_only` form needs about 39 GB less + let mut facts = server_facts(); + // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the + // parent already holds the sealed archive. + facts.memory = Memory { + total: 121 * GIB, + available: 70 * GIB, + swap_total: 0, + }; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ram"), + Level::Fail + ); + let mut n = needs(); + n.kar_fd_inherited = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Pass + ); + facts.memory.available = 20 * GIB; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Fail + ); +} + +#[test] +fn a_running_service_owns_its_ports_and_a_stranger_does_not() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.busy_ports = vec![8081]; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ports"), + Level::Fail + ); + let mut n = needs(); + n.service_running = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ports"), + Level::Pass + ); +} + +#[test] +fn other_platforms_stop_at_the_first_check() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let facts = Facts { + os: "macos".into(), + arch: "aarch64".into(), + ..Facts::default() + }; + let report = evaluate(&facts, &profile, &needs()); + assert!(report.failed()); + assert_eq!(report.checks.len(), 1); +} + +#[test] +fn no_systemd_points_at_foreground_mode() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.systemd_system = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "systemd"), Level::Fail); + assert!(report.render().contains("--foreground")); + let mut n = needs(); + n.wants_systemd = false; + assert!( + !evaluate(&facts, &profile, &n) + .checks + .iter() + .any(|c| c.id == "systemd") + ); +} diff --git a/crates/deploy/src/preflight/tests/windows_host.rs b/crates/deploy/src/preflight/tests/windows_host.rs new file mode 100644 index 00000000..667d26a3 --- /dev/null +++ b/crates/deploy/src/preflight/tests/windows_host.rs @@ -0,0 +1,92 @@ +//! A native Windows laptop is judged with DLL names and without systemd or memfd. + +#[allow(unused_imports)] +use super::*; + +/// The RTX 3080 laptop as `facts::probe` sees it natively on Windows (nvidia-smi.exe, Win32 memory, DLL search). +pub(super) fn windows_laptop() -> Facts { + let mut facts = Facts { + os: "windows".into(), + arch: "x86_64".into(), + gpus: vec![Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15234, + sm: Some(86), + }], + memory: crate::facts::Memory { + total: 48 << 30, + available: 30 << 30, + swap_total: 8 << 30, + }, + cpu_cores: 16, + nvidia_smi_found: true, + ..Facts::default() + }; + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + crate::facts::DirFact { + path: format!("C:/{key}").into(), + free_bytes: Some(1 << 40), + fs_type: None, + }, + ); + } + for name in crate::layout::BINARIES { + facts.binaries.insert(name.into(), true); + } + facts +} + +#[test] +fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = windows_laptop(); + let mut needs = needs(); + needs.binary_has_sm86 = Some(true); + needs.may_install_cublas = false; + ( + needs.wants_systemd, + needs.shard_bytes_missing, + needs.kar_bytes_missing, + ) = (false, 0, 0); + // cuBLAS DLLs missing: a failure that names the DLLs and the remedy, never a download of the Linux tarball. + let report = evaluate(&facts, &profile, &needs); + let cublas = report.checks.iter().find(|c| c.id == "cublas").unwrap(); + assert_eq!(cublas.level, Level::Fail); + assert!( + cublas.detail.contains("cublas64_12.dll") + && cublas.fix.as_deref().unwrap().contains("--cublas-dir"), + "{cublas:?}" + ); + assert_eq!(level_of(&report, "platform"), Level::Pass); + assert_eq!(level_of(&report, "gpu"), Level::Pass); + assert_eq!(level_of(&report, "memfd"), Level::Pass); + facts.libs.insert( + "libcublas.so.12".into(), + Some("C:/cuda/cublas64_12.dll".into()), + ); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("C:/cuda/cublasLt64_12.dll".into()), + ); + facts.libs.insert( + "libcuda.so.1".into(), + Some("C:/Windows/System32/nvcuda.dll".into()), + ); + let report = evaluate(&facts, &profile, &needs); + assert!(!report.failed(), "{}", report.render()); + // The server profile holds the archive in a sealed memfd: refused with the reason. + let server = Profile::builtin("rtx5090-32g").unwrap(); + let report = evaluate(&facts, &server, &needs); + assert_eq!(level_of(&report, "memfd"), Level::Fail); + assert!( + report + .checks + .iter() + .any(|c| c.id == "expert-source" && c.level == Level::Fail) + ); +} diff --git a/crates/deploy/src/preflight/wsl_filesystem.rs b/crates/deploy/src/preflight/wsl_filesystem.rs new file mode 100644 index 00000000..630de733 --- /dev/null +++ b/crates/deploy/src/preflight/wsl_filesystem.rs @@ -0,0 +1,44 @@ +//! The WSL2 file system check: the model volume must not sit on a Windows or network mount. + +use super::*; + +pub(super) fn check_wsl_filesystem(facts: &Facts, checks: &mut Vec) { + if !facts.wsl { + return; + } + let slow = slow_mounts(facts); + if slow.is_empty() { + checks.push(pass( + "wsl", + "WSL2", + "model volume is on the Linux file system".into(), + )); + return; + } + checks.push(check( + "wsl", + Level::Fail, + "WSL2 file system", + format!( + "{} is on a Windows/network mount; mapped and direct reads are far too slow there", + slow.join(", ") + ), + Some("put --assets (and --state-dir) on the WSL ext4 disk, e.g. under ~/leleka, not under /mnt/c".into()), + )); +} + +/// The model directories that sit on a Windows or network mount, as `path (fs type)`. +fn slow_mounts(facts: &Facts) -> Vec { + ["assets", "state", "prefix"] + .iter() + .filter_map(|key| facts.dirs.get(*key)) + .filter(|dir| dir.fs_type.as_deref().is_some_and(is_slow_foreign_fs)) + .map(|dir| { + format!( + "{} ({})", + dir.path.display(), + dir.fs_type.as_deref().unwrap_or("?") + ) + }) + .collect() +} diff --git a/crates/deploy/src/profile.rs b/crates/deploy/src/profile.rs index 3b334df0..8b22a959 100644 --- a/crates/deploy/src/profile.rs +++ b/crates/deploy/src/profile.rs @@ -196,121 +196,6 @@ pub struct MemoryBudget { pub resident_budget_gib: Option, } -impl MemoryBudget { - pub fn validate(&self) -> Result<(), String> { - if let Some(value) = &self.prefix_cache_mib - && value != "auto" - && value.parse::().ok().is_none_or(|mib| mib > (1 << 30)) - { - return Err("memory.prefix_cache_mib must be \"auto\", \"0\" or a size in MiB".into()); - } - if let Some(tail) = &self.prefix_cache_tail - && !matches!(tail.as_str(), "off" | "prompt" | "reply") - { - return Err("memory.prefix_cache_tail must be off, prompt or reply".into()); - } - if let Some(block) = self.prefix_cache_block - && (block % 256 != 0 || block > 8192) - { - return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); - } - if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib) - && hard >= soft - { - return Err("memory.hard_floor_mib must be below memory.soft_floor_mib".into()); - } - if let Some(percent) = self.cache_share_percent - && !(1..=100).contains(&percent) - { - return Err("memory.cache_share_percent must be 1..=100".into()); - } - if let Some(lock) = &self.lock - && !matches!(lock.as_str(), "off" | "try" | "require") - { - return Err("memory.lock must be off, try or require".into()); - } - Ok(()) - } - - /// The engine arguments this section adds. - pub fn args(&self) -> Vec { - let mut args = Vec::new(); - if let Some(value) = &self.prefix_cache_mib { - args.extend(["--prefix-cache-mib".to_owned(), value.clone()]); - } - if let Some(tail) = &self.prefix_cache_tail { - args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]); - } - if let Some(block) = self.prefix_cache_block - && self.prefix_cache_on() - { - args.extend(["--prefix-cache-block".to_owned(), block.to_string()]); - } - args - } - - /// The explicit MiB cap of the prefix cache: `Some(n)` for a number above zero, `None` for `auto`, off or unset. An `auto` cache - /// is sized from the memory that is free when the stack opens (75 % of it, ceiling 96 GiB), so it grows whenever RAM is freed - /// elsewhere; a number never does (`leleka_memory::plan::explicit_prefix_budget`). - pub fn prefix_cache_cap_mib(&self) -> Option { - self.prefix_cache_mib - .as_deref()? - .parse::() - .ok() - .filter(|mib| *mib > 0) - } - - /// The prefix cache is configured and not switched off (`0`). - pub fn prefix_cache_on(&self) -> bool { - self.prefix_cache_mib - .as_deref() - .is_some_and(|mib| mib != "0") - } - - /// The engine environment this section adds. - pub fn env(&self) -> BTreeMap { - let mut env = BTreeMap::new(); - let mut put = |key: &str, value: Option| { - if let Some(value) = value { - env.insert(key.to_owned(), value); - } - }; - put( - "LELEKA_MEMORY_SOFT_FLOOR_MIB", - self.soft_floor_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_HARD_FLOOR_MIB", - self.hard_floor_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_RESERVE_MIB", - self.reserve_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_CACHE_SHARE_PERCENT", - self.cache_share_percent.map(|v| v.to_string()), - ); - put("LELEKA_MEMORY_LOCK", self.lock.clone()); - if self.prefix_cache_on() { - put( - "LELEKA_PREFIX_RETENTION_S", - self.prefix_retention_min - .map(|minutes| minutes.saturating_mul(60).to_string()), - ); - } - put( - "LELEKA_MEMORY_HEAL", - self.heal.map(|v| if v { "1" } else { "0" }.to_owned()), - ); - put( - "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB", - self.resident_budget_gib.map(|v| v.to_string()), - ); - env - } -} - /// Automatic selection window (`sm` is compute capability times ten; `sm_max` and `vram_mib_max` are exclusive). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -370,666 +255,11 @@ pub struct Profile { pub memory: MemoryBudget, } -impl Profile { - /// Host RAM the sealed memfd holds for the life of the service (0 for a file-backed archive). - pub fn memfd_bytes(&self) -> u64 { - match (self.kar_source, self.memfd_extents) { - (KarSource::File | KarSource::None, _) => 0, - (KarSource::Memfd, MemfdExtents::Full) => ARCHIVE_BYTES, - (KarSource::Memfd, MemfdExtents::PleOnly) => SPARSE_MEMFD_BYTES_ESTIMATE, - } - } - - /// `min_ram_available_bytes` for this profile. The profile figure is written for the full archive copy; a `ple_only` memfd - /// needs that much less. - pub fn min_ram_available(&self) -> u64 { - let saved = match (self.kar_source, self.memfd_extents) { - (KarSource::Memfd, MemfdExtents::PleOnly) => { - ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE - } - _ => 0, - }; - self.min_ram_available_bytes.saturating_sub(saved) - } - - pub fn builtin(name: &str) -> Option { - BUILTIN - .iter() - .find(|(candidate, _)| *candidate == name) - .map(|(_, text)| { - let profile: Profile = - serde_json::from_str(text).expect("built-in profile JSON is valid"); - profile - }) - } - - pub fn builtins() -> Vec { - BUILTIN - .iter() - .map(|(name, _)| Profile::builtin(name).expect("built-in")) - .collect() - } - - pub fn from_file(path: &Path) -> Result { - let bytes = std::fs::read(path) - .map_err(|error| format!("cannot read profile {}: {error}", path.display()))?; - if bytes.len() > 64 * 1024 { - return Err("profile file exceeds 64 KiB".into()); - } - let profile: Profile = serde_json::from_slice(&bytes) - .map_err(|error| format!("invalid profile {}: {error}", path.display()))?; - profile.validate()?; - Ok(profile) - } - - pub fn validate(&self) -> Result<(), String> { - if self.memfd_extents == MemfdExtents::PleOnly { - if self.kar_source != KarSource::Memfd { - return Err("memfd_extents=ple_only needs kar_source=memfd (a file-backed archive has no memfd to make sparse)".into()); - } - // Freed RAM must not be refilled "on purpose" by an `auto` cache (docs/design/memory-single-copy-and-elastic-state.md section B). - if self.memory.prefix_cache_cap_mib().is_none() && self.memory.prefix_cache_on() { - return Err("memfd_extents=ple_only needs an explicit memory.prefix_cache_mib (or 0): `auto` would size the cache from the RAM the sparse memfd frees".into()); - } - } - if self.name.is_empty() - || self.name.len() > 64 - || !self - .name - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) - { - return Err("profile name must be 1..64 characters of [A-Za-z0-9._-]".into()); - } - if self.gpu_budget_bytes < (1 << 30) || self.gpu_budget_bytes > (1 << 40) { - return Err("gpu_budget_bytes must be between 1 GiB and 1 TiB".into()); - } - if !(1..=262_144).contains(&self.context_tokens) { - return Err("context_tokens must be 1..=262144 for the Original serve path".into()); - } - if let Some(capacity) = self.prefill_capacity - && !PREFILL_CAPACITIES.contains(&capacity) - { - return Err(format!( - "prefill_capacity must be one of {PREFILL_CAPACITIES:?}" - )); - } - if let Some(p) = self.spec_min_p - && !(0.0..=1.0).contains(&p) - { - return Err("spec_min_p must be within 0..=1".into()); - } - if let Some(kv) = &self.kv - && kv != "int8" - { - return Err("kv must be int8 (the engine refuses other formats)".into()); - } - if let Some(digest) = &self.expert_profile_sha256 - && (digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit())) - { - return Err("expert_profile_sha256 must be 64 hex digits".into()); - } - if let Some(path) = &self.expert_profile - && (path.is_empty() - || path.starts_with('/') - || path.split('/').any(|part| part == ".." || part.is_empty())) - { - return Err( - "expert_profile must be a relative path inside the assets directory".into(), - ); - } - self.memory.validate()?; - for (key, value) in &self.engine_env { - // LELEKA_CHAIN selects the chain-kernel group (docs/chain-kernels.md), LELEKA_SM120_* the compute-capability-12 kernel switches - // (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the GGUF PLE row reader (`kar_source: none`); every other switch is a serve-stack one - if !(key.starts_with("LELEKA_ORIGINAL_SERVE_") - || key.starts_with("LELEKA_SM120_") - || key.starts_with("LELEKA_PLE_") - || key == "LELEKA_CHAIN") - || !key - .bytes() - .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') - { - return Err(format!( - "engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_* or LELEKA_PLE_* name (or LELEKA_CHAIN)" - )); - } - if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) { - return Err(format!( - "engine_env value of {key} is empty or not printable" - )); - } - } - Ok(()) - } - - /// True when the compute capability and VRAM of `gpu` fall inside the selection window. - pub fn matches(&self, gpu: &Gpu) -> bool { - let Some(sm) = gpu.sm else { return false }; - (self.select.sm_min..self.select.sm_max).contains(&sm) - && (self.select.vram_mib_min..self.select.vram_mib_max).contains(&gpu.vram_total_mib) - } -} - -/// Resolve `--profile`: `auto` (or nothing), a built-in name, or a path to a JSON file. -pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result { - let spec = spec.unwrap_or("auto"); - if spec != "auto" { - if let Some(profile) = Profile::builtin(spec) { - return Ok(profile); - } - if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") { - return Profile::from_file(Path::new(spec)); - } - let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect(); - return Err(format!( - "unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)", - names.join(", ") - )); - } - let gpu = gpu.ok_or( - "no NVIDIA GPU was detected, so no profile can be selected automatically; pass --profile NAME|FILE", - )?; - let matches: Vec = Profile::builtins() - .into_iter() - .filter(|profile| profile.matches(gpu)) - .collect(); - match matches.len() { - 1 => Ok(matches.into_iter().next().expect("one")), - 0 => Err(format!( - "no built-in profile fits {} (sm_{}, {} MiB); built-in: {}; write a profile file from `leleka profiles show NAME` and pass --profile FILE", - gpu.name, - gpu.sm.map_or("?".into(), |sm| sm.to_string()), - gpu.vram_total_mib, - BUILTIN - .iter() - .map(|(name, _)| *name) - .collect::>() - .join(", ") - )), - _ => Err("more than one built-in profile matches; pass --profile NAME".into()), - } -} - #[cfg(test)] -mod tests { - use super::*; +mod tests; - fn gpu(name: &str, sm: u32, mib: u64) -> Gpu { - Gpu { - index: 0, - name: name.into(), - driver: "595.99.02".into(), - vram_total_mib: mib, - vram_free_mib: mib, - sm: Some(sm), - } - } - - #[test] - fn built_in_profiles_parse_and_validate() { - for profile in Profile::builtins() { - profile.validate().unwrap(); - } - assert_eq!(Profile::builtins().len(), 4); - } - - #[test] - fn the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_matters() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - let file = Profile::builtin("rtx5090-32g-file").unwrap(); - file.validate().unwrap(); - assert_eq!( - (file.kar_source, file.expert_source), - (KarSource::File, ExpertSource::Resident) - ); - // same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM the memfd no longer - // holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ - for (name, same) in [ - ( - "gpu_budget_bytes", - server.gpu_budget_bytes == file.gpu_budget_bytes, - ), - ( - "context_tokens", - server.context_tokens == file.context_tokens, - ), - ( - "prefill_capacity", - server.prefill_capacity == file.prefill_capacity, - ), - ("spec_min_p", server.spec_min_p == file.spec_min_p), - ( - "expert_profile", - server.expert_profile == file.expert_profile, - ), - ("engine_env", server.engine_env == file.engine_env), - ( - "prefix_cache_tail", - server.memory.prefix_cache_tail == file.memory.prefix_cache_tail, - ), - ( - "prefix_cache_block", - server.memory.prefix_cache_block == file.memory.prefix_cache_block, - ), - ( - "floors", - ( - server.memory.soft_floor_mib, - server.memory.hard_floor_mib, - server.memory.reserve_mib, - ) == ( - file.memory.soft_floor_mib, - file.memory.hard_floor_mib, - file.memory.reserve_mib, - ), - ), - ] { - assert!(same, "{name} must match rtx5090-32g"); - } - assert_eq!(file.memory.prefix_cache_mib.as_deref(), Some("6144")); - assert!( - file.min_ram_available_bytes + ARCHIVE_BYTES - 5_000_000_000 - <= server.min_ram_available_bytes, - "the file form does not need the archive's RAM" - ); - // an experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile - assert!(!file.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); - assert_eq!( - resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))) - .unwrap() - .name, - "rtx5090-32g" - ); - assert_eq!( - resolve(Some("rtx5090-32g-file"), None).unwrap().kar_source, - KarSource::File - ); - } - - #[test] - fn the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - let ggufp = Profile::builtin("rtx5090-32g-gguf-ple").unwrap(); - ggufp.validate().unwrap(); - assert_eq!(ggufp.kar_source, KarSource::None); - assert_eq!(ggufp.memfd_bytes(), 0); - assert_eq!(KarSource::None.as_str(), "none"); - for (name, same) in [ - ("gpu_budget_bytes", server.gpu_budget_bytes == ggufp.gpu_budget_bytes), - ("context_tokens", server.context_tokens == ggufp.context_tokens), - ("prefill_capacity", server.prefill_capacity == ggufp.prefill_capacity), - ("spec_min_p", server.spec_min_p == ggufp.spec_min_p), - ("expert_profile", server.expert_profile == ggufp.expert_profile), - ("expert_source", server.expert_source == ggufp.expert_source), - ("prefix_cache_mib", server.memory.prefix_cache_mib == ggufp.memory.prefix_cache_mib), - ("prefix_cache_tail", server.memory.prefix_cache_tail == ggufp.memory.prefix_cache_tail), - ("prefix_cache_block", server.memory.prefix_cache_block == ggufp.memory.prefix_cache_block), - ] { - assert!(same, "{name} must match rtx5090-32g"); - } - // the engine switches are the server's plus the page-cache form of the PLE reader - let mut expected = server.engine_env.clone(); - expected.insert("LELEKA_PLE_DIRECT".into(), "0".into()); - expected.insert("LELEKA_ORIGINAL_SERVE_GGUF_PLE".into(), "1".into()); - assert_eq!(ggufp.engine_env, expected); - // experimental: never auto-selected - assert!(!ggufp.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); - assert_eq!( - resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap().name, - "rtx5090-32g" - ); - // only the PLE reader family is let through next to the serve-stack switches - let mut bad = ggufp.clone(); - bad.engine_env.insert("LELEKA_PLEX".into(), "1".into()); - assert!(bad.validate().is_err()); - let mut json: serde_json::Value = serde_json::to_value(&ggufp).unwrap(); - assert_eq!(json["kar_source"], "none"); - json["kar_source"] = "memfd".into(); - let back: Profile = serde_json::from_value(json).unwrap(); - assert_eq!(back.kar_source, KarSource::Memfd); - } - - #[test] - fn only_the_server_profile_turns_the_prompt_routing_seed_off() { - // placement-class setting (docs/experiments/decode-tail-5090.md): off for the 5090 profile, the engine default and the laptop profile are unchanged - let server = Profile::builtin("rtx5090-32g").unwrap(); - assert_eq!( - server - .engine_env - .get("LELEKA_ORIGINAL_SERVE_SEED") - .map(String::as_str), - Some("off") - ); - let laptop = Profile::builtin("rtx3080-16g").unwrap(); - assert!(!laptop.engine_env.contains_key("LELEKA_ORIGINAL_SERVE_SEED")); - } - - #[test] - fn only_the_server_profile_enables_the_mtp_draft_attention_switch() { - // bitwise draft-attention kernels of the compute capability 12 card (docs/experiments/draft-round-5090.md); the laptop (sm_86) has no companion for them - let server = Profile::builtin("rtx5090-32g").unwrap(); - assert_eq!( - server - .engine_env - .get("LELEKA_SM120_ATTN_DAILY_MTP") - .map(String::as_str), - Some("1") - ); - let laptop = Profile::builtin("rtx3080-16g").unwrap(); - assert!( - !laptop - .engine_env - .contains_key("LELEKA_SM120_ATTN_DAILY_MTP") - ); - // the key space of engine_env still refuses everything else - let mut bad = server.clone(); - bad.engine_env.insert("LELEKA_SM86_X".into(), "1".into()); - assert!(bad.validate().is_err()); - let mut ok = server; - ok.engine_env - .insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "1".into()); - ok.validate().unwrap(); - } - - #[test] - fn auto_selection_picks_the_server_and_the_laptop_profile() { - let server = resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap(); - assert_eq!(server.name, "rtx5090-32g"); - assert_eq!(server.kar_source, KarSource::Memfd); - let laptop = resolve( - Some("auto"), - Some(&gpu("NVIDIA GeForce RTX 3080 Laptop GPU", 86, 16384)), - ) - .unwrap(); - assert_eq!(laptop.name, "rtx3080-16g"); - assert_eq!(laptop.kar_source, KarSource::File); - assert_eq!( - laptop.context_tokens, 262144, - "the owner's real work is 256k" - ); - assert_eq!( - (laptop.prefill_capacity, laptop.memory.prefix_cache_block), - (Some(6144), Some(6144)) - ); - assert_eq!(laptop.memory.prefix_cache_tail.as_deref(), Some("prompt")); - } - - #[test] - fn unmatched_gpu_and_missing_gpu_give_actionable_errors() { - let error = resolve(None, Some(&gpu("NVIDIA GeForce RTX 4090", 89, 24564))).unwrap_err(); - assert!(error.contains("--profile FILE"), "{error}"); - assert!(resolve(None, None).unwrap_err().contains("--profile")); - assert!( - resolve(Some("nope"), None) - .unwrap_err() - .contains("rtx5090-32g") - ); - } - - #[test] - fn explicit_name_overrides_the_detected_gpu() { - let forced = resolve( - Some("rtx3080-16g"), - Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)), - ) - .unwrap(); - assert_eq!(forced.name, "rtx3080-16g"); - } - - #[test] - fn validation_rejects_unsafe_values() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile - .engine_env - .insert("LD_PRELOAD".into(), "/tmp/x.so".into()); - assert!(profile.validate().unwrap_err().contains("LD_PRELOAD")); - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.context_tokens = 524_288; - assert!(profile.validate().is_err()); - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.prefill_capacity = Some(1000); - assert!(profile.validate().is_err()); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.expert_profile = Some("../x".into()); - assert!(profile.validate().is_err()); - profile.expert_profile = Some("/etc/passwd".into()); - assert!(profile.validate().is_err()); - } - - #[test] - fn the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_environment() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - assert_eq!( - server.memory.args(), - [ - "--prefix-cache-mib", - "6144", - "--prefix-cache-tail", - "reply", - "--prefix-cache-block", - "8192" - ] - .map(str::to_owned) - .to_vec() - ); - let mut bad = server.memory.clone(); - bad.prefix_cache_tail = Some("always".into()); - assert!(bad.validate().is_err()); - let env = server.memory.env(); - assert_eq!(env["LELEKA_MEMORY_SOFT_FLOOR_MIB"], "4096"); - assert_eq!(env["LELEKA_MEMORY_HARD_FLOOR_MIB"], "2048"); - assert_eq!(env["LELEKA_MEMORY_LOCK"], "try"); - let laptop = Profile::builtin("rtx3080-16g").unwrap(); - assert_eq!( - laptop.memory.env()["LELEKA_MEMORY_LOCK"], - "off", - "the laptop archive is a file, not a memfd" - ); - for profile in Profile::builtins() { - profile.validate().unwrap(); - } - } - - #[test] - fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_store() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - // 6144 MiB = what `auto` resolves to on this host today (5.7-6.1 GiB, docs/memory-safety.md section 8): behaviour at 245k is unchanged - assert_eq!(server.memory.prefix_cache_cap_mib(), Some(6144)); - assert!(server.memory.prefix_cache_on()); - assert!( - server - .memory - .args() - .windows(2) - .any(|w| w == ["--prefix-cache-mib", "6144"]) - ); - // a cache that fits the cap with room to spare: 245k tokens x 14,208 B + ~4 nodes of ~127 MiB is about 4 GiB - let session_245k = 245_000u64 * 14_208 + 4 * (127 << 20); - assert!(session_245k < 6144 << 20, "{session_245k}"); - // `auto`, `0`, off and unset are not caps - for (value, cap) in [ - (Some("auto"), None), - (Some("0"), None), - (None, None), - (Some("8192"), Some(8192)), - ] { - let mut memory = server.memory.clone(); - memory.prefix_cache_mib = value.map(str::to_owned); - assert_eq!(memory.prefix_cache_cap_mib(), cap, "{value:?}"); - } - // the dedicated memfd profile must keep an explicit cap; the laptop (file archive, mapped experts) is a different machine - for profile in Profile::builtins() - .iter() - .filter(|p| p.kar_source == KarSource::Memfd) - { - assert!( - profile.memory.prefix_cache_cap_mib().is_some(), - "{} uses `auto`", - profile.name - ); - } - } - - fn sparse_server() -> Profile { - Profile::builtin("rtx5090-32g").unwrap() - } - - #[test] - fn only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized() { - for profile in Profile::builtins() { - let want = if profile.name == "rtx5090-32g" { - MemfdExtents::PleOnly - } else { - MemfdExtents::Full - }; - assert_eq!(profile.memfd_extents, want, "{}", profile.name); - assert_eq!( - serde_json::to_string(&profile) - .unwrap() - .contains("\"memfd_extents\":"), - want == MemfdExtents::PleOnly, - "{}", - profile.name - ); - } - let mut full = sparse_server(); - full.memfd_extents = MemfdExtents::Full; - assert!( - !serde_json::to_string(&full) - .unwrap() - .contains("\"memfd_extents\":") - ); - let text = serde_json::to_string(&sparse_server()).unwrap(); - assert!(text.contains("\"memfd_extents\":\"ple_only\""), "{text}"); - let back: Profile = serde_json::from_str(&text).unwrap(); - assert_eq!(back, sparse_server()); - let mut value: serde_json::Value = serde_json::from_str( - &serde_json::to_string(&Profile::builtin("rtx5090-32g").unwrap()).unwrap(), - ) - .unwrap(); - value["memfd_extents"] = "everything".into(); - assert!(serde_json::from_value::(value).is_err()); - } - - #[test] - fn a_sparse_memfd_profile_needs_a_memfd_and_an_explicit_prefix_cap() { - sparse_server().validate().unwrap(); - // 0 (cache off) and any number are fine; `auto` would refill the freed RAM - for (value, ok) in [("6144", true), ("0", true), ("auto", false)] { - let mut profile = sparse_server(); - profile.memory.prefix_cache_mib = Some(value.into()); - assert_eq!(profile.validate().is_ok(), ok, "{value}"); - } - let mut profile = sparse_server(); - profile.memory.prefix_cache_mib = None; - assert!( - profile.validate().is_ok(), - "no cache at all cannot refill anything" - ); - let mut file_backed = sparse_server(); - file_backed.kar_source = KarSource::File; - let error = file_backed.validate().unwrap_err(); - assert!( - error.contains("ple_only") && error.contains("memfd"), - "{error}" - ); - // the same profile in the full form validates with `auto` - let mut full = Profile::builtin("rtx5090-32g").unwrap(); - full.memfd_extents = MemfdExtents::Full; - full.memory.prefix_cache_mib = Some("auto".into()); - full.validate().unwrap(); - } - - #[test] - fn a_sparse_memfd_holds_a_third_of_the_archive_and_lowers_the_ram_the_profile_asks_for() { - let mut full = Profile::builtin("rtx5090-32g").unwrap(); - full.memfd_extents = MemfdExtents::Full; - let sparse = sparse_server(); - assert_eq!(full.memfd_bytes(), ARCHIVE_BYTES); - assert_eq!(sparse.memfd_bytes(), SPARSE_MEMFD_BYTES_ESTIMATE); - // 320,001,536 rows x 50 B = 16,000,076,800 B are the floor of what the serve path reads - const { - assert!( - SPARSE_MEMFD_BYTES_ESTIMATE > 16_000_076_800 - && SPARSE_MEMFD_BYTES_ESTIMATE < ARCHIVE_BYTES / 3 - ) - }; - assert_eq!(full.min_ram_available(), full.min_ram_available_bytes); - assert_eq!( - sparse.min_ram_available(), - full.min_ram_available_bytes - (ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE) - ); - assert!( - sparse.min_ram_available() > 70_000_000_000 - && sparse.min_ram_available() < 80_000_000_000 - ); - let laptop = Profile::builtin("rtx3080-16g").unwrap(); - assert_eq!( - (laptop.memfd_bytes(), laptop.min_ram_available()), - (0, laptop.min_ram_available_bytes) - ); - } - - #[test] - fn the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent() { - let none = |_: &str| None; - let with = |value: &str| { - let value = value.to_owned(); - move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone()) - }; - let hex64 = "ab".repeat(32); - let zeros = "00".repeat(32); - let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; - if compiled == [0u8; 32] { - // not measured yet: the sparse form refuses to start without an explicit value, and says how to get one - let error = extents_sha256(&none).unwrap_err(); - assert!( - error.contains("kar_census") && error.contains("--hash-extents"), - "{error}" - ); - assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex")); - assert!( - extents_sha256(&with("abcd")) - .unwrap_err() - .contains("64 hex") - ); - assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero")); - let (pin, source) = extents_sha256(&with(&hex64)).unwrap(); - assert_eq!((pin, source), ([0xab; 32], PinSource::Operator)); - } else { - // measured: the binary's value wins and an environment value cannot override it - assert_eq!( - extents_sha256(&none).unwrap(), - (compiled, PinSource::Compiled) - ); - assert_eq!( - extents_sha256(&with(&hex64)).unwrap(), - (compiled, PinSource::Compiled) - ); - } - } - - #[test] - fn memory_budget_validation_rejects_nonsense() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memory.hard_floor_mib = Some(8192); - assert!(profile.validate().unwrap_err().contains("hard_floor")); - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memory.lock = Some("maybe".into()); - assert!(profile.validate().is_err()); - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memory.prefix_cache_mib = Some("lots".into()); - assert!(profile.validate().is_err()); - profile.memory.prefix_cache_mib = Some("0".into()); - assert!(profile.validate().is_ok()); - profile.memory.cache_share_percent = Some(0); - assert!(profile.validate().is_err()); - } - - #[test] - fn unknown_fields_in_a_profile_file_are_refused() { - let text = BUILTIN[0].1.replacen('{', "{\"typo\": 1,", 1); - assert!(serde_json::from_str::(&text).is_err()); - } -} +mod catalog; +mod memory_budget; +#[allow(unused_imports)] +pub use catalog::resolve; +mod profile_limits; diff --git a/crates/deploy/src/profile/catalog.rs b/crates/deploy/src/profile/catalog.rs new file mode 100644 index 00000000..2a9252e7 --- /dev/null +++ b/crates/deploy/src/profile/catalog.rs @@ -0,0 +1,83 @@ +//! The built-in profiles, loading a profile file and picking the profile that fits a GPU. + +#[allow(unused_imports)] +use super::*; + +impl Profile { + pub fn builtin(name: &str) -> Option { + BUILTIN + .iter() + .find(|(candidate, _)| *candidate == name) + .map(|(_, text)| { + let profile: Profile = + serde_json::from_str(text).expect("built-in profile JSON is valid"); + profile + }) + } + + pub fn builtins() -> Vec { + BUILTIN + .iter() + .map(|(name, _)| Profile::builtin(name).expect("built-in")) + .collect() + } + + pub fn from_file(path: &Path) -> Result { + let bytes = std::fs::read(path) + .map_err(|error| format!("cannot read profile {}: {error}", path.display()))?; + if bytes.len() > 64 * 1024 { + return Err("profile file exceeds 64 KiB".into()); + } + let profile: Profile = serde_json::from_slice(&bytes) + .map_err(|error| format!("invalid profile {}: {error}", path.display()))?; + profile.validate()?; + Ok(profile) + } + + /// True when the compute capability and VRAM of `gpu` fall inside the selection window. + pub fn matches(&self, gpu: &Gpu) -> bool { + let Some(sm) = gpu.sm else { return false }; + (self.select.sm_min..self.select.sm_max).contains(&sm) + && (self.select.vram_mib_min..self.select.vram_mib_max).contains(&gpu.vram_total_mib) + } +} + +/// Resolve `--profile`: `auto` (or nothing), a built-in name, or a path to a JSON file. +pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result { + let spec = spec.unwrap_or("auto"); + if spec != "auto" { + if let Some(profile) = Profile::builtin(spec) { + return Ok(profile); + } + if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") { + return Profile::from_file(Path::new(spec)); + } + let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect(); + return Err(format!( + "unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)", + names.join(", ") + )); + } + let gpu = gpu.ok_or( + "no NVIDIA GPU was detected, so no profile can be selected automatically; pass --profile NAME|FILE", + )?; + let matches: Vec = Profile::builtins() + .into_iter() + .filter(|profile| profile.matches(gpu)) + .collect(); + match matches.len() { + 1 => Ok(matches.into_iter().next().expect("one")), + 0 => Err(format!( + "no built-in profile fits {} (sm_{}, {} MiB); built-in: {}; write a profile file from `leleka profiles show NAME` and pass --profile FILE", + gpu.name, + gpu.sm.map_or("?".into(), |sm| sm.to_string()), + gpu.vram_total_mib, + BUILTIN + .iter() + .map(|(name, _)| *name) + .collect::>() + .join(", ") + )), + _ => Err("more than one built-in profile matches; pass --profile NAME".into()), + } +} diff --git a/crates/deploy/src/profile/memory_budget.rs b/crates/deploy/src/profile/memory_budget.rs new file mode 100644 index 00000000..1eb4ca5c --- /dev/null +++ b/crates/deploy/src/profile/memory_budget.rs @@ -0,0 +1,119 @@ +//! The memory budget of a profile: validation, engine arguments, environment and the prefix-cache cap. + +#[allow(unused_imports)] +use super::*; + +impl MemoryBudget { + pub fn validate(&self) -> Result<(), String> { + if let Some(value) = &self.prefix_cache_mib + && value != "auto" + && value.parse::().ok().is_none_or(|mib| mib > (1 << 30)) + { + return Err("memory.prefix_cache_mib must be \"auto\", \"0\" or a size in MiB".into()); + } + if let Some(tail) = &self.prefix_cache_tail + && !matches!(tail.as_str(), "off" | "prompt" | "reply") + { + return Err("memory.prefix_cache_tail must be off, prompt or reply".into()); + } + if let Some(block) = self.prefix_cache_block + && (block % 256 != 0 || block > 8192) + { + return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); + } + if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib) + && hard >= soft + { + return Err("memory.hard_floor_mib must be below memory.soft_floor_mib".into()); + } + if let Some(percent) = self.cache_share_percent + && !(1..=100).contains(&percent) + { + return Err("memory.cache_share_percent must be 1..=100".into()); + } + if let Some(lock) = &self.lock + && !matches!(lock.as_str(), "off" | "try" | "require") + { + return Err("memory.lock must be off, try or require".into()); + } + Ok(()) + } + + /// The engine arguments this section adds. + pub fn args(&self) -> Vec { + let mut args = Vec::new(); + if let Some(value) = &self.prefix_cache_mib { + args.extend(["--prefix-cache-mib".to_owned(), value.clone()]); + } + if let Some(tail) = &self.prefix_cache_tail { + args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]); + } + if let Some(block) = self.prefix_cache_block + && self.prefix_cache_on() + { + args.extend(["--prefix-cache-block".to_owned(), block.to_string()]); + } + args + } + + /// The explicit MiB cap of the prefix cache: `Some(n)` for a number above zero, `None` for `auto`, off or unset. An `auto` cache + /// is sized from the memory that is free when the stack opens (75 % of it, ceiling 96 GiB), so it grows whenever RAM is freed + /// elsewhere; a number never does (`leleka_memory::plan::explicit_prefix_budget`). + pub fn prefix_cache_cap_mib(&self) -> Option { + self.prefix_cache_mib + .as_deref()? + .parse::() + .ok() + .filter(|mib| *mib > 0) + } + + /// The prefix cache is configured and not switched off (`0`). + pub fn prefix_cache_on(&self) -> bool { + self.prefix_cache_mib + .as_deref() + .is_some_and(|mib| mib != "0") + } + + /// The engine environment this section adds. + pub fn env(&self) -> BTreeMap { + let mut env = BTreeMap::new(); + let mut put = |key: &str, value: Option| { + if let Some(value) = value { + env.insert(key.to_owned(), value); + } + }; + put( + "LELEKA_MEMORY_SOFT_FLOOR_MIB", + self.soft_floor_mib.map(|v| v.to_string()), + ); + put( + "LELEKA_MEMORY_HARD_FLOOR_MIB", + self.hard_floor_mib.map(|v| v.to_string()), + ); + put( + "LELEKA_MEMORY_RESERVE_MIB", + self.reserve_mib.map(|v| v.to_string()), + ); + put( + "LELEKA_MEMORY_CACHE_SHARE_PERCENT", + self.cache_share_percent.map(|v| v.to_string()), + ); + put("LELEKA_MEMORY_LOCK", self.lock.clone()); + if self.prefix_cache_on() { + put( + "LELEKA_PREFIX_RETENTION_S", + self.prefix_retention_min + .map(|minutes| minutes.saturating_mul(60).to_string()), + ); + } + put( + "LELEKA_MEMORY_HEAL", + self.heal.map(|v| if v { "1" } else { "0" }.to_owned()), + ); + put( + "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB", + self.resident_budget_gib.map(|v| v.to_string()), + ); + env + } +} diff --git a/crates/deploy/src/profile/profile_limits.rs b/crates/deploy/src/profile/profile_limits.rs new file mode 100644 index 00000000..058ae920 --- /dev/null +++ b/crates/deploy/src/profile/profile_limits.rs @@ -0,0 +1,108 @@ +//! What a profile needs from the host: the sealed-archive size, the free RAM floor and its validation. + +#[allow(unused_imports)] +use super::*; + +impl Profile { + /// Host RAM the sealed memfd holds for the life of the service (0 for a file-backed archive). + pub fn memfd_bytes(&self) -> u64 { + match (self.kar_source, self.memfd_extents) { + (KarSource::File | KarSource::None, _) => 0, + (KarSource::Memfd, MemfdExtents::Full) => ARCHIVE_BYTES, + (KarSource::Memfd, MemfdExtents::PleOnly) => SPARSE_MEMFD_BYTES_ESTIMATE, + } + } + + /// `min_ram_available_bytes` for this profile. The profile figure is written for the full archive copy; a `ple_only` memfd + /// needs that much less. + pub fn min_ram_available(&self) -> u64 { + let saved = match (self.kar_source, self.memfd_extents) { + (KarSource::Memfd, MemfdExtents::PleOnly) => { + ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE + } + _ => 0, + }; + self.min_ram_available_bytes.saturating_sub(saved) + } + + pub fn validate(&self) -> Result<(), String> { + if self.memfd_extents == MemfdExtents::PleOnly { + if self.kar_source != KarSource::Memfd { + return Err("memfd_extents=ple_only needs kar_source=memfd (a file-backed archive has no memfd to make sparse)".into()); + } + // Freed RAM must not be refilled "on purpose" by an `auto` cache (docs/design/memory-single-copy-and-elastic-state.md section B). + if self.memory.prefix_cache_cap_mib().is_none() && self.memory.prefix_cache_on() { + return Err("memfd_extents=ple_only needs an explicit memory.prefix_cache_mib (or 0): `auto` would size the cache from the RAM the sparse memfd frees".into()); + } + } + if self.name.is_empty() + || self.name.len() > 64 + || !self + .name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + { + return Err("profile name must be 1..64 characters of [A-Za-z0-9._-]".into()); + } + if self.gpu_budget_bytes < (1 << 30) || self.gpu_budget_bytes > (1 << 40) { + return Err("gpu_budget_bytes must be between 1 GiB and 1 TiB".into()); + } + if !(1..=262_144).contains(&self.context_tokens) { + return Err("context_tokens must be 1..=262144 for the Original serve path".into()); + } + if let Some(capacity) = self.prefill_capacity + && !PREFILL_CAPACITIES.contains(&capacity) + { + return Err(format!( + "prefill_capacity must be one of {PREFILL_CAPACITIES:?}" + )); + } + if let Some(p) = self.spec_min_p + && !(0.0..=1.0).contains(&p) + { + return Err("spec_min_p must be within 0..=1".into()); + } + if let Some(kv) = &self.kv + && kv != "int8" + { + return Err("kv must be int8 (the engine refuses other formats)".into()); + } + if let Some(digest) = &self.expert_profile_sha256 + && (digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit())) + { + return Err("expert_profile_sha256 must be 64 hex digits".into()); + } + if let Some(path) = &self.expert_profile + && (path.is_empty() + || path.starts_with('/') + || path.split('/').any(|part| part == ".." || part.is_empty())) + { + return Err( + "expert_profile must be a relative path inside the assets directory".into(), + ); + } + self.memory.validate()?; + for (key, value) in &self.engine_env { + // LELEKA_CHAIN selects the chain-kernel group (docs/chain-kernels.md), LELEKA_SM120_* the compute-capability-12 kernel switches + // (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the GGUF PLE row reader (`kar_source: none`); every other switch is a serve-stack one + if !(key.starts_with("LELEKA_ORIGINAL_SERVE_") + || key.starts_with("LELEKA_SM120_") + || key.starts_with("LELEKA_PLE_") + || key == "LELEKA_CHAIN") + || !key + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + return Err(format!( + "engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_* or LELEKA_PLE_* name (or LELEKA_CHAIN)" + )); + } + if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) { + return Err(format!( + "engine_env value of {key} is empty or not printable" + )); + } + } + Ok(()) + } +} diff --git a/crates/deploy/src/profile/tests.rs b/crates/deploy/src/profile/tests.rs new file mode 100644 index 00000000..93d13c9e --- /dev/null +++ b/crates/deploy/src/profile/tests.rs @@ -0,0 +1,23 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn gpu(name: &str, sm: u32, mib: u64) -> Gpu { + Gpu { + index: 0, + name: name.into(), + driver: "595.99.02".into(), + vram_total_mib: mib, + vram_free_mib: mib, + sm: Some(sm), + } +} + +fn sparse_server() -> Profile { + Profile::builtin("rtx5090-32g").unwrap() +} + +mod budget_arguments; +mod builtin_profiles; +mod selection; +mod sparse_memfd; diff --git a/crates/deploy/src/profile/tests/budget_arguments.rs b/crates/deploy/src/profile/tests/budget_arguments.rs new file mode 100644 index 00000000..3d878143 --- /dev/null +++ b/crates/deploy/src/profile/tests/budget_arguments.rs @@ -0,0 +1,78 @@ +//! The memory budget in the engine arguments and environment, and the prefix-cache cap. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_environment() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + assert_eq!( + server.memory.args(), + [ + "--prefix-cache-mib", + "6144", + "--prefix-cache-tail", + "reply", + "--prefix-cache-block", + "8192" + ] + .map(str::to_owned) + .to_vec() + ); + let mut bad = server.memory.clone(); + bad.prefix_cache_tail = Some("always".into()); + assert!(bad.validate().is_err()); + let env = server.memory.env(); + assert_eq!(env["LELEKA_MEMORY_SOFT_FLOOR_MIB"], "4096"); + assert_eq!(env["LELEKA_MEMORY_HARD_FLOOR_MIB"], "2048"); + assert_eq!(env["LELEKA_MEMORY_LOCK"], "try"); + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + assert_eq!( + laptop.memory.env()["LELEKA_MEMORY_LOCK"], + "off", + "the laptop archive is a file, not a memfd" + ); + for profile in Profile::builtins() { + profile.validate().unwrap(); + } +} + +#[test] +fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_store() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + // 6144 MiB = what `auto` resolves to on this host today (5.7-6.1 GiB, docs/memory-safety.md section 8): behaviour at 245k is unchanged + assert_eq!(server.memory.prefix_cache_cap_mib(), Some(6144)); + assert!(server.memory.prefix_cache_on()); + assert!( + server + .memory + .args() + .windows(2) + .any(|w| w == ["--prefix-cache-mib", "6144"]) + ); + // a cache that fits the cap with room to spare: 245k tokens x 14,208 B + ~4 nodes of ~127 MiB is about 4 GiB + let session_245k = 245_000u64 * 14_208 + 4 * (127 << 20); + assert!(session_245k < 6144 << 20, "{session_245k}"); + // `auto`, `0`, off and unset are not caps + for (value, cap) in [ + (Some("auto"), None), + (Some("0"), None), + (None, None), + (Some("8192"), Some(8192)), + ] { + let mut memory = server.memory.clone(); + memory.prefix_cache_mib = value.map(str::to_owned); + assert_eq!(memory.prefix_cache_cap_mib(), cap, "{value:?}"); + } + // the dedicated memfd profile must keep an explicit cap; the laptop (file archive, mapped experts) is a different machine + for profile in Profile::builtins() + .iter() + .filter(|p| p.kar_source == KarSource::Memfd) + { + assert!( + profile.memory.prefix_cache_cap_mib().is_some(), + "{} uses `auto`", + profile.name + ); + } +} diff --git a/crates/deploy/src/profile/tests/builtin_profiles.rs b/crates/deploy/src/profile/tests/builtin_profiles.rs new file mode 100644 index 00000000..b41a0a74 --- /dev/null +++ b/crates/deploy/src/profile/tests/builtin_profiles.rs @@ -0,0 +1,236 @@ +//! The built-in profiles parse, validate and differ only where their form says so. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn built_in_profiles_parse_and_validate() { + for profile in Profile::builtins() { + profile.validate().unwrap(); + } + assert_eq!(Profile::builtins().len(), 4); +} + +#[test] +fn the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_matters() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let file = Profile::builtin("rtx5090-32g-file").unwrap(); + file.validate().unwrap(); + assert_eq!( + (file.kar_source, file.expert_source), + (KarSource::File, ExpertSource::Resident) + ); + // same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM the memfd no longer + // holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ + for (name, same) in [ + ( + "gpu_budget_bytes", + server.gpu_budget_bytes == file.gpu_budget_bytes, + ), + ( + "context_tokens", + server.context_tokens == file.context_tokens, + ), + ( + "prefill_capacity", + server.prefill_capacity == file.prefill_capacity, + ), + ("spec_min_p", server.spec_min_p == file.spec_min_p), + ( + "expert_profile", + server.expert_profile == file.expert_profile, + ), + ("engine_env", server.engine_env == file.engine_env), + ( + "prefix_cache_tail", + server.memory.prefix_cache_tail == file.memory.prefix_cache_tail, + ), + ( + "prefix_cache_block", + server.memory.prefix_cache_block == file.memory.prefix_cache_block, + ), + ( + "floors", + ( + server.memory.soft_floor_mib, + server.memory.hard_floor_mib, + server.memory.reserve_mib, + ) == ( + file.memory.soft_floor_mib, + file.memory.hard_floor_mib, + file.memory.reserve_mib, + ), + ), + ] { + assert!(same, "{name} must match rtx5090-32g"); + } + assert_eq!(file.memory.prefix_cache_mib.as_deref(), Some("6144")); + assert!( + file.min_ram_available_bytes + ARCHIVE_BYTES - 5_000_000_000 + <= server.min_ram_available_bytes, + "the file form does not need the archive's RAM" + ); + // an experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile + assert!(!file.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); + assert_eq!( + resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))) + .unwrap() + .name, + "rtx5090-32g" + ); + assert_eq!( + resolve(Some("rtx5090-32g-file"), None).unwrap().kar_source, + KarSource::File + ); +} + +#[test] +fn the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let ggufp = Profile::builtin("rtx5090-32g-gguf-ple").unwrap(); + ggufp.validate().unwrap(); + assert_eq!(ggufp.kar_source, KarSource::None); + assert_eq!(ggufp.memfd_bytes(), 0); + assert_eq!(KarSource::None.as_str(), "none"); + for (name, same) in [ + ( + "gpu_budget_bytes", + server.gpu_budget_bytes == ggufp.gpu_budget_bytes, + ), + ( + "context_tokens", + server.context_tokens == ggufp.context_tokens, + ), + ( + "prefill_capacity", + server.prefill_capacity == ggufp.prefill_capacity, + ), + ("spec_min_p", server.spec_min_p == ggufp.spec_min_p), + ( + "expert_profile", + server.expert_profile == ggufp.expert_profile, + ), + ("expert_source", server.expert_source == ggufp.expert_source), + ( + "prefix_cache_mib", + server.memory.prefix_cache_mib == ggufp.memory.prefix_cache_mib, + ), + ( + "prefix_cache_tail", + server.memory.prefix_cache_tail == ggufp.memory.prefix_cache_tail, + ), + ( + "prefix_cache_block", + server.memory.prefix_cache_block == ggufp.memory.prefix_cache_block, + ), + ] { + assert!(same, "{name} must match rtx5090-32g"); + } + // the engine switches are the server's plus the page-cache form of the PLE reader + let mut expected = server.engine_env.clone(); + expected.insert("LELEKA_PLE_DIRECT".into(), "0".into()); + expected.insert("LELEKA_ORIGINAL_SERVE_GGUF_PLE".into(), "1".into()); + assert_eq!(ggufp.engine_env, expected); + // experimental: never auto-selected + assert!(!ggufp.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); + assert_eq!( + resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))) + .unwrap() + .name, + "rtx5090-32g" + ); + // only the PLE reader family is let through next to the serve-stack switches + let mut bad = ggufp.clone(); + bad.engine_env.insert("LELEKA_PLEX".into(), "1".into()); + assert!(bad.validate().is_err()); + let mut json: serde_json::Value = serde_json::to_value(&ggufp).unwrap(); + assert_eq!(json["kar_source"], "none"); + json["kar_source"] = "memfd".into(); + let back: Profile = serde_json::from_value(json).unwrap(); + assert_eq!(back.kar_source, KarSource::Memfd); +} + +#[test] +fn only_the_server_profile_turns_the_prompt_routing_seed_off() { + // placement-class setting (docs/experiments/decode-tail-5090.md): off for the 5090 profile, the engine default and the laptop profile are unchanged + let server = Profile::builtin("rtx5090-32g").unwrap(); + assert_eq!( + server + .engine_env + .get("LELEKA_ORIGINAL_SERVE_SEED") + .map(String::as_str), + Some("off") + ); + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + assert!(!laptop.engine_env.contains_key("LELEKA_ORIGINAL_SERVE_SEED")); +} + +#[test] +fn only_the_server_profile_enables_the_mtp_draft_attention_switch() { + // bitwise draft-attention kernels of the compute capability 12 card (docs/experiments/draft-round-5090.md); the laptop (sm_86) has no companion for them + let server = Profile::builtin("rtx5090-32g").unwrap(); + assert_eq!( + server + .engine_env + .get("LELEKA_SM120_ATTN_DAILY_MTP") + .map(String::as_str), + Some("1") + ); + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + assert!( + !laptop + .engine_env + .contains_key("LELEKA_SM120_ATTN_DAILY_MTP") + ); + // the key space of engine_env still refuses everything else + let mut bad = server.clone(); + bad.engine_env.insert("LELEKA_SM86_X".into(), "1".into()); + assert!(bad.validate().is_err()); + let mut ok = server; + ok.engine_env + .insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "1".into()); + ok.validate().unwrap(); +} + +#[test] +fn validation_rejects_unsafe_values() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile + .engine_env + .insert("LD_PRELOAD".into(), "/tmp/x.so".into()); + assert!(profile.validate().unwrap_err().contains("LD_PRELOAD")); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.context_tokens = 524_288; + assert!(profile.validate().is_err()); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.prefill_capacity = Some(1000); + assert!(profile.validate().is_err()); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.expert_profile = Some("../x".into()); + assert!(profile.validate().is_err()); + profile.expert_profile = Some("/etc/passwd".into()); + assert!(profile.validate().is_err()); +} + +#[test] +fn memory_budget_validation_rejects_nonsense() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memory.hard_floor_mib = Some(8192); + assert!(profile.validate().unwrap_err().contains("hard_floor")); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memory.lock = Some("maybe".into()); + assert!(profile.validate().is_err()); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memory.prefix_cache_mib = Some("lots".into()); + assert!(profile.validate().is_err()); + profile.memory.prefix_cache_mib = Some("0".into()); + assert!(profile.validate().is_ok()); + profile.memory.cache_share_percent = Some(0); + assert!(profile.validate().is_err()); +} + +#[test] +fn unknown_fields_in_a_profile_file_are_refused() { + let text = BUILTIN[0].1.replacen('{', "{\"typo\": 1,", 1); + assert!(serde_json::from_str::(&text).is_err()); +} diff --git a/crates/deploy/src/profile/tests/selection.rs b/crates/deploy/src/profile/tests/selection.rs new file mode 100644 index 00000000..2b7126ec --- /dev/null +++ b/crates/deploy/src/profile/tests/selection.rs @@ -0,0 +1,49 @@ +//! Picking a profile from the detected GPU or an explicit name. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn auto_selection_picks_the_server_and_the_laptop_profile() { + let server = resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap(); + assert_eq!(server.name, "rtx5090-32g"); + assert_eq!(server.kar_source, KarSource::Memfd); + let laptop = resolve( + Some("auto"), + Some(&gpu("NVIDIA GeForce RTX 3080 Laptop GPU", 86, 16384)), + ) + .unwrap(); + assert_eq!(laptop.name, "rtx3080-16g"); + assert_eq!(laptop.kar_source, KarSource::File); + assert_eq!( + laptop.context_tokens, 262144, + "the owner's real work is 256k" + ); + assert_eq!( + (laptop.prefill_capacity, laptop.memory.prefix_cache_block), + (Some(6144), Some(6144)) + ); + assert_eq!(laptop.memory.prefix_cache_tail.as_deref(), Some("prompt")); +} + +#[test] +fn unmatched_gpu_and_missing_gpu_give_actionable_errors() { + let error = resolve(None, Some(&gpu("NVIDIA GeForce RTX 4090", 89, 24564))).unwrap_err(); + assert!(error.contains("--profile FILE"), "{error}"); + assert!(resolve(None, None).unwrap_err().contains("--profile")); + assert!( + resolve(Some("nope"), None) + .unwrap_err() + .contains("rtx5090-32g") + ); +} + +#[test] +fn explicit_name_overrides_the_detected_gpu() { + let forced = resolve( + Some("rtx3080-16g"), + Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)), + ) + .unwrap(); + assert_eq!(forced.name, "rtx3080-16g"); +} diff --git a/crates/deploy/src/profile/tests/sparse_memfd.rs b/crates/deploy/src/profile/tests/sparse_memfd.rs new file mode 100644 index 00000000..fc448e31 --- /dev/null +++ b/crates/deploy/src/profile/tests/sparse_memfd.rs @@ -0,0 +1,138 @@ +//! The sparse memfd form of the server profile: its pin, its RAM floor and what is serialized. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized() { + for profile in Profile::builtins() { + let want = if profile.name == "rtx5090-32g" { + MemfdExtents::PleOnly + } else { + MemfdExtents::Full + }; + assert_eq!(profile.memfd_extents, want, "{}", profile.name); + assert_eq!( + serde_json::to_string(&profile) + .unwrap() + .contains("\"memfd_extents\":"), + want == MemfdExtents::PleOnly, + "{}", + profile.name + ); + } + let mut full = sparse_server(); + full.memfd_extents = MemfdExtents::Full; + assert!( + !serde_json::to_string(&full) + .unwrap() + .contains("\"memfd_extents\":") + ); + let text = serde_json::to_string(&sparse_server()).unwrap(); + assert!(text.contains("\"memfd_extents\":\"ple_only\""), "{text}"); + let back: Profile = serde_json::from_str(&text).unwrap(); + assert_eq!(back, sparse_server()); + let mut value: serde_json::Value = serde_json::from_str( + &serde_json::to_string(&Profile::builtin("rtx5090-32g").unwrap()).unwrap(), + ) + .unwrap(); + value["memfd_extents"] = "everything".into(); + assert!(serde_json::from_value::(value).is_err()); +} + +#[test] +fn a_sparse_memfd_profile_needs_a_memfd_and_an_explicit_prefix_cap() { + sparse_server().validate().unwrap(); + // 0 (cache off) and any number are fine; `auto` would refill the freed RAM + for (value, ok) in [("6144", true), ("0", true), ("auto", false)] { + let mut profile = sparse_server(); + profile.memory.prefix_cache_mib = Some(value.into()); + assert_eq!(profile.validate().is_ok(), ok, "{value}"); + } + let mut profile = sparse_server(); + profile.memory.prefix_cache_mib = None; + assert!( + profile.validate().is_ok(), + "no cache at all cannot refill anything" + ); + let mut file_backed = sparse_server(); + file_backed.kar_source = KarSource::File; + let error = file_backed.validate().unwrap_err(); + assert!( + error.contains("ple_only") && error.contains("memfd"), + "{error}" + ); + // the same profile in the full form validates with `auto` + let mut full = Profile::builtin("rtx5090-32g").unwrap(); + full.memfd_extents = MemfdExtents::Full; + full.memory.prefix_cache_mib = Some("auto".into()); + full.validate().unwrap(); +} + +#[test] +fn a_sparse_memfd_holds_a_third_of_the_archive_and_lowers_the_ram_the_profile_asks_for() { + let mut full = Profile::builtin("rtx5090-32g").unwrap(); + full.memfd_extents = MemfdExtents::Full; + let sparse = sparse_server(); + assert_eq!(full.memfd_bytes(), ARCHIVE_BYTES); + assert_eq!(sparse.memfd_bytes(), SPARSE_MEMFD_BYTES_ESTIMATE); + // 320,001,536 rows x 50 B = 16,000,076,800 B are the floor of what the serve path reads + const { + assert!( + SPARSE_MEMFD_BYTES_ESTIMATE > 16_000_076_800 + && SPARSE_MEMFD_BYTES_ESTIMATE < ARCHIVE_BYTES / 3 + ) + }; + assert_eq!(full.min_ram_available(), full.min_ram_available_bytes); + assert_eq!( + sparse.min_ram_available(), + full.min_ram_available_bytes - (ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE) + ); + assert!( + sparse.min_ram_available() > 70_000_000_000 && sparse.min_ram_available() < 80_000_000_000 + ); + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + assert_eq!( + (laptop.memfd_bytes(), laptop.min_ram_available()), + (0, laptop.min_ram_available_bytes) + ); +} + +#[test] +fn the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent() { + let none = |_: &str| None; + let with = |value: &str| { + let value = value.to_owned(); + move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone()) + }; + let hex64 = "ab".repeat(32); + let zeros = "00".repeat(32); + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + if compiled == [0u8; 32] { + // not measured yet: the sparse form refuses to start without an explicit value, and says how to get one + let error = extents_sha256(&none).unwrap_err(); + assert!( + error.contains("kar_census") && error.contains("--hash-extents"), + "{error}" + ); + assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex")); + assert!( + extents_sha256(&with("abcd")) + .unwrap_err() + .contains("64 hex") + ); + assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero")); + let (pin, source) = extents_sha256(&with(&hex64)).unwrap(); + assert_eq!((pin, source), ([0xab; 32], PinSource::Operator)); + } else { + // measured: the binary's value wins and an environment value cannot override it + assert_eq!( + extents_sha256(&none).unwrap(), + (compiled, PinSource::Compiled) + ); + assert_eq!( + extents_sha256(&with(&hex64)).unwrap(), + (compiled, PinSource::Compiled) + ); + } +} diff --git a/crates/deploy/src/reconfigure/tests.rs b/crates/deploy/src/reconfigure/tests.rs index a5993e16..56aa5098 100644 --- a/crates/deploy/src/reconfigure/tests.rs +++ b/crates/deploy/src/reconfigure/tests.rs @@ -63,537 +63,6 @@ fn big_host() -> Facts { host(32, 121, 100, vec![gpu(32607, 32100)]) } -#[test] -fn runtime_settings_become_profile_fields_with_the_engines_ranges() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - let settings = json!({ - "context_tokens": 131072, "prefill_capacity": 4096, "kv_resident": 0, "prefix_cache_mib": "20480", - "prefix_cache_tail": "reply", "prefix_cache_block": 4096, "prefix_retention_min": 30, "cpu_workers": 6, "spec_min_p": 0.5 - }); - let changed = apply_settings(&mut profile, settings.as_object().unwrap()).unwrap(); - for name in [ - "context_tokens", - "prefill_capacity", - "prefix_cache_mib", - "prefix_cache_block", - "prefix_retention_min", - "cpu_workers", - "spec_min_p", - ] { - assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); - } - assert_eq!( - ( - profile.context_tokens, - profile.prefill_capacity, - profile.kv_resident - ), - (131072, Some(4096), Some(0)) - ); - assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("20480")); - assert_eq!(profile.memory.prefix_cache_tail.as_deref(), Some("reply")); - assert_eq!( - ( - profile.memory.prefix_cache_block, - profile.memory.prefix_retention_min - ), - (Some(4096), Some(30)) - ); - assert_eq!( - profile.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("6") - ); - assert_eq!(profile.spec_min_p, Some(0.5)); - // the same document again changes nothing - assert!( - apply_settings(&mut profile, settings.as_object().unwrap()) - .unwrap() - .is_empty() - ); - // and they reach the engine as flags and environment - let config = RunConfig::new( - &Dirs { - prefix: "/p".into(), - state: "/s".into(), - assets: "/a".into(), - }, - Ports { - api: "127.0.0.1:1".into(), - engine: "127.0.0.1:2".into(), - daemon: "127.0.0.1:3".into(), - }, - 0, - profile, - BTreeMap::new(), - ); - let args = config.engine_args(crate::config::KarArg::Fd).join(" "); - assert!( - args.contains("--context-tokens 131072") - && args.contains("--original-prefill-capacity 4096"), - "{args}" - ); - assert!( - args.contains("--kv-resident 0") && args.contains("--prefix-cache-mib 20480"), - "{args}" - ); - assert!( - args.contains("--prefix-cache-tail reply") && args.contains("--prefix-cache-block 4096"), - "{args}" - ); - assert!(args.contains("--spec-min-p 0.5"), "{args}"); - let env = config.engine_environment(); - assert_eq!( - env.get("LELEKA_PREFIX_RETENTION_S").map(String::as_str), - Some("1800") - ); - assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("6")); -} - -#[test] -fn invalid_settings_change_nothing_and_say_why() { - for (bad, why) in [ - (json!({"context_tokens": 0}), "context_tokens"), - (json!({"context_tokens": 300000}), "context_tokens"), - (json!({"context_tokens": "big"}), "whole number"), - (json!({"prefill_capacity": 5000}), "prefill_capacity"), - (json!({"kv_resident": 1000}), "kv_resident"), - (json!({"cpu_workers": 0}), "cpu_workers"), - (json!({"cpu_workers": 65}), "cpu_workers"), - (json!({"spec_min_p": 1.5}), "spec_min_p"), - (json!({"prefix_cache_tail": "always"}), "prefix_cache_tail"), - (json!({"prefix_cache_mib": "lots"}), "prefix_cache_mib"), - (json!({"prefix_cache_block": 300}), "multiple of 256"), - ( - json!({"prefill_capacity": 4096, "prefix_cache_block": 8192}), - "larger than the prefill chunk", - ), - (json!({"nonsense": 1}), "unknown setting"), - ] { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - let before = profile.clone(); - let error = apply_settings(&mut profile, bad.as_object().unwrap()).unwrap_err(); - assert!(error.contains(why), "{bad}: {error}"); - assert_eq!(profile, before, "{bad} must change nothing"); - } -} - -#[test] -fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - // a `ple_only` profile refuses an `auto` cache (the freed RAM would be refilled); the full form accepts it - profile.memfd_extents = crate::profile::MemfdExtents::Full; - profile.memory.prefix_cache_mib = None; - apply_settings( - &mut profile, - json!({"prefix_cache_tail": "prompt"}).as_object().unwrap(), - ) - .unwrap(); - assert_eq!( - profile.memory.prefix_cache_mib.as_deref(), - Some("auto"), - "the engine opens an auto cache for a lone member" - ); - apply_settings( - &mut profile, - json!({"prefix_cache_mib": "off"}).as_object().unwrap(), - ) - .unwrap(); - assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("0")); - profile.memory.prefix_cache_block = Some(512); - let mut config = server_config(); - config.profile = profile; - let args = config.engine_args(crate::config::KarArg::Fd).join(" "); - assert!( - !args.contains("--prefix-cache-block"), - "a block is not passed while the cache is off: {args}" - ); -} - -#[test] -fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { - let config = server_config(); - let planned = plan( - &config, - &request(Some(24), None, json!({})), - &big_host(), - true, - ) - .unwrap(); - assert!(!planned.unchanged); - assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB); - assert_eq!( - planned - .config - .base_profile - .as_ref() - .unwrap() - .gpu_budget_bytes, - 24 * GIB - ); - assert_eq!( - planned.config.profile.context_tokens, - config.profile.context_tokens - ); - assert_eq!(planned.config.preset, Preset::Dedicated); - let args = planned - .config - .engine_args(crate::config::KarArg::Fd) - .join(" "); - assert!( - args.contains(&format!("--gpu-budget {}", 24 * GIB)), - "{args}" - ); - // the same budget again is a no-op, not a five-minute restart - // (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 GiB just planned) - let same = plan( - &planned.config, - &request(Some(24), None, json!({})), - &big_host(), - true, - ) - .unwrap(); - assert!(same.unchanged, "the profile already has a 24 GiB budget"); -} - -#[test] -fn the_workstation_preset_applies_and_dedicated_undoes_it() { - let config = server_config(); - let to_workstation = plan( - &config, - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap(); - let ws = &to_workstation.config; - assert_eq!(ws.preset, Preset::Workstation); - assert_eq!( - ws.profile.gpu_budget_bytes, - 29 * GIB, - "32100 MiB free minus the 2 GiB left to the desktop" - ); - assert_eq!(ws.profile.memory.soft_floor_mib, Some(16384)); - assert_eq!( - ws.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("15") - ); - // back: the unmodified profile is restored from the recorded base - let back = plan( - ws, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap(); - assert_eq!(back.config.profile, config.profile); - assert_eq!(back.config.preset, Preset::Dedicated); - // `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it - let both = plan( - &config, - &request(Some(24), Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap(); - assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB); - assert_eq!(both.config.preset, Preset::Workstation); - assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384)); -} - -#[test] -fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset() { - let mut config = server_config(); - config.base_profile = None; - config.preset = Preset::Workstation; - let error = plan( - &config, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap_err(); - assert!(error.contains("leleka up --preset dedicated"), "{error}"); - // staying on workstation, or going to it from dedicated, works without a base - assert!( - plan( - &config, - &request(Some(20), None, json!({})), - &big_host(), - true - ) - .is_ok() - ); - config.preset = Preset::Dedicated; - assert!( - plan( - &config, - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true - ) - .is_ok() - ); -} - -#[test] -fn unsafe_values_are_refused_by_the_planner() { - let config = server_config(); - let refused = |request: Request, facts: &Facts, resident: bool| { - plan(&config, &request, facts, resident).unwrap_err() - }; - // more than the card has - let error = refused(request(Some(40), None, json!({})), &big_host(), true); - assert!(error.contains("does not fit the 32607 MiB"), "{error}"); - // not a budget at all - assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024")); - assert!(refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024")); - // another process holds the card (checked once the engine is stopped) - let busy = host(32, 121, 100, vec![gpu(32607, 9000)]); - let error = refused(request(Some(24), None, json!({})), &busy, true); - assert!( - error.contains("9000 MiB free") && error.contains("needs"), - "{error}" - ); - // the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM - assert!( - plan( - &config, - &request(Some(24), None, json!({})), - &optimistic(&busy), - true - ) - .is_ok() - ); - // the workstation preset on a card that is mostly taken is a problem, not a silent shrink - let taken = host(32, 121, 100, vec![gpu(32607, 12000)]); - let error = refused( - request(None, Some(Preset::Workstation), json!({})), - &taken, - true, - ); - assert!(error.contains("workstation preset"), "{error}"); - // an explicit budget the preset cannot give - let error = refused( - request(Some(30), Some(Preset::Workstation), json!({})), - &big_host(), - true, - ); - assert!(error.contains("asks for more"), "{error}"); - // a bad runtime setting riding along refuses the whole request - assert!( - refused( - request(Some(24), None, json!({"cpu_workers": 99})), - &big_host(), - true - ) - .contains("cpu_workers") - ); - // a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form - let small = host(32, 64, 10, vec![gpu(32607, 32100)]); - let error = refused( - request(None, Some(Preset::Workstation), json!({})), - &small, - true, - ); - assert!( - error.contains("file-backed form") || error.contains("leleka up"), - "{error}" - ); -} - -#[test] -fn the_resident_archive_is_not_charged_twice_to_the_host() { - // 121 GiB host, 66 GiB available *with* the 55 GB memfd already resident (what the supervisor sees): fits the dedicated preset - let config = server_config(); - assert!( - plan( - &config, - &request(Some(20), None, json!({})), - &host(32, 121, 66, vec![gpu(32607, 32100)]), - true - ) - .is_ok() - ); - // a profile that reads the archive from a file keeps charging it to the planner as before - let mut file = server_config(); - file.profile.kar_source = KarSource::File; - file.base_profile = Some(file.profile.clone()); - assert!( - plan( - &file, - &request(Some(20), None, json!({})), - &host(32, 121, 40, vec![gpu(32607, 32100)]), - false - ) - .is_ok() - ); -} - -#[test] -fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() { - let mut config = plan( - &server_config(), - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap() - .config; - assert_eq!( - config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("15") - ); - let changed = record_settings( - &mut config, - json!({"context_tokens": 65536, "cpu_workers": 5}) - .as_object() - .unwrap(), - ) - .unwrap(); - assert_eq!( - changed, - vec!["context_tokens".to_owned(), "cpu_workers".to_owned()] - ); - assert_eq!(config.profile.context_tokens, 65536); - assert_eq!(config.base_profile.as_ref().unwrap().context_tokens, 65536); - assert_eq!( - config - .engine_environment() - .get(CPU_WORKERS_ENV) - .map(String::as_str), - Some("5") - ); - // an invalid document leaves the configuration alone - let before = config.clone(); - assert!( - record_settings( - &mut config, - json!({"context_tokens": 0}).as_object().unwrap() - ) - .is_err() - ); - assert_eq!(config, before); - // switching preset afterwards keeps the explicit setting - let again = plan( - &config, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap() - .config; - assert_eq!(again.profile.context_tokens, 65536); - assert_eq!( - again - .engine_environment() - .get(CPU_WORKERS_ENV) - .map(String::as_str), - Some("5") - ); -} - -#[test] -fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { - let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let dirs = Dirs { - prefix: root.join("p"), - state: root.join("s"), - assets: root.join("a"), - }; - let paths = dirs.paths(); - std::fs::create_dir_all(paths.run_dir()).unwrap(); - assert!(take_request(&paths).is_none()); - let asked = request( - Some(24), - Some(Preset::Workstation), - json!({"context_tokens": 65536}), - ); - write_request(&paths, &asked).unwrap(); - assert!( - write_request(&paths, &asked) - .unwrap_err() - .contains("waiting") - ); - assert_eq!(take_request(&paths).unwrap().unwrap(), asked); - assert!(take_request(&paths).is_none(), "the file is consumed"); - // a corrupt request is reported, not retried forever - std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); - assert!( - take_request(&paths) - .unwrap() - .unwrap_err() - .contains("invalid") - ); - assert!(!paths.reconfigure_request().exists()); - let outcome = Outcome { - id: asked.id.clone(), - state: State::Refused, - message: "no".into(), - effective: None, - persisted: false, - }; - write_outcome(&paths, &outcome).unwrap(); - assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); - assert_eq!(read_outcome(&paths, "other"), None); - let _ = std::fs::remove_dir_all(&root); -} - -#[test] -fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { - let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let dirs = Dirs { - prefix: root.join("p"), - state: root.join("s"), - assets: root.join("a"), - }; - let paths = dirs.paths(); - std::fs::create_dir_all(paths.run_dir()).unwrap(); - let mut config = server_config(); - config.prefix = dirs.prefix.display().to_string(); - config.state = dirs.state.display().to_string(); - config.assets = dirs.assets.display().to_string(); - persist(&paths, &config).unwrap(); - let changed = persist_offline( - &paths, - json!({"context_tokens": 100000, "prefix_cache_tail": "prompt"}) - .as_object() - .unwrap(), - ) - .unwrap(); - assert_eq!(changed.len(), 2); - let back = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!(back.profile.context_tokens, 100000); - assert_eq!( - back.profile.memory.prefix_cache_tail.as_deref(), - Some("prompt") - ); - let strata: Value = - serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); - assert_eq!(strata["runtime"]["max_context"], 100000); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(paths.run_config()) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o600); - } - let _ = std::fs::remove_dir_all(&root); -} - -#[test] -fn the_effective_summary_names_the_numbers_in_force() { - let summary = effective(&server_config()); - // the 5090 profile ships 32819404800 bytes (31,299 MiB, "31,300 MiB" in the slots-footprint notes), the budget the dense-slab slot gain needs - assert_eq!( - summary["gpu_budget_gib"], - 32819404800_f64 / (1u64 << 30) as f64 - ); - assert_eq!(summary["preset"], "dedicated"); - assert_eq!(summary["context_tokens"], 262144); - assert_eq!(summary["cpu_workers"], 15); -} +mod planning; +mod recording; +mod settings_ranges; diff --git a/crates/deploy/src/reconfigure/tests/planning.rs b/crates/deploy/src/reconfigure/tests/planning.rs new file mode 100644 index 00000000..b5bba64a --- /dev/null +++ b/crates/deploy/src/reconfigure/tests/planning.rs @@ -0,0 +1,158 @@ +//! A budget change or a preset is planned against the host and keeps everything else. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { + let config = server_config(); + let planned = plan( + &config, + &request(Some(24), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(!planned.unchanged); + assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!( + planned + .config + .base_profile + .as_ref() + .unwrap() + .gpu_budget_bytes, + 24 * GIB + ); + assert_eq!( + planned.config.profile.context_tokens, + config.profile.context_tokens + ); + assert_eq!(planned.config.preset, Preset::Dedicated); + let args = planned + .config + .engine_args(crate::config::KarArg::Fd) + .join(" "); + assert!( + args.contains(&format!("--gpu-budget {}", 24 * GIB)), + "{args}" + ); + // the same budget again is a no-op, not a five-minute restart + // (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 GiB just planned) + let same = plan( + &planned.config, + &request(Some(24), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(same.unchanged, "the profile already has a 24 GiB budget"); +} + +#[test] +fn the_workstation_preset_applies_and_dedicated_undoes_it() { + let config = server_config(); + let to_workstation = plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + let ws = &to_workstation.config; + assert_eq!(ws.preset, Preset::Workstation); + assert_eq!( + ws.profile.gpu_budget_bytes, + 29 * GIB, + "32100 MiB free minus the 2 GiB left to the desktop" + ); + assert_eq!(ws.profile.memory.soft_floor_mib, Some(16384)); + assert_eq!( + ws.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("15") + ); + // back: the unmodified profile is restored from the recorded base + let back = plan( + ws, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(back.config.profile, config.profile); + assert_eq!(back.config.preset, Preset::Dedicated); + // `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it + let both = plan( + &config, + &request(Some(24), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!(both.config.preset, Preset::Workstation); + assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384)); +} + +#[test] +fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset() { + let mut config = server_config(); + config.base_profile = None; + config.preset = Preset::Workstation; + let error = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap_err(); + assert!(error.contains("leleka up --preset dedicated"), "{error}"); + // staying on workstation, or going to it from dedicated, works without a base + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &big_host(), + true + ) + .is_ok() + ); + config.preset = Preset::Dedicated; + assert!( + plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true + ) + .is_ok() + ); +} + +#[test] +fn the_resident_archive_is_not_charged_twice_to_the_host() { + // 121 GiB host, 66 GiB available *with* the 55 GB memfd already resident (what the supervisor sees): fits the dedicated preset + let config = server_config(); + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &host(32, 121, 66, vec![gpu(32607, 32100)]), + true + ) + .is_ok() + ); + // a profile that reads the archive from a file keeps charging it to the planner as before + let mut file = server_config(); + file.profile.kar_source = KarSource::File; + file.base_profile = Some(file.profile.clone()); + assert!( + plan( + &file, + &request(Some(20), None, json!({})), + &host(32, 121, 40, vec![gpu(32607, 32100)]), + false + ) + .is_ok() + ); +} diff --git a/crates/deploy/src/reconfigure/tests/recording.rs b/crates/deploy/src/reconfigure/tests/recording.rs new file mode 100644 index 00000000..58bb4f54 --- /dev/null +++ b/crates/deploy/src/reconfigure/tests/recording.rs @@ -0,0 +1,173 @@ +//! Recording the settings, the request and answer files, persisting the config and the effective summary. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() { + let mut config = plan( + &server_config(), + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!( + config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("15") + ); + let changed = record_settings( + &mut config, + json!({"context_tokens": 65536, "cpu_workers": 5}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!( + changed, + vec!["context_tokens".to_owned(), "cpu_workers".to_owned()] + ); + assert_eq!(config.profile.context_tokens, 65536); + assert_eq!(config.base_profile.as_ref().unwrap().context_tokens, 65536); + assert_eq!( + config + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); + // an invalid document leaves the configuration alone + let before = config.clone(); + assert!( + record_settings( + &mut config, + json!({"context_tokens": 0}).as_object().unwrap() + ) + .is_err() + ); + assert_eq!(config, before); + // switching preset afterwards keeps the explicit setting + let again = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!(again.profile.context_tokens, 65536); + assert_eq!( + again + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); +} + +#[test] +fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { + let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + assert!(take_request(&paths).is_none()); + let asked = request( + Some(24), + Some(Preset::Workstation), + json!({"context_tokens": 65536}), + ); + write_request(&paths, &asked).unwrap(); + assert!( + write_request(&paths, &asked) + .unwrap_err() + .contains("waiting") + ); + assert_eq!(take_request(&paths).unwrap().unwrap(), asked); + assert!(take_request(&paths).is_none(), "the file is consumed"); + // a corrupt request is reported, not retried forever + std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); + assert!( + take_request(&paths) + .unwrap() + .unwrap_err() + .contains("invalid") + ); + assert!(!paths.reconfigure_request().exists()); + let outcome = Outcome { + id: asked.id.clone(), + state: State::Refused, + message: "no".into(), + effective: None, + persisted: false, + }; + write_outcome(&paths, &outcome).unwrap(); + assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); + assert_eq!(read_outcome(&paths, "other"), None); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { + let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + let mut config = server_config(); + config.prefix = dirs.prefix.display().to_string(); + config.state = dirs.state.display().to_string(); + config.assets = dirs.assets.display().to_string(); + persist(&paths, &config).unwrap(); + let changed = persist_offline( + &paths, + json!({"context_tokens": 100000, "prefix_cache_tail": "prompt"}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!(changed.len(), 2); + let back = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!(back.profile.context_tokens, 100000); + assert_eq!( + back.profile.memory.prefix_cache_tail.as_deref(), + Some("prompt") + ); + let strata: Value = + serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); + assert_eq!(strata["runtime"]["max_context"], 100000); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(paths.run_config()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn the_effective_summary_names_the_numbers_in_force() { + let summary = effective(&server_config()); + // the 5090 profile ships 32819404800 bytes (31,299 MiB, "31,300 MiB" in the slots-footprint notes), the budget the dense-slab slot gain needs + assert_eq!( + summary["gpu_budget_gib"], + 32819404800_f64 / (1u64 << 30) as f64 + ); + assert_eq!(summary["preset"], "dedicated"); + assert_eq!(summary["context_tokens"], 262144); + assert_eq!(summary["cpu_workers"], 15); +} diff --git a/crates/deploy/src/reconfigure/tests/settings_ranges.rs b/crates/deploy/src/reconfigure/tests/settings_ranges.rs new file mode 100644 index 00000000..43c40f89 --- /dev/null +++ b/crates/deploy/src/reconfigure/tests/settings_ranges.rs @@ -0,0 +1,216 @@ +//! Runtime settings become profile fields within the engine's ranges; invalid and unsafe values change nothing. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn runtime_settings_become_profile_fields_with_the_engines_ranges() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let settings = json!({ + "context_tokens": 131072, "prefill_capacity": 4096, "kv_resident": 0, "prefix_cache_mib": "20480", + "prefix_cache_tail": "reply", "prefix_cache_block": 4096, "prefix_retention_min": 30, "cpu_workers": 6, "spec_min_p": 0.5 + }); + let changed = apply_settings(&mut profile, settings.as_object().unwrap()).unwrap(); + for name in [ + "context_tokens", + "prefill_capacity", + "prefix_cache_mib", + "prefix_cache_block", + "prefix_retention_min", + "cpu_workers", + "spec_min_p", + ] { + assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); + } + assert_eq!( + ( + profile.context_tokens, + profile.prefill_capacity, + profile.kv_resident + ), + (131072, Some(4096), Some(0)) + ); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("20480")); + assert_eq!(profile.memory.prefix_cache_tail.as_deref(), Some("reply")); + assert_eq!( + ( + profile.memory.prefix_cache_block, + profile.memory.prefix_retention_min + ), + (Some(4096), Some(30)) + ); + assert_eq!( + profile.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("6") + ); + assert_eq!(profile.spec_min_p, Some(0.5)); + // the same document again changes nothing + assert!( + apply_settings(&mut profile, settings.as_object().unwrap()) + .unwrap() + .is_empty() + ); + // and they reach the engine as flags and environment + let config = RunConfig::new( + &Dirs { + prefix: "/p".into(), + state: "/s".into(), + assets: "/a".into(), + }, + Ports { + api: "127.0.0.1:1".into(), + engine: "127.0.0.1:2".into(), + daemon: "127.0.0.1:3".into(), + }, + 0, + profile, + BTreeMap::new(), + ); + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + args.contains("--context-tokens 131072") + && args.contains("--original-prefill-capacity 4096"), + "{args}" + ); + assert!( + args.contains("--kv-resident 0") && args.contains("--prefix-cache-mib 20480"), + "{args}" + ); + assert!( + args.contains("--prefix-cache-tail reply") && args.contains("--prefix-cache-block 4096"), + "{args}" + ); + assert!(args.contains("--spec-min-p 0.5"), "{args}"); + let env = config.engine_environment(); + assert_eq!( + env.get("LELEKA_PREFIX_RETENTION_S").map(String::as_str), + Some("1800") + ); + assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("6")); +} + +#[test] +fn invalid_settings_change_nothing_and_say_why() { + for (bad, why) in [ + (json!({"context_tokens": 0}), "context_tokens"), + (json!({"context_tokens": 300000}), "context_tokens"), + (json!({"context_tokens": "big"}), "whole number"), + (json!({"prefill_capacity": 5000}), "prefill_capacity"), + (json!({"kv_resident": 1000}), "kv_resident"), + (json!({"cpu_workers": 0}), "cpu_workers"), + (json!({"cpu_workers": 65}), "cpu_workers"), + (json!({"spec_min_p": 1.5}), "spec_min_p"), + (json!({"prefix_cache_tail": "always"}), "prefix_cache_tail"), + (json!({"prefix_cache_mib": "lots"}), "prefix_cache_mib"), + (json!({"prefix_cache_block": 300}), "multiple of 256"), + ( + json!({"prefill_capacity": 4096, "prefix_cache_block": 8192}), + "larger than the prefill chunk", + ), + (json!({"nonsense": 1}), "unknown setting"), + ] { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let before = profile.clone(); + let error = apply_settings(&mut profile, bad.as_object().unwrap()).unwrap_err(); + assert!(error.contains(why), "{bad}: {error}"); + assert_eq!(profile, before, "{bad} must change nothing"); + } +} + +#[test] +fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + // a `ple_only` profile refuses an `auto` cache (the freed RAM would be refilled); the full form accepts it + profile.memfd_extents = crate::profile::MemfdExtents::Full; + profile.memory.prefix_cache_mib = None; + apply_settings( + &mut profile, + json!({"prefix_cache_tail": "prompt"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!( + profile.memory.prefix_cache_mib.as_deref(), + Some("auto"), + "the engine opens an auto cache for a lone member" + ); + apply_settings( + &mut profile, + json!({"prefix_cache_mib": "off"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("0")); + profile.memory.prefix_cache_block = Some(512); + let mut config = server_config(); + config.profile = profile; + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + !args.contains("--prefix-cache-block"), + "a block is not passed while the cache is off: {args}" + ); +} + +#[test] +fn unsafe_values_are_refused_by_the_planner() { + let config = server_config(); + let refused = |request: Request, facts: &Facts, resident: bool| { + plan(&config, &request, facts, resident).unwrap_err() + }; + // more than the card has + let error = refused(request(Some(40), None, json!({})), &big_host(), true); + assert!(error.contains("does not fit the 32607 MiB"), "{error}"); + // not a budget at all + assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024")); + assert!(refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024")); + // another process holds the card (checked once the engine is stopped) + let busy = host(32, 121, 100, vec![gpu(32607, 9000)]); + let error = refused(request(Some(24), None, json!({})), &busy, true); + assert!( + error.contains("9000 MiB free") && error.contains("needs"), + "{error}" + ); + // the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM + assert!( + plan( + &config, + &request(Some(24), None, json!({})), + &optimistic(&busy), + true + ) + .is_ok() + ); + // the workstation preset on a card that is mostly taken is a problem, not a silent shrink + let taken = host(32, 121, 100, vec![gpu(32607, 12000)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &taken, + true, + ); + assert!(error.contains("workstation preset"), "{error}"); + // an explicit budget the preset cannot give + let error = refused( + request(Some(30), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ); + assert!(error.contains("asks for more"), "{error}"); + // a bad runtime setting riding along refuses the whole request + assert!( + refused( + request(Some(24), None, json!({"cpu_workers": 99})), + &big_host(), + true + ) + .contains("cpu_workers") + ); + // a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form + let small = host(32, 64, 10, vec![gpu(32607, 32100)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &small, + true, + ); + assert!( + error.contains("file-backed form") || error.contains("leleka up"), + "{error}" + ); +} diff --git a/crates/deploy/src/resources.rs b/crates/deploy/src/resources.rs index afc20c02..1bdc52ec 100644 --- a/crates/deploy/src/resources.rs +++ b/crates/deploy/src/resources.rs @@ -116,285 +116,6 @@ fn gib_text(bytes: u64) -> String { format!("{:.1} GiB", bytes as f64 / GIB as f64) } -/// The largest prompt chunk an expert cache of this GPU budget can lend to the prompt path (measured on the 3080 laptop with the pinned Qwen3.8 -/// IQ3_S pack: a budget of 13 GiB holds 2,234 expert slots of 1.97 MiB, about 520 more per GiB; the loan of a chunk plus the 128-slot floor is -/// 1,282 slots at 2048, 1,497 at 3072, 1,713 at 4096, 2,144 at 6144 and about 2,575 at 8192; a chunk that does not fit stops the engine from opening). -/// Whole GiB, rounded down, with the margin the 1-GiB steps leave: 14+ GiB carry 8192, 13 carry 6144, 12 carry 3072, less keeps 2048. -pub fn prefill_capacity_for_budget(gpu_budget_bytes: u64) -> u32 { - match gpu_budget_bytes / GIB { - 14.. => 8192, - 13 => 6144, - 12 => 3072, - _ => 2048, - } -} - -/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM. -pub fn workstation_ram_target(total: u64) -> u64 { - if total >= 64 * GIB { - 16 * GIB - } else if total >= 32 * GIB { - 12 * GIB - } else { - 8 * GIB - } -} - -/// The host as the planner should see it when the sealed archive memfd is already resident (an inherited `--kar-fd`, or the -/// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the -/// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not. -pub fn with_resident_archive(facts: &Facts) -> Facts { - with_resident_bytes(facts, ARCHIVE_BYTES) -} - -/// [`with_resident_archive`] for a memfd of `bytes` (a `ple_only` memfd holds about 16 GB, not 55). -pub fn with_resident_bytes(facts: &Facts, bytes: u64) -> Facts { - let mut facts = facts.clone(); - facts.memory.available = facts.memory.available.saturating_add(bytes); - facts -} - -pub fn compute( - facts: &Facts, - gpu: Option<&Gpu>, - profile: &Profile, - preset: Preset, -) -> ResourcePlan { - let mut plan = ResourcePlan { - preset, - cores: facts.cpu_cores, - cpu_workers: None, - gpu_budget_bytes: profile.gpu_budget_bytes, - min_vram_free_mib: profile.min_vram_free_mib, - vram_free_after_mib: None, - ram_floors_mib: None, - ram_expected_free_after_bytes: None, - mapped_resident_gib: None, - resident_budget_gib: None, - windows_floors_mib: None, - mapped_working_set_gib: None, - problems: Vec::new(), - warnings: Vec::new(), - }; - - // CPU - if facts.cpu_cores > 0 { - let cores = facts.cpu_cores; - let leave = match preset { - Preset::Dedicated => 2, - Preset::Workstation if cores <= 16 => 4, - Preset::Workstation => 8, - }; - let mut workers = cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS); - // The pool's workers spin while they wait: one without a core of its own steals cycles from one that has it, so a - // bigger count is slower, not just useless (docs/upstream-port-plan.md row 2.3). Where the platform reports the - // physical cores (Windows), the count never exceeds every physical core but the host thread's: 7 on the 8-core - // laptop instead of 12 (the workstation preset's logical-core count); the 16-core server is unchanged (15). - if facts.cpu_physical_cores > 0 { - workers = workers.min(facts.cpu_physical_cores.saturating_sub(1).max(1)); - } - plan.cpu_workers = Some(workers); - if preset == Preset::Workstation && cores < leave + 1 { - plan.warnings.push(format!( - "only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)" - )); - } - } - - // VRAM - if let Some(gpu) = gpu { - let budget_mib = profile.gpu_budget_bytes / MIB; - if preset == Preset::Workstation { - let cap_mib = (gpu - .vram_free_mib - .saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) - / 1024) - * 1024; - if cap_mib < budget_mib { - plan.gpu_budget_bytes = cap_mib * MIB; - let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib); - plan.min_vram_free_mib = Some(need); - // Below half of the profile budget the expert tier and KV window shrink past what was measured. - if cap_mib * 2 < budget_mib { - plan.problems.push(format!( - "the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)", - WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib - )); - } - } - } - let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0)); - plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used)); - } - - // Host RAM - let ram = &facts.memory; - if ram.total > 0 { - let target = match preset { - // Windows reclaims standby and trimmed mapped pages on its own (the engine trims its working set under pressure), so a - // free-RAM target above 8 GiB only starves the prefix cache: live 48 GB run 2026-10-26, 12 GiB left it a budget of 0. - Preset::Workstation if facts.os == "windows" => { - workstation_ram_target(ram.total).min(WINDOWS_WORKSTATION_RAM_TARGET_BYTES) - } - Preset::Workstation => workstation_ram_target(ram.total), - Preset::Dedicated => profile - .memory - .soft_floor_mib - .map_or(4 * GIB, |mib| mib * MIB), - }; - if preset == Preset::Workstation { - let soft = target / MIB; - plan.ram_floors_mib = Some((soft, soft / 2)); - } - // The sealed memfd holds the whole archive; a file-backed archive with a resident expert bank (rtx5090-32g-file) holds only the bank and - // the engine's pins, its archive pages are page cache that the kernel gives back. The mapped file form (laptop) is already the low tier. - // `kar_source: none` has no archive at all (the PLE table is read from the shard through the page cache): the same footprint. - let resident_file = matches!(profile.kar_source, KarSource::File | KarSource::None) - && profile.expert_source == ExpertSource::Resident; - if profile.kar_source == KarSource::Memfd || resident_file { - let engine = if profile.expert_source == ExpertSource::Resident { - ENGINE_FIXED_RESIDENT_BYTES - } else { - ENGINE_EXTRA_BYTES - }; - let footprint = if resident_file { - engine - } else { - profile.memfd_bytes() + engine - }; - let after = ram.available.saturating_sub(footprint); - let reserve = profile - .memory - .reserve_mib - .map_or(DEFAULT_RESERVE_BYTES, |mib| mib * MIB); - if after >= target + reserve { - plan.ram_expected_free_after_bytes = Some(after); - } else { - // Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing. - let resident = ram - .available - .saturating_sub(target + reserve + MAPPED_OVERHEAD_BYTES) - / GIB; - let resident = resident.min(RESIDENT_BANK_GIB) as u32; - plan.mapped_resident_gib = Some(resident); - plan.ram_expected_free_after_bytes = Some( - ram.available - .saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES), - ); - plan.warnings.push(format!( - "{} of host RAM available, the pinned form needs about {} plus {} free: {} served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", - gib_text(ram.available), - gib_text(footprint), - gib_text(target), - if resident_file { "the experts are" } else { "the archive and the experts are" }, - resident - )); - } - } - } - if facts.os == "windows" - && profile.kar_source == KarSource::File - && profile.expert_source == ExpertSource::Mapped - && profile.memory.resident_budget_gib.is_none() - && ram.total > 0 - { - let workstation = preset == Preset::Workstation; - let desktop = if workstation { - WINDOWS_WORKSTATION_DESKTOP_RESERVE_BYTES - } else { - WINDOWS_DESKTOP_RESERVE_BYTES - }; - let engine_fixed = MAPPED_ENGINE_FIXED_BYTES; - let room = ram.available.saturating_sub(desktop + engine_fixed) / GIB; - plan.resident_budget_gib = Some(room.min(24) as u32); - if workstation { - // the workstation floors (already raised above) stay: the desktop is the point of the preset - plan.mapped_working_set_gib = Some(WINDOWS_WORKSTATION_WORKING_SET_GIB); - } else { - plan.windows_floors_mib = Some((3072, 1536)); - } - plan.warnings.push(format!( - "Windows: the engine may page-lock {room} GiB of experts ({} available, {} left to the desktop, {} for the engine's own pools); close heavy applications for a larger share", - gib_text(ram.available), - gib_text(desktop), - gib_text(engine_fixed) - )); - } - plan -} - -/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win. -pub fn apply( - plan: &ResourcePlan, - profile: &mut Profile, - engine_env: &mut BTreeMap, - budget_overridden: bool, -) { - if !budget_overridden { - profile.gpu_budget_bytes = plan.gpu_budget_bytes; - profile.min_vram_free_mib = plan.min_vram_free_mib; - } - if let Some((soft, hard)) = plan.ram_floors_mib { - // The profile's floors are its dedicated-host values; the workstation preset only raises them. - let raised = - |current: Option, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted))); - profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft); - profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); - } - if let Some(resident) = plan.mapped_resident_gib { - // `kar_source: none` has no archive to map: it stays none (the PLE table is read from the shard either way) - if profile.kar_source != KarSource::None { - profile.kar_source = KarSource::File; - profile.memfd_extents = crate::profile::MemfdExtents::Full; - } - profile.expert_source = ExpertSource::Mapped; - profile.memory.resident_budget_gib.get_or_insert(resident); - profile.memory.lock = Some("off".into()); - profile.memory.heal = Some(false); - profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); - profile.min_ram_available_bytes = profile - .min_ram_available_bytes - .min(MAPPED_MIN_AVAILABLE_BYTES); - } - if let Some(resident) = plan.resident_budget_gib { - profile.memory.resident_budget_gib.get_or_insert(resident); - } - // The prompt chunk borrows its buffers from the expert cache, so a smaller VRAM budget (the workstation preset's, or `--gpu-budget-gib`) - // that cannot hold the profile's chunk would stop the engine from starting: lower the chunk (and the grid with it) to what the budget carries. - if let Some(chunk) = profile.prefill_capacity { - let fits = prefill_capacity_for_budget(profile.gpu_budget_bytes); - if chunk > fits { - profile.prefill_capacity = Some(fits); - if let Some(block) = profile.memory.prefix_cache_block - && block > fits - { - profile.memory.prefix_cache_block = Some(fits); - } - } - } - if let Some((soft, hard)) = plan.windows_floors_mib { - // only ever lowered, and only when the profile asks for more than the Windows values - if profile - .memory - .soft_floor_mib - .is_none_or(|current| current > soft) - { - profile.memory.soft_floor_mib = Some(soft); - profile.memory.hard_floor_mib = Some(hard); - } - } - if let Some(gib) = plan.mapped_working_set_gib - && !profile.engine_env.contains_key(MAPPED_WORKING_SET_ENV) - { - engine_env.insert(MAPPED_WORKING_SET_ENV.to_owned(), gib.to_string()); - } - if let Some(workers) = plan.cpu_workers - && !profile.engine_env.contains_key(CPU_WORKERS_ENV) - { - engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); - } -} - impl ResourcePlan { /// The table `leleka up` prints: what the engine takes and what stays free. pub fn render(&self, facts: &Facts) -> String { @@ -437,528 +158,18 @@ impl ResourcePlan { } #[cfg(test)] -mod tests { - use super::*; - use crate::facts::Memory; - use crate::profile::SPARSE_MEMFD_BYTES_ESTIMATE; +mod tests; - fn gpu(total: u64, free: u64) -> Gpu { - Gpu { - index: 0, - name: "gpu".into(), - driver: "595.1".into(), - vram_total_mib: total, - vram_free_mib: free, - sm: Some(120), - } - } - - fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts { - Facts { - cpu_cores: cores, - memory: Memory { - total: ram_gib * GIB, - available: avail_gib * GIB, - swap_total: 0, - }, - ..Facts::default() - } - } - - /// The full-copy form of the server profile (the shipped profile is `ple_only`; the tests below build that explicitly). - fn server() -> Profile { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memfd_extents = crate::profile::MemfdExtents::Full; - profile - } - fn laptop() -> Profile { - Profile::builtin("rtx3080-16g").unwrap() - } - - #[test] - fn the_prompt_chunk_follows_what_the_gpu_budget_can_lend() { - assert_eq!(prefill_capacity_for_budget(15 * GIB), 8192); - assert_eq!(prefill_capacity_for_budget(14 * GIB), 8192); - assert_eq!(prefill_capacity_for_budget(13 * GIB), 6144); - assert_eq!(prefill_capacity_for_budget(13 * GIB + 900 * MIB), 6144); - assert_eq!(prefill_capacity_for_budget(12 * GIB), 3072); - assert_eq!(prefill_capacity_for_budget(10 * GIB), 2048); - // the laptop profile ships 6144 / 6144: it stays at the workstation preset's 13 GiB budget, goes down on a smaller one and is - // never raised; the server profile (32,819,404,800 B, 30 whole GiB here) keeps its 8192 - let apply_with = |budget_gib: u64| { - let mut profile = laptop(); - let mut env = BTreeMap::new(); - let plan = compute( - &host(16, 48, 36), - Some(&gpu(16384, 16384)), - &profile, - Preset::Dedicated, - ); - profile.gpu_budget_bytes = budget_gib * GIB; - apply(&plan, &mut profile, &mut env, true); - (profile.prefill_capacity, profile.memory.prefix_cache_block) - }; - assert_eq!(apply_with(13), (Some(6144), Some(6144))); - assert_eq!(apply_with(15), (Some(6144), Some(6144))); - assert_eq!(apply_with(12), (Some(3072), Some(3072))); - assert_eq!(apply_with(10), (Some(2048), Some(2048))); - let mut server = server(); - let plan = compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &server, - Preset::Dedicated, - ); - apply(&plan, &mut server, &mut BTreeMap::new(), false); - assert_eq!(server.prefill_capacity, Some(8192)); - } - - #[test] - fn workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known() { - let mut laptop_host = host(16, 48, 36); - laptop_host.cpu_physical_cores = 8; - assert_eq!( - compute(&laptop_host, None, &laptop(), Preset::Workstation).cpu_workers, - Some(7), - "8c/16t: 12 workers would put 5 of them on SMT siblings" - ); - assert_eq!( - compute(&host(16, 48, 36), None, &laptop(), Preset::Workstation).cpu_workers, - Some(12), - "physical cores unknown: unchanged" - ); - let mut server_host = host(32, 121, 100); - server_host.cpu_physical_cores = 16; - assert_eq!( - compute( - &server_host, - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated - ) - .cpu_workers, - Some(15), - "the 16-core server is unchanged" - ); - let mut small = host(2, 16, 8); - small.cpu_physical_cores = 1; - assert_eq!( - compute(&small, None, &laptop(), Preset::Dedicated).cpu_workers, - Some(1) - ); - } - - #[test] - fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() { - let plan = compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated, - ); - assert_eq!(plan.cpu_workers, Some(15)); - assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes); - assert_eq!(plan.ram_floors_mib, None); - assert!(plan.problems.is_empty()); - } - - #[test] - fn workstation_leaves_cores_ram_and_vram_on_the_server() { - let plan = compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &server(), - Preset::Workstation, - ); - assert_eq!( - plan.cpu_workers, - Some(15), - "32 cores - 8 left free = 24, capped at the pool's 15" - ); - assert_eq!( - plan.gpu_budget_bytes, - 29 * GIB, - "32100 MiB free - 2048 MiB, rounded down to GiB" - ); - assert_eq!(plan.ram_floors_mib, Some((16384, 8192))); - assert!(plan.problems.is_empty(), "{:?}", plan.problems); - let mut profile = server(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!(profile.gpu_budget_bytes, 29 * GIB); - assert_eq!(profile.memory.soft_floor_mib, Some(16384)); - assert_eq!(profile.memory.hard_floor_mib, Some(8192)); - assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("15")); - } - - #[test] - fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() { - let plan = compute( - &host(16, 24, 21), - Some(&gpu(16384, 15500)), - &laptop(), - Preset::Workstation, - ); - assert_eq!(plan.cpu_workers, Some(12), "16 threads - 4 left free"); - assert_eq!(plan.ram_floors_mib, Some((8192, 4096))); - assert_eq!(plan.gpu_budget_bytes, 13 * GIB); - assert!(plan.problems.is_empty(), "{:?}", plan.problems); - let small = compute( - &host(8, 24, 21), - Some(&gpu(16384, 15500)), - &laptop(), - Preset::Workstation, - ); - assert_eq!(small.cpu_workers, Some(4)); - } - - #[test] - fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() { - let plan = compute( - &host(16, 24, 21), - Some(&gpu(16384, 9000)), - &laptop(), - Preset::Workstation, - ); - assert!(!plan.problems.is_empty()); - let dedicated = compute( - &host(16, 24, 21), - Some(&gpu(16384, 9000)), - &laptop(), - Preset::Dedicated, - ); - assert!(dedicated.problems.is_empty()); - } - - #[test] - fn explicit_values_win_and_floors_are_only_raised() { - let plan = compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &server(), - Preset::Workstation, - ); - let mut profile = server(); - profile.memory.soft_floor_mib = Some(30000); - profile - .engine_env - .insert(CPU_WORKERS_ENV.into(), "3".into()); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, true); - assert_eq!( - profile.gpu_budget_bytes, - server().gpu_budget_bytes, - "--gpu-budget-gib wins" - ); - assert_eq!(profile.memory.soft_floor_mib, Some(30000)); - assert_eq!( - profile.memory.hard_floor_mib, - Some(8192), - "floors are only ever raised" - ); - assert!(env.is_empty()); - } - - #[test] - fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credited_by_its_own_size() - { - // 80 GiB available at start: the full pinned form (55.3 GB memfd + the engine's 54 GiB) does not fit next to the 4 GiB target and - // the 2 GiB reserve and is sent to the mapped form; with a 16 GB memfd it does - let facts = host(32, 121, 80); - let gpu = gpu(32607, 32100); - let full = compute(&facts, Some(&gpu), &server(), Preset::Dedicated); - assert!(full.mapped_resident_gib.is_some(), "{:?}", full.warnings); - let mut sparse = server(); - sparse.memfd_extents = crate::profile::MemfdExtents::PleOnly; - let plan = compute(&facts, Some(&gpu), &sparse, Preset::Dedicated); - assert_eq!(plan.mapped_resident_gib, None, "{:?}", plan.warnings); - assert_eq!( - plan.ram_expected_free_after_bytes, - Some(80 * GIB - (SPARSE_MEMFD_BYTES_ESTIMATE + ENGINE_FIXED_RESIDENT_BYTES)), - "the footprint is the sparse memfd plus the engine's own memory" - ); - // a resident sparse memfd is credited with its own size, not the archive's - let resident = host(32, 121, 66); - let credited = with_resident_bytes(&resident, sparse.memfd_bytes()); - assert_eq!( - credited.memory.available, - 66 * GIB + SPARSE_MEMFD_BYTES_ESTIMATE - ); - assert_eq!( - with_resident_archive(&resident).memory.available, - 66 * GIB + ARCHIVE_BYTES - ); - // a plan that falls back to the mapped form is a different machine: the sparse switch is dropped with the memfd - let tiny = host(32, 121, 2); - let mut profile = sparse.clone(); - let fallback = compute(&tiny, Some(&gpu), &profile, Preset::Dedicated); - assert!(fallback.mapped_resident_gib.is_some()); - apply(&fallback, &mut profile, &mut BTreeMap::new(), false); - assert_eq!( - (profile.kar_source, profile.memfd_extents), - (KarSource::File, crate::profile::MemfdExtents::Full) - ); - profile.validate().unwrap(); - } - - #[test] - fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() { - // the server with the 51.5 GiB memfd already resident: 121 GiB total, 66 GiB available (what the supervisor sees before the engine starts) - let resident = host(32, 121, 66); - let charged_twice = compute( - &resident, - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated, - ); - assert!( - charged_twice.mapped_resident_gib.is_some(), - "without the correction the pinned form looks impossible" - ); - let corrected = compute( - &with_resident_archive(&resident), - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated, - ); - assert_eq!( - corrected.mapped_resident_gib, None, - "the archive is already paid for: the engine's 54 GiB fit next to the 4 GiB target and the 2 GiB reserve" - ); - assert!(corrected.ram_expected_free_after_bytes.is_some()); - // a host that really lacks the engine's own memory is still sent to the mapped form - let tiny = host(32, 121, 2); - assert!( - compute( - &with_resident_archive(&tiny), - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated - ) - .mapped_resident_gib - .is_some() - ); - // saturating, not wrapping - assert!( - with_resident_archive(&host(1, 1, u64::MAX / GIB)) - .memory - .available - >= u64::MAX / 2 - ); - } - - #[test] - fn the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archive() { - let file = Profile::builtin("rtx5090-32g-file").unwrap(); - assert_eq!( - (file.kar_source, file.expert_source), - (KarSource::File, ExpertSource::Resident) - ); - // 121 GiB host with 100 GiB available and no holder: the 54 GiB of the engine fit; the 55 GB archive is page cache, not a charge - let plan = compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &file, - Preset::Dedicated, - ); - assert_eq!(plan.mapped_resident_gib, None); - assert_eq!(plan.ram_expected_free_after_bytes, Some(46 * GIB)); - // the same host is already too small for the memfd profile once it has to create the archive copy - assert!( - compute( - &host(32, 121, 100), - Some(&gpu(32607, 32100)), - &server(), - Preset::Dedicated - ) - .mapped_resident_gib - .is_some() - ); - // a host that cannot hold the bank is sent to the mapped form, and the warning does not claim the archive moves - let small = host(32, 64, 50); - let plan = compute(&small, Some(&gpu(32607, 32100)), &file, Preset::Dedicated); - assert!(plan.mapped_resident_gib.is_some()); - assert!( - plan.warnings[0].contains("the experts are served from disk") - && !plan.warnings[0].contains("the archive and"), - "{:?}", - plan.warnings - ); - let mut applied = file.clone(); - apply(&plan, &mut applied, &mut BTreeMap::new(), false); - assert_eq!( - (applied.kar_source, applied.expert_source), - (KarSource::File, ExpertSource::Mapped) - ); - applied.validate().unwrap(); - } - - #[test] - fn unknown_core_count_leaves_the_engine_default() { - let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); - assert_eq!(plan.cpu_workers, None); - } - - #[test] - fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() { - // 121 GiB host with 70 GiB available: archive and resident experts (105.5 GiB) do not fit at all - let plan = compute( - &host(32, 121, 70), - Some(&gpu(32607, 32100)), - &server(), - Preset::Workstation, - ); - assert_eq!( - plan.mapped_resident_gib, - Some(44), - "70 - 16 target - 2 reserve - 8 overhead" - ); - assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); - assert!(plan.render(&host(32, 121, 70)).contains("served from disk")); - let mut profile = server(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!(profile.kar_source, KarSource::File); - assert_eq!(profile.expert_source, ExpertSource::Mapped); - assert_eq!(profile.memory.resident_budget_gib, Some(44)); - assert_eq!(profile.memory.lock.as_deref(), Some("off")); - assert!( - profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB - ); - profile.validate().unwrap(); - } - - #[test] - fn the_low_ram_fallback_keeps_a_profile_without_an_archive_without_one() { - let plan = compute( - &host(32, 121, 70), - Some(&gpu(32607, 32100)), - &Profile::builtin("rtx5090-32g-gguf-ple").unwrap(), - Preset::Workstation, - ); - assert!(plan.mapped_resident_gib.is_some(), "{plan:?}"); - let mut profile = Profile::builtin("rtx5090-32g-gguf-ple").unwrap(); - apply(&plan, &mut profile, &mut BTreeMap::new(), false); - assert_eq!(profile.kar_source, KarSource::None); - assert_eq!(profile.expert_source, ExpertSource::Mapped); - profile.validate().unwrap(); - } - - #[test] - fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() { - let plan = compute( - &host(16, 24, 12), - Some(&gpu(16384, 15500)), - &server(), - Preset::Dedicated, - ); - assert_eq!( - plan.mapped_resident_gib, - Some(0), - "12 GiB available is below the 4 GiB target plus 8 GiB overhead" - ); - let ample = compute( - &host(64, 256, 240), - Some(&gpu(32607, 32100)), - &server(), - Preset::Workstation, - ); - assert_eq!(ample.mapped_resident_gib, None); - assert!(ample.warnings.is_empty(), "{:?}", ample.warnings); - } - - #[test] - fn the_windows_file_backed_form_sizes_its_page_locked_experts_from_the_free_ram() { - let mut windows = host(16, 48, 34); - windows.os = "windows".into(); - let plan = compute( - &windows, - Some(&gpu(16384, 16175)), - &laptop(), - Preset::Dedicated, - ); - assert_eq!( - plan.resident_budget_gib, - Some(11), - "34 GiB free - 12 for the desktop - 11 for the engine's pools" - ); - let mut profile = laptop(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!(profile.memory.resident_budget_gib, Some(11)); - assert_eq!( - (profile.memory.soft_floor_mib, profile.memory.hard_floor_mib), - (Some(3072), Some(1536)), - "Windows lowers the Linux floors of the laptop profile" - ); - // an explicit profile value wins, and Linux hosts are left alone - let mut explicit = laptop(); - explicit.memory.resident_budget_gib = Some(16); - assert_eq!( - compute(&windows, None, &explicit, Preset::Dedicated).resident_budget_gib, - None - ); - assert_eq!( - compute(&host(16, 48, 34), None, &laptop(), Preset::Dedicated).resident_budget_gib, - None - ); - // a squeezed machine gets zero, not an underflow - let mut squeezed = host(16, 48, 6); - squeezed.os = "windows".into(); - assert_eq!( - compute(&squeezed, None, &laptop(), Preset::Dedicated).resident_budget_gib, - Some(0) - ); - } - - #[test] - fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors() { - let mut windows = host(16, 48, 34); - windows.os = "windows".into(); - let plan = compute( - &windows, - Some(&gpu(16384, 16175)), - &laptop(), - Preset::Workstation, - ); - assert_eq!( - plan.resident_budget_gib, - Some(5), - "34 GiB free - 18 for the agent, IDE and browser - 11 for the engine's pools" - ); - assert_eq!( - plan.windows_floors_mib, None, - "the workstation floors are not lowered to the dedicated Windows values" - ); - assert_eq!(plan.mapped_working_set_gib, Some(8)); - let mut profile = laptop(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!( - profile.memory.soft_floor_mib, - Some(8 * 1024), - "Windows workstation keeps 8 GiB available (12 GiB left the prefix cache no budget)" - ); - assert_eq!(profile.memory.hard_floor_mib, Some(4 * 1024)); - assert_eq!( - env.get(MAPPED_WORKING_SET_ENV).map(String::as_str), - Some("8") - ); - // the dedicated preset on the same host is unchanged - let dedicated = compute(&windows, None, &laptop(), Preset::Dedicated); - assert_eq!( - ( - dedicated.resident_budget_gib, - dedicated.mapped_working_set_gib - ), - (Some(11), None) - ); - } - - #[test] - fn presets_parse_and_default_to_dedicated() { - assert_eq!(Preset::default(), Preset::Dedicated); - assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation); - assert!(Preset::parse("x").is_err()); - } -} +mod sizing; +#[allow(unused_imports)] +pub use sizing::apply; +#[allow(unused_imports)] +pub use sizing::compute; +#[allow(unused_imports)] +pub use sizing::prefill_capacity_for_budget; +#[allow(unused_imports)] +pub use sizing::with_resident_archive; +#[allow(unused_imports)] +pub use sizing::with_resident_bytes; +#[allow(unused_imports)] +pub use sizing::workstation_ram_target; diff --git a/crates/deploy/src/resources/sizing.rs b/crates/deploy/src/resources/sizing.rs new file mode 100644 index 00000000..4c3c5d2e --- /dev/null +++ b/crates/deploy/src/resources/sizing.rs @@ -0,0 +1,283 @@ +//! Sizing the resource plan from the host facts and applying a preset to a profile. + +#[allow(unused_imports)] +use super::*; + +/// The largest prompt chunk an expert cache of this GPU budget can lend to the prompt path (measured on the 3080 laptop with the pinned Qwen3.8 +/// IQ3_S pack: a budget of 13 GiB holds 2,234 expert slots of 1.97 MiB, about 520 more per GiB; the loan of a chunk plus the 128-slot floor is +/// 1,282 slots at 2048, 1,497 at 3072, 1,713 at 4096, 2,144 at 6144 and about 2,575 at 8192; a chunk that does not fit stops the engine from opening). +/// Whole GiB, rounded down, with the margin the 1-GiB steps leave: 14+ GiB carry 8192, 13 carry 6144, 12 carry 3072, less keeps 2048. +pub fn prefill_capacity_for_budget(gpu_budget_bytes: u64) -> u32 { + match gpu_budget_bytes / GIB { + 14.. => 8192, + 13 => 6144, + 12 => 3072, + _ => 2048, + } +} + +/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM. +pub fn workstation_ram_target(total: u64) -> u64 { + if total >= 64 * GIB { + 16 * GIB + } else if total >= 32 * GIB { + 12 * GIB + } else { + 8 * GIB + } +} + +/// The host as the planner should see it when the sealed archive memfd is already resident (an inherited `--kar-fd`, or the +/// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the +/// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not. +pub fn with_resident_archive(facts: &Facts) -> Facts { + with_resident_bytes(facts, ARCHIVE_BYTES) +} + +/// [`with_resident_archive`] for a memfd of `bytes` (a `ple_only` memfd holds about 16 GB, not 55). +pub fn with_resident_bytes(facts: &Facts, bytes: u64) -> Facts { + let mut facts = facts.clone(); + facts.memory.available = facts.memory.available.saturating_add(bytes); + facts +} + +pub fn compute( + facts: &Facts, + gpu: Option<&Gpu>, + profile: &Profile, + preset: Preset, +) -> ResourcePlan { + let mut plan = ResourcePlan { + preset, + cores: facts.cpu_cores, + cpu_workers: None, + gpu_budget_bytes: profile.gpu_budget_bytes, + min_vram_free_mib: profile.min_vram_free_mib, + vram_free_after_mib: None, + ram_floors_mib: None, + ram_expected_free_after_bytes: None, + mapped_resident_gib: None, + resident_budget_gib: None, + windows_floors_mib: None, + mapped_working_set_gib: None, + problems: Vec::new(), + warnings: Vec::new(), + }; + + // CPU + if facts.cpu_cores > 0 { + let cores = facts.cpu_cores; + let leave = match preset { + Preset::Dedicated => 2, + Preset::Workstation if cores <= 16 => 4, + Preset::Workstation => 8, + }; + let mut workers = cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS); + // The pool's workers spin while they wait: one without a core of its own steals cycles from one that has it, so a + // bigger count is slower, not just useless (docs/upstream-port-plan.md row 2.3). Where the platform reports the + // physical cores (Windows), the count never exceeds every physical core but the host thread's: 7 on the 8-core + // laptop instead of 12 (the workstation preset's logical-core count); the 16-core server is unchanged (15). + if facts.cpu_physical_cores > 0 { + workers = workers.min(facts.cpu_physical_cores.saturating_sub(1).max(1)); + } + plan.cpu_workers = Some(workers); + if preset == Preset::Workstation && cores < leave + 1 { + plan.warnings.push(format!( + "only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)" + )); + } + } + + // VRAM + if let Some(gpu) = gpu { + let budget_mib = profile.gpu_budget_bytes / MIB; + if preset == Preset::Workstation { + let cap_mib = (gpu + .vram_free_mib + .saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) + / 1024) + * 1024; + if cap_mib < budget_mib { + plan.gpu_budget_bytes = cap_mib * MIB; + let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib); + plan.min_vram_free_mib = Some(need); + // Below half of the profile budget the expert tier and KV window shrink past what was measured. + if cap_mib * 2 < budget_mib { + plan.problems.push(format!( + "the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)", + WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib + )); + } + } + } + let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0)); + plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used)); + } + + // Host RAM + let ram = &facts.memory; + if ram.total > 0 { + let target = match preset { + // Windows reclaims standby and trimmed mapped pages on its own (the engine trims its working set under pressure), so a + // free-RAM target above 8 GiB only starves the prefix cache: live 48 GB run 2026-10-26, 12 GiB left it a budget of 0. + Preset::Workstation if facts.os == "windows" => { + workstation_ram_target(ram.total).min(WINDOWS_WORKSTATION_RAM_TARGET_BYTES) + } + Preset::Workstation => workstation_ram_target(ram.total), + Preset::Dedicated => profile + .memory + .soft_floor_mib + .map_or(4 * GIB, |mib| mib * MIB), + }; + if preset == Preset::Workstation { + let soft = target / MIB; + plan.ram_floors_mib = Some((soft, soft / 2)); + } + // The sealed memfd holds the whole archive; a file-backed archive with a resident expert bank (rtx5090-32g-file) holds only the bank and + // the engine's pins, its archive pages are page cache that the kernel gives back. The mapped file form (laptop) is already the low tier. + // `kar_source: none` has no archive at all (the PLE table is read from the shard through the page cache): the same footprint. + let resident_file = matches!(profile.kar_source, KarSource::File | KarSource::None) + && profile.expert_source == ExpertSource::Resident; + if profile.kar_source == KarSource::Memfd || resident_file { + let engine = if profile.expert_source == ExpertSource::Resident { + ENGINE_FIXED_RESIDENT_BYTES + } else { + ENGINE_EXTRA_BYTES + }; + let footprint = if resident_file { + engine + } else { + profile.memfd_bytes() + engine + }; + let after = ram.available.saturating_sub(footprint); + let reserve = profile + .memory + .reserve_mib + .map_or(DEFAULT_RESERVE_BYTES, |mib| mib * MIB); + if after >= target + reserve { + plan.ram_expected_free_after_bytes = Some(after); + } else { + // Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing. + let resident = ram + .available + .saturating_sub(target + reserve + MAPPED_OVERHEAD_BYTES) + / GIB; + let resident = resident.min(RESIDENT_BANK_GIB) as u32; + plan.mapped_resident_gib = Some(resident); + plan.ram_expected_free_after_bytes = Some( + ram.available + .saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES), + ); + plan.warnings.push(format!( + "{} of host RAM available, the pinned form needs about {} plus {} free: {} served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", + gib_text(ram.available), + gib_text(footprint), + gib_text(target), + if resident_file { "the experts are" } else { "the archive and the experts are" }, + resident + )); + } + } + } + if facts.os == "windows" + && profile.kar_source == KarSource::File + && profile.expert_source == ExpertSource::Mapped + && profile.memory.resident_budget_gib.is_none() + && ram.total > 0 + { + let workstation = preset == Preset::Workstation; + let desktop = if workstation { + WINDOWS_WORKSTATION_DESKTOP_RESERVE_BYTES + } else { + WINDOWS_DESKTOP_RESERVE_BYTES + }; + let engine_fixed = MAPPED_ENGINE_FIXED_BYTES; + let room = ram.available.saturating_sub(desktop + engine_fixed) / GIB; + plan.resident_budget_gib = Some(room.min(24) as u32); + if workstation { + // the workstation floors (already raised above) stay: the desktop is the point of the preset + plan.mapped_working_set_gib = Some(WINDOWS_WORKSTATION_WORKING_SET_GIB); + } else { + plan.windows_floors_mib = Some((3072, 1536)); + } + plan.warnings.push(format!( + "Windows: the engine may page-lock {room} GiB of experts ({} available, {} left to the desktop, {} for the engine's own pools); close heavy applications for a larger share", + gib_text(ram.available), + gib_text(desktop), + gib_text(engine_fixed) + )); + } + plan +} + +/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win. +pub fn apply( + plan: &ResourcePlan, + profile: &mut Profile, + engine_env: &mut BTreeMap, + budget_overridden: bool, +) { + if !budget_overridden { + profile.gpu_budget_bytes = plan.gpu_budget_bytes; + profile.min_vram_free_mib = plan.min_vram_free_mib; + } + if let Some((soft, hard)) = plan.ram_floors_mib { + // The profile's floors are its dedicated-host values; the workstation preset only raises them. + let raised = + |current: Option, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted))); + profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft); + profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); + } + if let Some(resident) = plan.mapped_resident_gib { + // `kar_source: none` has no archive to map: it stays none (the PLE table is read from the shard either way) + if profile.kar_source != KarSource::None { + profile.kar_source = KarSource::File; + profile.memfd_extents = crate::profile::MemfdExtents::Full; + } + profile.expert_source = ExpertSource::Mapped; + profile.memory.resident_budget_gib.get_or_insert(resident); + profile.memory.lock = Some("off".into()); + profile.memory.heal = Some(false); + profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); + profile.min_ram_available_bytes = profile + .min_ram_available_bytes + .min(MAPPED_MIN_AVAILABLE_BYTES); + } + if let Some(resident) = plan.resident_budget_gib { + profile.memory.resident_budget_gib.get_or_insert(resident); + } + // The prompt chunk borrows its buffers from the expert cache, so a smaller VRAM budget (the workstation preset's, or `--gpu-budget-gib`) + // that cannot hold the profile's chunk would stop the engine from starting: lower the chunk (and the grid with it) to what the budget carries. + if let Some(chunk) = profile.prefill_capacity { + let fits = prefill_capacity_for_budget(profile.gpu_budget_bytes); + if chunk > fits { + profile.prefill_capacity = Some(fits); + if let Some(block) = profile.memory.prefix_cache_block + && block > fits + { + profile.memory.prefix_cache_block = Some(fits); + } + } + } + if let Some((soft, hard)) = plan.windows_floors_mib { + // only ever lowered, and only when the profile asks for more than the Windows values + if profile + .memory + .soft_floor_mib + .is_none_or(|current| current > soft) + { + profile.memory.soft_floor_mib = Some(soft); + profile.memory.hard_floor_mib = Some(hard); + } + } + if let Some(gib) = plan.mapped_working_set_gib + && !profile.engine_env.contains_key(MAPPED_WORKING_SET_ENV) + { + engine_env.insert(MAPPED_WORKING_SET_ENV.to_owned(), gib.to_string()); + } + if let Some(workers) = plan.cpu_workers + && !profile.engine_env.contains_key(CPU_WORKERS_ENV) + { + engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); + } +} diff --git a/crates/deploy/src/resources/tests.rs b/crates/deploy/src/resources/tests.rs new file mode 100644 index 00000000..81e22eb4 --- /dev/null +++ b/crates/deploy/src/resources/tests.rs @@ -0,0 +1,42 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::facts::Memory; +use crate::profile::SPARSE_MEMFD_BYTES_ESTIMATE; + +fn gpu(total: u64, free: u64) -> Gpu { + Gpu { + index: 0, + name: "gpu".into(), + driver: "595.1".into(), + vram_total_mib: total, + vram_free_mib: free, + sm: Some(120), + } +} + +fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts { + Facts { + cpu_cores: cores, + memory: Memory { + total: ram_gib * GIB, + available: avail_gib * GIB, + swap_total: 0, + }, + ..Facts::default() + } +} + +/// The full-copy form of the server profile (the shipped profile is `ple_only`; the tests below build that explicitly). +fn server() -> Profile { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; + profile +} +fn laptop() -> Profile { + Profile::builtin("rtx3080-16g").unwrap() +} + +mod presets_and_workers; +mod ram_fit; +mod windows_presets; diff --git a/crates/deploy/src/resources/tests/presets_and_workers.rs b/crates/deploy/src/resources/tests/presets_and_workers.rs new file mode 100644 index 00000000..ff13b68b --- /dev/null +++ b/crates/deploy/src/resources/tests/presets_and_workers.rs @@ -0,0 +1,201 @@ +//! Presets, the prompt chunk and the worker count that a host and a preset allow. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_prompt_chunk_follows_what_the_gpu_budget_can_lend() { + assert_eq!(prefill_capacity_for_budget(15 * GIB), 8192); + assert_eq!(prefill_capacity_for_budget(14 * GIB), 8192); + assert_eq!(prefill_capacity_for_budget(13 * GIB), 6144); + assert_eq!(prefill_capacity_for_budget(13 * GIB + 900 * MIB), 6144); + assert_eq!(prefill_capacity_for_budget(12 * GIB), 3072); + assert_eq!(prefill_capacity_for_budget(10 * GIB), 2048); + // the laptop profile ships 6144 / 6144: it stays at the workstation preset's 13 GiB budget, goes down on a smaller one and is + // never raised; the server profile (32,819,404,800 B, 30 whole GiB here) keeps its 8192 + let apply_with = |budget_gib: u64| { + let mut profile = laptop(); + let mut env = BTreeMap::new(); + let plan = compute( + &host(16, 48, 36), + Some(&gpu(16384, 16384)), + &profile, + Preset::Dedicated, + ); + profile.gpu_budget_bytes = budget_gib * GIB; + apply(&plan, &mut profile, &mut env, true); + (profile.prefill_capacity, profile.memory.prefix_cache_block) + }; + assert_eq!(apply_with(13), (Some(6144), Some(6144))); + assert_eq!(apply_with(15), (Some(6144), Some(6144))); + assert_eq!(apply_with(12), (Some(3072), Some(3072))); + assert_eq!(apply_with(10), (Some(2048), Some(2048))); + let mut server = server(); + let plan = compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &server, + Preset::Dedicated, + ); + apply(&plan, &mut server, &mut BTreeMap::new(), false); + assert_eq!(server.prefill_capacity, Some(8192)); +} + +#[test] +fn workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known() { + let mut laptop_host = host(16, 48, 36); + laptop_host.cpu_physical_cores = 8; + assert_eq!( + compute(&laptop_host, None, &laptop(), Preset::Workstation).cpu_workers, + Some(7), + "8c/16t: 12 workers would put 5 of them on SMT siblings" + ); + assert_eq!( + compute(&host(16, 48, 36), None, &laptop(), Preset::Workstation).cpu_workers, + Some(12), + "physical cores unknown: unchanged" + ); + let mut server_host = host(32, 121, 100); + server_host.cpu_physical_cores = 16; + assert_eq!( + compute( + &server_host, + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated + ) + .cpu_workers, + Some(15), + "the 16-core server is unchanged" + ); + let mut small = host(2, 16, 8); + small.cpu_physical_cores = 1; + assert_eq!( + compute(&small, None, &laptop(), Preset::Dedicated).cpu_workers, + Some(1) + ); +} + +#[test] +fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() { + let plan = compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated, + ); + assert_eq!(plan.cpu_workers, Some(15)); + assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes); + assert_eq!(plan.ram_floors_mib, None); + assert!(plan.problems.is_empty()); +} + +#[test] +fn workstation_leaves_cores_ram_and_vram_on_the_server() { + let plan = compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &server(), + Preset::Workstation, + ); + assert_eq!( + plan.cpu_workers, + Some(15), + "32 cores - 8 left free = 24, capped at the pool's 15" + ); + assert_eq!( + plan.gpu_budget_bytes, + 29 * GIB, + "32100 MiB free - 2048 MiB, rounded down to GiB" + ); + assert_eq!(plan.ram_floors_mib, Some((16384, 8192))); + assert!(plan.problems.is_empty(), "{:?}", plan.problems); + let mut profile = server(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!(profile.gpu_budget_bytes, 29 * GIB); + assert_eq!(profile.memory.soft_floor_mib, Some(16384)); + assert_eq!(profile.memory.hard_floor_mib, Some(8192)); + assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("15")); +} + +#[test] +fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() { + let plan = compute( + &host(16, 24, 21), + Some(&gpu(16384, 15500)), + &laptop(), + Preset::Workstation, + ); + assert_eq!(plan.cpu_workers, Some(12), "16 threads - 4 left free"); + assert_eq!(plan.ram_floors_mib, Some((8192, 4096))); + assert_eq!(plan.gpu_budget_bytes, 13 * GIB); + assert!(plan.problems.is_empty(), "{:?}", plan.problems); + let small = compute( + &host(8, 24, 21), + Some(&gpu(16384, 15500)), + &laptop(), + Preset::Workstation, + ); + assert_eq!(small.cpu_workers, Some(4)); +} + +#[test] +fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() { + let plan = compute( + &host(16, 24, 21), + Some(&gpu(16384, 9000)), + &laptop(), + Preset::Workstation, + ); + assert!(!plan.problems.is_empty()); + let dedicated = compute( + &host(16, 24, 21), + Some(&gpu(16384, 9000)), + &laptop(), + Preset::Dedicated, + ); + assert!(dedicated.problems.is_empty()); +} + +#[test] +fn explicit_values_win_and_floors_are_only_raised() { + let plan = compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &server(), + Preset::Workstation, + ); + let mut profile = server(); + profile.memory.soft_floor_mib = Some(30000); + profile + .engine_env + .insert(CPU_WORKERS_ENV.into(), "3".into()); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, true); + assert_eq!( + profile.gpu_budget_bytes, + server().gpu_budget_bytes, + "--gpu-budget-gib wins" + ); + assert_eq!(profile.memory.soft_floor_mib, Some(30000)); + assert_eq!( + profile.memory.hard_floor_mib, + Some(8192), + "floors are only ever raised" + ); + assert!(env.is_empty()); +} + +#[test] +fn unknown_core_count_leaves_the_engine_default() { + let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); + assert_eq!(plan.cpu_workers, None); +} + +#[test] +fn presets_parse_and_default_to_dedicated() { + assert_eq!(Preset::default(), Preset::Dedicated); + assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation); + assert!(Preset::parse("x").is_err()); +} diff --git a/crates/deploy/src/resources/tests/ram_fit.rs b/crates/deploy/src/resources/tests/ram_fit.rs new file mode 100644 index 00000000..281f5778 --- /dev/null +++ b/crates/deploy/src/resources/tests/ram_fit.rs @@ -0,0 +1,204 @@ +//! How the archive form is charged to the RAM footprint and what a small or low-RAM host falls back to. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credited_by_its_own_size() + { + // 80 GiB available at start: the full pinned form (55.3 GB memfd + the engine's 54 GiB) does not fit next to the 4 GiB target and + // the 2 GiB reserve and is sent to the mapped form; with a 16 GB memfd it does + let facts = host(32, 121, 80); + let gpu = gpu(32607, 32100); + let full = compute(&facts, Some(&gpu), &server(), Preset::Dedicated); + assert!(full.mapped_resident_gib.is_some(), "{:?}", full.warnings); + let mut sparse = server(); + sparse.memfd_extents = crate::profile::MemfdExtents::PleOnly; + let plan = compute(&facts, Some(&gpu), &sparse, Preset::Dedicated); + assert_eq!(plan.mapped_resident_gib, None, "{:?}", plan.warnings); + assert_eq!( + plan.ram_expected_free_after_bytes, + Some(80 * GIB - (SPARSE_MEMFD_BYTES_ESTIMATE + ENGINE_FIXED_RESIDENT_BYTES)), + "the footprint is the sparse memfd plus the engine's own memory" + ); + // a resident sparse memfd is credited with its own size, not the archive's + let resident = host(32, 121, 66); + let credited = with_resident_bytes(&resident, sparse.memfd_bytes()); + assert_eq!( + credited.memory.available, + 66 * GIB + SPARSE_MEMFD_BYTES_ESTIMATE + ); + assert_eq!( + with_resident_archive(&resident).memory.available, + 66 * GIB + ARCHIVE_BYTES + ); + // a plan that falls back to the mapped form is a different machine: the sparse switch is dropped with the memfd + let tiny = host(32, 121, 2); + let mut profile = sparse.clone(); + let fallback = compute(&tiny, Some(&gpu), &profile, Preset::Dedicated); + assert!(fallback.mapped_resident_gib.is_some()); + apply(&fallback, &mut profile, &mut BTreeMap::new(), false); + assert_eq!( + (profile.kar_source, profile.memfd_extents), + (KarSource::File, crate::profile::MemfdExtents::Full) + ); + profile.validate().unwrap(); +} + +#[test] +fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() { + // the server with the 51.5 GiB memfd already resident: 121 GiB total, 66 GiB available (what the supervisor sees before the engine starts) + let resident = host(32, 121, 66); + let charged_twice = compute( + &resident, + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated, + ); + assert!( + charged_twice.mapped_resident_gib.is_some(), + "without the correction the pinned form looks impossible" + ); + let corrected = compute( + &with_resident_archive(&resident), + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated, + ); + assert_eq!( + corrected.mapped_resident_gib, None, + "the archive is already paid for: the engine's 54 GiB fit next to the 4 GiB target and the 2 GiB reserve" + ); + assert!(corrected.ram_expected_free_after_bytes.is_some()); + // a host that really lacks the engine's own memory is still sent to the mapped form + let tiny = host(32, 121, 2); + assert!( + compute( + &with_resident_archive(&tiny), + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated + ) + .mapped_resident_gib + .is_some() + ); + // saturating, not wrapping + assert!( + with_resident_archive(&host(1, 1, u64::MAX / GIB)) + .memory + .available + >= u64::MAX / 2 + ); +} + +#[test] +fn the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archive() { + let file = Profile::builtin("rtx5090-32g-file").unwrap(); + assert_eq!( + (file.kar_source, file.expert_source), + (KarSource::File, ExpertSource::Resident) + ); + // 121 GiB host with 100 GiB available and no holder: the 54 GiB of the engine fit; the 55 GB archive is page cache, not a charge + let plan = compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &file, + Preset::Dedicated, + ); + assert_eq!(plan.mapped_resident_gib, None); + assert_eq!(plan.ram_expected_free_after_bytes, Some(46 * GIB)); + // the same host is already too small for the memfd profile once it has to create the archive copy + assert!( + compute( + &host(32, 121, 100), + Some(&gpu(32607, 32100)), + &server(), + Preset::Dedicated + ) + .mapped_resident_gib + .is_some() + ); + // a host that cannot hold the bank is sent to the mapped form, and the warning does not claim the archive moves + let small = host(32, 64, 50); + let plan = compute(&small, Some(&gpu(32607, 32100)), &file, Preset::Dedicated); + assert!(plan.mapped_resident_gib.is_some()); + assert!( + plan.warnings[0].contains("the experts are served from disk") + && !plan.warnings[0].contains("the archive and"), + "{:?}", + plan.warnings + ); + let mut applied = file.clone(); + apply(&plan, &mut applied, &mut BTreeMap::new(), false); + assert_eq!( + (applied.kar_source, applied.expert_source), + (KarSource::File, ExpertSource::Mapped) + ); + applied.validate().unwrap(); +} + +#[test] +fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() { + // 121 GiB host with 70 GiB available: archive and resident experts (105.5 GiB) do not fit at all + let plan = compute( + &host(32, 121, 70), + Some(&gpu(32607, 32100)), + &server(), + Preset::Workstation, + ); + assert_eq!( + plan.mapped_resident_gib, + Some(44), + "70 - 16 target - 2 reserve - 8 overhead" + ); + assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); + assert!(plan.render(&host(32, 121, 70)).contains("served from disk")); + let mut profile = server(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!(profile.kar_source, KarSource::File); + assert_eq!(profile.expert_source, ExpertSource::Mapped); + assert_eq!(profile.memory.resident_budget_gib, Some(44)); + assert_eq!(profile.memory.lock.as_deref(), Some("off")); + assert!(profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB); + profile.validate().unwrap(); +} + +#[test] +fn the_low_ram_fallback_keeps_a_profile_without_an_archive_without_one() { + let plan = compute( + &host(32, 121, 70), + Some(&gpu(32607, 32100)), + &Profile::builtin("rtx5090-32g-gguf-ple").unwrap(), + Preset::Workstation, + ); + assert!(plan.mapped_resident_gib.is_some(), "{plan:?}"); + let mut profile = Profile::builtin("rtx5090-32g-gguf-ple").unwrap(); + apply(&plan, &mut profile, &mut BTreeMap::new(), false); + assert_eq!(profile.kar_source, KarSource::None); + assert_eq!(profile.expert_source, ExpertSource::Mapped); + profile.validate().unwrap(); +} + +#[test] +fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() { + let plan = compute( + &host(16, 24, 12), + Some(&gpu(16384, 15500)), + &server(), + Preset::Dedicated, + ); + assert_eq!( + plan.mapped_resident_gib, + Some(0), + "12 GiB available is below the 4 GiB target plus 8 GiB overhead" + ); + let ample = compute( + &host(64, 256, 240), + Some(&gpu(32607, 32100)), + &server(), + Preset::Workstation, + ); + assert_eq!(ample.mapped_resident_gib, None); + assert!(ample.warnings.is_empty(), "{:?}", ample.warnings); +} diff --git a/crates/deploy/src/resources/tests/windows_presets.rs b/crates/deploy/src/resources/tests/windows_presets.rs new file mode 100644 index 00000000..96ce2293 --- /dev/null +++ b/crates/deploy/src/resources/tests/windows_presets.rs @@ -0,0 +1,92 @@ +//! The Windows forms: page-locked experts from the free RAM and the workstation preset. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_windows_file_backed_form_sizes_its_page_locked_experts_from_the_free_ram() { + let mut windows = host(16, 48, 34); + windows.os = "windows".into(); + let plan = compute( + &windows, + Some(&gpu(16384, 16175)), + &laptop(), + Preset::Dedicated, + ); + assert_eq!( + plan.resident_budget_gib, + Some(11), + "34 GiB free - 12 for the desktop - 11 for the engine's pools" + ); + let mut profile = laptop(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!(profile.memory.resident_budget_gib, Some(11)); + assert_eq!( + (profile.memory.soft_floor_mib, profile.memory.hard_floor_mib), + (Some(3072), Some(1536)), + "Windows lowers the Linux floors of the laptop profile" + ); + // an explicit profile value wins, and Linux hosts are left alone + let mut explicit = laptop(); + explicit.memory.resident_budget_gib = Some(16); + assert_eq!( + compute(&windows, None, &explicit, Preset::Dedicated).resident_budget_gib, + None + ); + assert_eq!( + compute(&host(16, 48, 34), None, &laptop(), Preset::Dedicated).resident_budget_gib, + None + ); + // a squeezed machine gets zero, not an underflow + let mut squeezed = host(16, 48, 6); + squeezed.os = "windows".into(); + assert_eq!( + compute(&squeezed, None, &laptop(), Preset::Dedicated).resident_budget_gib, + Some(0) + ); +} + +#[test] +fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors() { + let mut windows = host(16, 48, 34); + windows.os = "windows".into(); + let plan = compute( + &windows, + Some(&gpu(16384, 16175)), + &laptop(), + Preset::Workstation, + ); + assert_eq!( + plan.resident_budget_gib, + Some(5), + "34 GiB free - 18 for the agent, IDE and browser - 11 for the engine's pools" + ); + assert_eq!( + plan.windows_floors_mib, None, + "the workstation floors are not lowered to the dedicated Windows values" + ); + assert_eq!(plan.mapped_working_set_gib, Some(8)); + let mut profile = laptop(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!( + profile.memory.soft_floor_mib, + Some(8 * 1024), + "Windows workstation keeps 8 GiB available (12 GiB left the prefix cache no budget)" + ); + assert_eq!(profile.memory.hard_floor_mib, Some(4 * 1024)); + assert_eq!( + env.get(MAPPED_WORKING_SET_ENV).map(String::as_str), + Some("8") + ); + // the dedicated preset on the same host is unchanged + let dedicated = compute(&windows, None, &laptop(), Preset::Dedicated); + assert_eq!( + ( + dedicated.resident_budget_gib, + dedicated.mapped_working_set_gib + ), + (Some(11), None) + ); +} diff --git a/crates/deploy/src/sealed.rs b/crates/deploy/src/sealed.rs index d9c5c125..e6a2ca7b 100644 --- a/crates/deploy/src/sealed.rs +++ b/crates/deploy/src/sealed.rs @@ -22,571 +22,16 @@ pub struct SealExecPlan { pub const PLACEHOLDER: &str = "{FD}"; #[cfg(target_os = "linux")] -mod linux { - use super::substitute; - use leleka_model_format::{kar::Extent, verify_stamp::FileIdentity}; - use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; - use std::{ - convert::Infallible, - fs::File, - os::{ - fd::{AsFd, IntoRawFd}, - unix::{fs::FileExt, process::CommandExt}, - }, - path::Path, - process::Command, - sync::{ - Mutex, - atomic::{AtomicBool, AtomicU64, Ordering}, - }, - }; - - pub const SEALS: SealFlags = SealFlags::from_bits_truncate( - SealFlags::WRITE.bits() - | SealFlags::GROW.bits() - | SealFlags::SHRINK.bits() - | SealFlags::SEAL.bits(), - ); - /// Block size the tests use to cover several blocks and a ragged tail. - #[cfg(test)] - const COPY_CHUNK: usize = 32 << 20; - - /// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets - /// (copied, total) about every 4 GiB. - pub fn seal_file( - path: &Path, - expect_bytes: Option, - progress: &mut dyn FnMut(u64, u64), - ) -> Result { - seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file) - } - - /// As [`seal_file`], returning the identity of the source file when it is a stable one. The identity is taken from the - /// opened file before the first byte and again after the last; a source that changed while it was copied is - /// refused, so the identity describes exactly the bytes that are in the memfd. - pub fn seal_file_with_identity( - path: &Path, - expect_bytes: Option, - progress: &mut dyn FnMut(u64, u64), - ) -> Result<(File, Option), String> { - seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity)) - } - - /// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log. - pub fn seal_file_report( - path: &Path, - expect_bytes: Option, - progress: &mut dyn FnMut(u64, u64), - ) -> Result< - ( - File, - Option, - leleka_model_format::bulk_read::Report, - ), - String, - > { - seal_ranges(path, expect_bytes, None, progress) - } - - /// A **sparse** sealed memfd: the final length of the archive, but only `extents` are copied; every byte outside them is - /// a hole (no page is allocated, a read returns zeros). File offsets are identical to the archive's, so a reader needs no - /// change. The extents must be sorted, disjoint, page-aligned at the start and inside the archive. The memfd is sealed - /// like the full one, but it is NOT the archive: the engine verifies it against the pinned digest of the extents - /// (`VerifiedKarPleArtifact::verify_sparse`), never against the archive's SHA-256, and the identity returned here must not be - /// used to record a verification stamp of the archive. - pub fn seal_extents( - path: &Path, - expect_bytes: Option, - extents: &[Extent], - progress: &mut dyn FnMut(u64, u64), - ) -> Result<(File, Option), String> { - seal_extents_report(path, expect_bytes, extents, progress) - .map(|(file, identity, _)| (file, identity)) - } - - /// As [`seal_extents`], also returning how the file was read. - pub fn seal_extents_report( - path: &Path, - expect_bytes: Option, - extents: &[Extent], - progress: &mut dyn FnMut(u64, u64), - ) -> Result< - ( - File, - Option, - leleka_model_format::bulk_read::Report, - ), - String, - > { - seal_ranges(path, expect_bytes, Some(extents), progress) - } - - fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> { - let mut previous_end = 0; - for (i, e) in extents.iter().enumerate() { - if e.len == 0 - || e.offset % leleka_model_format::kar::EXTENT_ALIGN != 0 - || e.offset < previous_end - || e.offset.checked_add(e.len).is_none_or(|end| end > total) - { - return Err(format!( - "extent {i} ({}+{}) is empty, unaligned, out of order or outside the {total}-byte archive", - e.offset, e.len - )); - } - previous_end = e.end(); - } - Ok(()) - } - - fn seal_ranges( - path: &Path, - expect_bytes: Option, - extents: Option<&[Extent]>, - progress: &mut dyn FnMut(u64, u64), - ) -> Result< - ( - File, - Option, - leleka_model_format::bulk_read::Report, - ), - String, - > { - let source = - File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; - let metadata = source - .metadata() - .map_err(|e| format!("cannot inspect the archive: {e}"))?; - if !metadata.is_file() { - return Err("the archive must be a regular file".into()); - } - if let Some(expected) = expect_bytes - && metadata.len() != expected - { - return Err(format!( - "the archive has {} bytes, expected {expected}", - metadata.len() - )); - } - let identity_before = FileIdentity::of(&metadata); - let total = metadata.len(); - let whole = [Extent::new(0, total)]; - let ranges: &[Extent] = match extents { - Some(extents) => { - check_extents(extents, total)?; - extents - } - None => &whole, - }; - let want: u64 = ranges.iter().map(|r| r.len).sum(); - let fd = memfd_create( - "leleka-sealed-archive", - MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, - ) - .map_err(|e| format!("memfd_create failed: {e}"))?; - let memory = File::from(fd); - let report: Mutex> = Mutex::new(None); - // The final size first (before the GROW seal exists), so that workers write disjoint ranges. - memory - .set_len(total) - .map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?; - // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue - // instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the - // memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else). - let plan = leleka_model_format::bulk_read::Plan::from_env(); - let copied = AtomicU64::new(0); - let finished = AtomicBool::new(false); - let failure: Mutex> = Mutex::new(None); - std::thread::scope(|scope| { - scope.spawn(|| { - // Set on every exit, a panic included, so that the progress loop below ends. - struct Finished<'a>(&'a AtomicBool); - impl Drop for Finished<'_> { - fn drop(&mut self) { - self.0.store(true, Ordering::Release); - } - } - let _finished = Finished(&finished); - let mut strategy = None; - let mut elapsed = std::time::Duration::ZERO; - for range in ranges { - let outcome = leleka_model_format::bulk_read::for_each_chunk( - &source, - range.offset, - range.len, - plan, - |offset, data| { - memory.write_all_at(data, offset).map_err(|e| { - std::io::Error::other(format!( - "write to memfd failed (out of memory?): {e}" - )) - })?; - copied.fetch_add(data.len() as u64, Ordering::Relaxed); - Ok(()) - }, - ); - match outcome { - Ok(done) => { - strategy = Some(done.strategy); - elapsed += done.elapsed; - } - Err(e) => { - if let Ok(mut f) = failure.lock() { - f.get_or_insert(format!("read failed: {e}")); - } - return; - } - } - } - // No extents at all is a valid (empty) sparse copy: nothing was read. - let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain); - if let Ok(mut slot) = report.lock() { - *slot = Some(leleka_model_format::bulk_read::Report { - strategy, - bytes: want, - elapsed, - }); - } - }); - let mut reported = 0u64; - while !finished.load(Ordering::Acquire) { - std::thread::sleep(std::time::Duration::from_millis(100)); - let now = copied.load(Ordering::Relaxed); - if now - reported >= 4 << 30 { - reported = now; - progress(now, want); - } - } - }); - if let Some(message) = failure.into_inner().ok().flatten() { - return Err(message); - } - if copied.load(Ordering::Relaxed) != want { - return Err("the archive changed while it was being copied".into()); - } - let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m)); - if identity_before != identity_after { - return Err("the archive changed while it was being copied".into()); - } - fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?; - if !fcntl_get_seals(&memory) - .map_err(|e| format!("cannot read seals: {e}"))? - .contains(SEALS) - { - return Err("the kernel did not apply every seal".into()); - } - progress(want, want); - let report = report - .into_inner() - .ok() - .flatten() - .ok_or("the archive copy did not report")?; - Ok((memory, identity_before, report)) - } - - /// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an - /// independent read-only description. The original number stays open and untouched. - pub fn open_inherited(fd: u32) -> Result { - if !(3..=1_048_576).contains(&fd) { - return Err("an inherited descriptor must be 3 or higher".into()); - } - File::open(format!("/proc/self/fd/{fd}")) - .map_err(|e| format!("descriptor {fd} is not open in this process: {e}")) - } - - /// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked - /// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start. - pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> { - use std::os::unix::fs::MetadataExt; - let file = open_inherited(fd)?; - let meta = file - .metadata() - .map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?; - if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes { - return Err(format!( - "descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)", - meta.len(), - meta.nlink() - )); - } - if !fcntl_get_seals(&file) - .map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))? - .contains(SEALS) - { - return Err(format!( - "descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals" - )); - } - Ok(()) - } - - /// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor - /// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`. - pub fn exec_inherit(args: &[String]) -> Result { - let command = match args.split_first() { - Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest, - _ => return Err( - "usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)" - .into(), - ), - }; - let stdin = std::io::stdin(); - let moved = rustix::io::dup(stdin.as_fd()) - .map_err(|e| format!("cannot duplicate standard input: {e}"))?; - let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?; - rustix::stdio::dup2_stdin(&devnull) - .map_err(|e| format!("cannot replace standard input: {e}"))?; - let number = moved.into_raw_fd(); - if number < 3 { - return Err("the sealed descriptor landed on a standard stream".into()); - } - let arguments = substitute(&command[1..], number); - let error = Command::new(&command[0]).args(arguments).exec(); - Err(format!("cannot execute {:?}: {error}", command[0])) - } - - /// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`: copy the archive (or only the extents - /// the serve path reads) into a sealed memfd and replace this process with COMMAND, which inherits the descriptor (every `{FD}` in - /// its arguments is the number). The Rust form of `leleka-seal-exec`, with the sparse copy. Nothing is verified here: the engine - /// verifies the memfd it is given (the archive SHA-256, or with `--sparse-ple` the pinned digest of the extents). - pub fn seal_exec(args: &[String]) -> Result { - let plan = super::parse_seal_exec(args)?; - let started = std::time::Instant::now(); - let mut progress = |done: u64, total: u64| { - eprintln!( - "leleka seal-exec: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - ); - }; - let (memory, extents) = if plan.sparse_ple { - let expect = plan - .expect_bytes - .ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?; - let extents = super::archive_serve_extents(&plan.file, expect)?; - let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?; - (memory, Some(extents)) - } else { - ( - seal_file(&plan.file, plan.expect_bytes, &mut progress)?, - None, - ) - }; - let moved = rustix::io::dup(memory.as_fd()) - .map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?; - let number = moved.into_raw_fd(); - if number < 3 { - return Err("the sealed descriptor landed on a standard stream".into()); - } - let length = memory.metadata().map(|m| m.len()).unwrap_or(0); - eprintln!( - "leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s", - extents.as_ref().map_or(String::new(), |e| format!( - " (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)", - e.len(), - leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0 - )), - started.elapsed().as_secs_f64() - ); - let arguments = substitute(&plan.command[1..], number); - let error = Command::new(&plan.command[0]).args(arguments).exec(); - Err(format!("cannot execute {:?}: {error}", plan.command[0])) - } - - #[cfg(test)] - mod tests { - use super::*; - use std::io::Write; - use std::os::unix::fs::MetadataExt; - - #[test] - fn seal_is_exact_sealed_unlinked_and_cloexec() { - let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id())); - let payload: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); - std::fs::write(&path, &payload).unwrap(); - let mut calls = Vec::new(); - let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| { - calls.push((a, b)) - }) - .unwrap(); - let meta = sealed.metadata().unwrap(); - assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64); - assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); - assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err()); - assert!( - rustix::io::fcntl_getfd(&sealed) - .unwrap() - .contains(rustix::io::FdFlags::CLOEXEC) - ); - assert_eq!( - calls.last(), - Some(&(payload.len() as u64, payload.len() as u64)) - ); - // A descriptor reopened through /proc keeps the properties the engine checks. - let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32; - let reopened = open_inherited(number).unwrap(); - let meta = reopened.metadata().unwrap(); - assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64); - assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err()); - assert!(open_inherited(1).is_err()); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn parallel_fill_is_byte_exact_across_chunks_and_reports_the_source_identity() { - let path = std::env::temp_dir().join(format!("leleka-fill-{}", std::process::id())); - // Three full chunks and a ragged tail, with a pattern that differs per chunk. - let size = COPY_CHUNK * 3 + 4097; - let payload: Vec = (0..size) - .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) - .collect(); - std::fs::write(&path, &payload).unwrap(); - let (sealed, identity) = - seal_file_with_identity(&path, Some(size as u64), &mut |_, _| {}).unwrap(); - let identity = identity.expect("a regular file has an identity"); - assert_eq!(identity.size, size as u64); - let mut copy = vec![0u8; size]; - sealed.read_exact_at(&mut copy, 0).unwrap(); - assert!( - copy == payload, - "the memfd must equal the source byte for byte" - ); - assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); - std::fs::remove_file(path).unwrap(); - } - - fn blocks_bytes(f: &File) -> u64 { - f.metadata().unwrap().blocks() * 512 - } - - #[test] - fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() { - let path = std::env::temp_dir().join(format!("leleka-sparse-{}", std::process::id())); - // Two full chunks and a bit, so extents span and split across the 32 MiB pieces. - let size = COPY_CHUNK * 2 + 4096 * 5 + 77; - let payload: Vec = (0..size) - .map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1) - .collect(); - std::fs::write(&path, &payload).unwrap(); - let extents = [ - Extent::new(0, 8192), - Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096), - Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77), - ]; - let want: u64 = extents.iter().map(|e| e.len).sum(); - let mut calls = Vec::new(); - let (mut sealed, identity) = - seal_extents(&path, Some(size as u64), &extents, &mut |a, b| { - calls.push((a, b)) - }) - .unwrap(); - assert!(identity.is_some()); - assert_eq!( - calls.last(), - Some(&(want, want)), - "progress counts the extent bytes" - ); - // the memfd has the archive's length and the archive's seals - let meta = sealed.metadata().unwrap(); - assert!(meta.nlink() == 0 && meta.len() == size as u64); - assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); - assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err()); - // only the extents were allocated: pages of data, no page for any hole - let pages = |e: &Extent| (e.end().div_ceil(4096) - e.offset / 4096) * 4096; - assert_eq!( - blocks_bytes(&sealed), - extents.iter().map(pages).sum::() - ); - assert!(blocks_bytes(&sealed) < size as u64 / 4); - // extents hold the source's bytes at the same offsets; holes read as zeros - let mut copy = vec![0u8; size]; - sealed.read_exact_at(&mut copy, 0).unwrap(); - for (offset, byte) in copy.iter().enumerate() { - let inside = extents - .iter() - .any(|e| (offset as u64) >= e.offset && (offset as u64) < e.end()); - assert_eq!( - *byte, - if inside { payload[offset] } else { 0 }, - "offset {offset}" - ); - } - // reading the holes did not allocate them either - assert_eq!( - blocks_bytes(&sealed), - extents.iter().map(pages).sum::() - ); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn a_sparse_seal_refuses_extents_that_are_empty_unaligned_unsorted_or_outside_and_a_wrong_length() - { - let path = - std::env::temp_dir().join(format!("leleka-sparse-bad-{}", std::process::id())); - std::fs::write(&path, vec![7u8; 5 * 4096]).unwrap(); - let size = Some(5 * 4096); - for bad in [ - vec![Extent::new(0, 0)], - vec![Extent::new(1, 4096)], - vec![Extent::new(4096, 4096), Extent::new(0, 4096)], - vec![Extent::new(0, 8192), Extent::new(4096, 4096)], - vec![Extent::new(4 * 4096, 2 * 4096)], - vec![Extent::new(u64::MAX - 4095, 4096)], - ] { - let e = seal_extents(&path, size, &bad, &mut |_, _| {}) - .err() - .unwrap_or_else(|| panic!("{bad:?} accepted")); - assert!(e.contains("extent"), "{e}"); - } - assert!(seal_extents(&path, Some(1), &[Extent::new(0, 4096)], &mut |_, _| {}).is_err()); - // no extents at all is a valid (empty) sparse memfd, not the full copy - let (empty, _) = seal_extents(&path, size, &[], &mut |_, _| {}).unwrap(); - assert_eq!(blocks_bytes(&empty), 0); - assert_eq!(empty.metadata().unwrap().len(), 5 * 4096); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn exec_inherit_needs_a_command() { - assert!(exec_inherit(&[]).is_err()); - assert!(exec_inherit(&["--".into()]).is_err()); - assert!(exec_inherit(&["cmd".into()]).is_err()); - } - } -} +mod linux; #[cfg(test)] mod tests; -mod seal_file_fn; +mod exec_arguments; #[allow(unused_imports)] -pub use seal_file_fn::archive_serve_extents; +pub use exec_arguments::{archive_serve_extents, parse_seal_exec, substitute}; + #[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::check_inherited_archive; +mod unsupported_host; #[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::exec_inherit; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::open_inherited; -#[allow(unused_imports)] -pub use seal_file_fn::parse_seal_exec; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::seal_exec; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::seal_extents_report; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::seal_file; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::seal_file_report; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub use seal_file_fn::seal_file_with_identity; -#[allow(unused_imports)] -pub use seal_file_fn::substitute; +pub use unsupported_host::*; diff --git a/crates/deploy/src/sealed/seal_file_fn.rs b/crates/deploy/src/sealed/exec_arguments.rs similarity index 54% rename from crates/deploy/src/sealed/seal_file_fn.rs rename to crates/deploy/src/sealed/exec_arguments.rs index c3d306e1..285b1ddc 100644 --- a/crates/deploy/src/sealed/seal_file_fn.rs +++ b/crates/deploy/src/sealed/exec_arguments.rs @@ -1,85 +1,8 @@ -//! Moved out of the parent module by STRA-338: fn seal_file, fn seal_file_with_identity, fn seal_file_report, fn seal_extents_report, fn check_inherited_archive, fn open_inherited .... +//! The portable parts of `leleka seal-exec`: the sparse serve extents, the argument parser and the descriptor substitution. #[allow(unused_imports)] use super::*; -#[cfg(not(target_os = "linux"))] -pub fn seal_file( - _path: &std::path::Path, - _expect_bytes: Option, - _progress: &mut dyn FnMut(u64, u64), -) -> Result { - Err("sealed memfd archives require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn seal_file_with_identity( - _path: &std::path::Path, - _expect_bytes: Option, - _progress: &mut dyn FnMut(u64, u64), -) -> Result< - ( - std::fs::File, - Option, - ), - String, -> { - Err("sealed memfd archives require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn seal_file_report( - _path: &std::path::Path, - _expect_bytes: Option, - _progress: &mut dyn FnMut(u64, u64), -) -> Result< - ( - std::fs::File, - Option, - leleka_model_format::bulk_read::Report, - ), - String, -> { - Err("sealed memfd archives require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn seal_extents_report( - _path: &std::path::Path, - _expect_bytes: Option, - _extents: &[leleka_model_format::kar::Extent], - _progress: &mut dyn FnMut(u64, u64), -) -> Result< - ( - std::fs::File, - Option, - leleka_model_format::bulk_read::Report, - ), - String, -> { - Err("sealed memfd archives require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> { - Err("inherited descriptors require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn open_inherited(_fd: u32) -> Result { - Err("inherited descriptors require Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn exec_inherit(_args: &[String]) -> Result { - Err("exec-inherit requires Linux".into()) -} - -#[cfg(not(target_os = "linux"))] -pub fn seal_exec(_args: &[String]) -> Result { - Err("seal-exec requires Linux".into()) -} - /// The page-aligned ranges of the archive file at `kar` that the serve path reads, from its header and directory (about a megabyte of /// reads, none of the payload). Refuses a file that is not a valid KAR archive of `expect_bytes`. pub fn archive_serve_extents( diff --git a/crates/deploy/src/sealed/linux.rs b/crates/deploy/src/sealed/linux.rs new file mode 100644 index 00000000..33fb013b --- /dev/null +++ b/crates/deploy/src/sealed/linux.rs @@ -0,0 +1,374 @@ +//! The Linux sealing of the KAR archive: a sealed memfd, the sparse extent copy and the exec of the engine. + +use super::substitute; +use leleka_model_format::{kar::Extent, verify_stamp::FileIdentity}; +use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; +use std::{ + convert::Infallible, + fs::File, + os::{ + fd::{AsFd, IntoRawFd}, + unix::{fs::FileExt, process::CommandExt}, + }, + path::Path, + process::Command, + sync::{ + Mutex, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +pub const SEALS: SealFlags = SealFlags::from_bits_truncate( + SealFlags::WRITE.bits() + | SealFlags::GROW.bits() + | SealFlags::SHRINK.bits() + | SealFlags::SEAL.bits(), +); +/// Block size the tests use to cover several blocks and a ragged tail. +#[cfg(test)] +const COPY_CHUNK: usize = 32 << 20; + +/// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets +/// (copied, total) about every 4 GiB. +pub fn seal_file( + path: &Path, + expect_bytes: Option, + progress: &mut dyn FnMut(u64, u64), +) -> Result { + seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file) +} + +/// As [`seal_file`], returning the identity of the source file when it is a stable one. The identity is taken from the +/// opened file before the first byte and again after the last; a source that changed while it was copied is +/// refused, so the identity describes exactly the bytes that are in the memfd. +pub fn seal_file_with_identity( + path: &Path, + expect_bytes: Option, + progress: &mut dyn FnMut(u64, u64), +) -> Result<(File, Option), String> { + seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity)) +} + +/// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log. +pub fn seal_file_report( + path: &Path, + expect_bytes: Option, + progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + seal_ranges(path, expect_bytes, None, progress) +} + +/// A **sparse** sealed memfd: the final length of the archive, but only `extents` are copied; every byte outside them is +/// a hole (no page is allocated, a read returns zeros). File offsets are identical to the archive's, so a reader needs no +/// change. The extents must be sorted, disjoint, page-aligned at the start and inside the archive. The memfd is sealed +/// like the full one, but it is NOT the archive: the engine verifies it against the pinned digest of the extents +/// (`VerifiedKarPleArtifact::verify_sparse`), never against the archive's SHA-256, and the identity returned here must not be +/// used to record a verification stamp of the archive. +pub fn seal_extents( + path: &Path, + expect_bytes: Option, + extents: &[Extent], + progress: &mut dyn FnMut(u64, u64), +) -> Result<(File, Option), String> { + seal_extents_report(path, expect_bytes, extents, progress) + .map(|(file, identity, _)| (file, identity)) +} + +/// As [`seal_extents`], also returning how the file was read. +pub fn seal_extents_report( + path: &Path, + expect_bytes: Option, + extents: &[Extent], + progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + seal_ranges(path, expect_bytes, Some(extents), progress) +} + +fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> { + let mut previous_end = 0; + for (i, e) in extents.iter().enumerate() { + if e.len == 0 + || e.offset % leleka_model_format::kar::EXTENT_ALIGN != 0 + || e.offset < previous_end + || e.offset.checked_add(e.len).is_none_or(|end| end > total) + { + return Err(format!( + "extent {i} ({}+{}) is empty, unaligned, out of order or outside the {total}-byte archive", + e.offset, e.len + )); + } + previous_end = e.end(); + } + Ok(()) +} + +fn seal_ranges( + path: &Path, + expect_bytes: Option, + extents: Option<&[Extent]>, + progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + let source = File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; + let metadata = source + .metadata() + .map_err(|e| format!("cannot inspect the archive: {e}"))?; + if !metadata.is_file() { + return Err("the archive must be a regular file".into()); + } + if let Some(expected) = expect_bytes + && metadata.len() != expected + { + return Err(format!( + "the archive has {} bytes, expected {expected}", + metadata.len() + )); + } + let identity_before = FileIdentity::of(&metadata); + let total = metadata.len(); + let whole = [Extent::new(0, total)]; + let ranges: &[Extent] = match extents { + Some(extents) => { + check_extents(extents, total)?; + extents + } + None => &whole, + }; + let want: u64 = ranges.iter().map(|r| r.len).sum(); + let fd = memfd_create( + "leleka-sealed-archive", + MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, + ) + .map_err(|e| format!("memfd_create failed: {e}"))?; + let memory = File::from(fd); + let report: Mutex> = Mutex::new(None); + // The final size first (before the GROW seal exists), so that workers write disjoint ranges. + memory + .set_len(total) + .map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?; + // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue + // instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the + // memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else). + let plan = leleka_model_format::bulk_read::Plan::from_env(); + let copied = AtomicU64::new(0); + let finished = AtomicBool::new(false); + let failure: Mutex> = Mutex::new(None); + std::thread::scope(|scope| { + scope.spawn(|| { + // Set on every exit, a panic included, so that the progress loop below ends. + struct Finished<'a>(&'a AtomicBool); + impl Drop for Finished<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } + } + let _finished = Finished(&finished); + let mut strategy = None; + let mut elapsed = std::time::Duration::ZERO; + for range in ranges { + let outcome = leleka_model_format::bulk_read::for_each_chunk( + &source, + range.offset, + range.len, + plan, + |offset, data| { + memory.write_all_at(data, offset).map_err(|e| { + std::io::Error::other(format!( + "write to memfd failed (out of memory?): {e}" + )) + })?; + copied.fetch_add(data.len() as u64, Ordering::Relaxed); + Ok(()) + }, + ); + match outcome { + Ok(done) => { + strategy = Some(done.strategy); + elapsed += done.elapsed; + } + Err(e) => { + if let Ok(mut f) = failure.lock() { + f.get_or_insert(format!("read failed: {e}")); + } + return; + } + } + } + // No extents at all is a valid (empty) sparse copy: nothing was read. + let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain); + if let Ok(mut slot) = report.lock() { + *slot = Some(leleka_model_format::bulk_read::Report { + strategy, + bytes: want, + elapsed, + }); + } + }); + let mut reported = 0u64; + while !finished.load(Ordering::Acquire) { + std::thread::sleep(std::time::Duration::from_millis(100)); + let now = copied.load(Ordering::Relaxed); + if now - reported >= 4 << 30 { + reported = now; + progress(now, want); + } + } + }); + if let Some(message) = failure.into_inner().ok().flatten() { + return Err(message); + } + if copied.load(Ordering::Relaxed) != want { + return Err("the archive changed while it was being copied".into()); + } + let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m)); + if identity_before != identity_after { + return Err("the archive changed while it was being copied".into()); + } + fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?; + if !fcntl_get_seals(&memory) + .map_err(|e| format!("cannot read seals: {e}"))? + .contains(SEALS) + { + return Err("the kernel did not apply every seal".into()); + } + progress(want, want); + let report = report + .into_inner() + .ok() + .flatten() + .ok_or("the archive copy did not report")?; + Ok((memory, identity_before, report)) +} + +/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an +/// independent read-only description. The original number stays open and untouched. +pub fn open_inherited(fd: u32) -> Result { + if !(3..=1_048_576).contains(&fd) { + return Err("an inherited descriptor must be 3 or higher".into()); + } + File::open(format!("/proc/self/fd/{fd}")) + .map_err(|e| format!("descriptor {fd} is not open in this process: {e}")) +} + +/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked +/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start. +pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> { + use std::os::unix::fs::MetadataExt; + let file = open_inherited(fd)?; + let meta = file + .metadata() + .map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?; + if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes { + return Err(format!( + "descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)", + meta.len(), + meta.nlink() + )); + } + if !fcntl_get_seals(&file) + .map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))? + .contains(SEALS) + { + return Err(format!( + "descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals" + )); + } + Ok(()) +} + +/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor +/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`. +pub fn exec_inherit(args: &[String]) -> Result { + let command = + match args.split_first() { + Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest, + _ => return Err( + "usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)" + .into(), + ), + }; + let stdin = std::io::stdin(); + let moved = rustix::io::dup(stdin.as_fd()) + .map_err(|e| format!("cannot duplicate standard input: {e}"))?; + let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?; + rustix::stdio::dup2_stdin(&devnull) + .map_err(|e| format!("cannot replace standard input: {e}"))?; + let number = moved.into_raw_fd(); + if number < 3 { + return Err("the sealed descriptor landed on a standard stream".into()); + } + let arguments = substitute(&command[1..], number); + let error = Command::new(&command[0]).args(arguments).exec(); + Err(format!("cannot execute {:?}: {error}", command[0])) +} + +/// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`: copy the archive (or only the extents +/// the serve path reads) into a sealed memfd and replace this process with COMMAND, which inherits the descriptor (every `{FD}` in +/// its arguments is the number). The Rust form of `leleka-seal-exec`, with the sparse copy. Nothing is verified here: the engine +/// verifies the memfd it is given (the archive SHA-256, or with `--sparse-ple` the pinned digest of the extents). +pub fn seal_exec(args: &[String]) -> Result { + let plan = super::parse_seal_exec(args)?; + let started = std::time::Instant::now(); + let mut progress = |done: u64, total: u64| { + eprintln!( + "leleka seal-exec: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + ); + }; + let (memory, extents) = if plan.sparse_ple { + let expect = plan + .expect_bytes + .ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?; + let extents = super::archive_serve_extents(&plan.file, expect)?; + let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?; + (memory, Some(extents)) + } else { + ( + seal_file(&plan.file, plan.expect_bytes, &mut progress)?, + None, + ) + }; + let moved = rustix::io::dup(memory.as_fd()) + .map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?; + let number = moved.into_raw_fd(); + if number < 3 { + return Err("the sealed descriptor landed on a standard stream".into()); + } + let length = memory.metadata().map(|m| m.len()).unwrap_or(0); + eprintln!( + "leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s", + extents.as_ref().map_or(String::new(), |e| format!( + " (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)", + e.len(), + leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0 + )), + started.elapsed().as_secs_f64() + ); + let arguments = substitute(&plan.command[1..], number); + let error = Command::new(&plan.command[0]).args(arguments).exec(); + Err(format!("cannot execute {:?}: {error}", plan.command[0])) +} + +#[cfg(test)] +mod tests; diff --git a/crates/deploy/src/sealed/linux/tests.rs b/crates/deploy/src/sealed/linux/tests.rs new file mode 100644 index 00000000..08c62b4c --- /dev/null +++ b/crates/deploy/src/sealed/linux/tests.rs @@ -0,0 +1,157 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use std::io::Write; +use std::os::unix::fs::MetadataExt; + +#[test] +fn seal_is_exact_sealed_unlinked_and_cloexec() { + let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id())); + let payload: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); + std::fs::write(&path, &payload).unwrap(); + let mut calls = Vec::new(); + let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| { + calls.push((a, b)) + }) + .unwrap(); + let meta = sealed.metadata().unwrap(); + assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64); + assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); + assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err()); + assert!( + rustix::io::fcntl_getfd(&sealed) + .unwrap() + .contains(rustix::io::FdFlags::CLOEXEC) + ); + assert_eq!( + calls.last(), + Some(&(payload.len() as u64, payload.len() as u64)) + ); + // A descriptor reopened through /proc keeps the properties the engine checks. + let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32; + let reopened = open_inherited(number).unwrap(); + let meta = reopened.metadata().unwrap(); + assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64); + assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err()); + assert!(open_inherited(1).is_err()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn parallel_fill_is_byte_exact_across_chunks_and_reports_the_source_identity() { + let path = std::env::temp_dir().join(format!("leleka-fill-{}", std::process::id())); + // Three full chunks and a ragged tail, with a pattern that differs per chunk. + let size = COPY_CHUNK * 3 + 4097; + let payload: Vec = (0..size) + .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) + .collect(); + std::fs::write(&path, &payload).unwrap(); + let (sealed, identity) = + seal_file_with_identity(&path, Some(size as u64), &mut |_, _| {}).unwrap(); + let identity = identity.expect("a regular file has an identity"); + assert_eq!(identity.size, size as u64); + let mut copy = vec![0u8; size]; + sealed.read_exact_at(&mut copy, 0).unwrap(); + assert!( + copy == payload, + "the memfd must equal the source byte for byte" + ); + assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); + std::fs::remove_file(path).unwrap(); +} + +fn blocks_bytes(f: &File) -> u64 { + f.metadata().unwrap().blocks() * 512 +} + +#[test] +fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() { + let path = std::env::temp_dir().join(format!("leleka-sparse-{}", std::process::id())); + // Two full chunks and a bit, so extents span and split across the 32 MiB pieces. + let size = COPY_CHUNK * 2 + 4096 * 5 + 77; + let payload: Vec = (0..size) + .map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1) + .collect(); + std::fs::write(&path, &payload).unwrap(); + let extents = [ + Extent::new(0, 8192), + Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096), + Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77), + ]; + let want: u64 = extents.iter().map(|e| e.len).sum(); + let mut calls = Vec::new(); + let (mut sealed, identity) = seal_extents(&path, Some(size as u64), &extents, &mut |a, b| { + calls.push((a, b)) + }) + .unwrap(); + assert!(identity.is_some()); + assert_eq!( + calls.last(), + Some(&(want, want)), + "progress counts the extent bytes" + ); + // the memfd has the archive's length and the archive's seals + let meta = sealed.metadata().unwrap(); + assert!(meta.nlink() == 0 && meta.len() == size as u64); + assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); + assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err()); + // only the extents were allocated: pages of data, no page for any hole + let pages = |e: &Extent| (e.end().div_ceil(4096) - e.offset / 4096) * 4096; + assert_eq!( + blocks_bytes(&sealed), + extents.iter().map(pages).sum::() + ); + assert!(blocks_bytes(&sealed) < size as u64 / 4); + // extents hold the source's bytes at the same offsets; holes read as zeros + let mut copy = vec![0u8; size]; + sealed.read_exact_at(&mut copy, 0).unwrap(); + for (offset, byte) in copy.iter().enumerate() { + let inside = extents + .iter() + .any(|e| (offset as u64) >= e.offset && (offset as u64) < e.end()); + assert_eq!( + *byte, + if inside { payload[offset] } else { 0 }, + "offset {offset}" + ); + } + // reading the holes did not allocate them either + assert_eq!( + blocks_bytes(&sealed), + extents.iter().map(pages).sum::() + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn a_sparse_seal_refuses_extents_that_are_empty_unaligned_unsorted_or_outside_and_a_wrong_length() { + let path = std::env::temp_dir().join(format!("leleka-sparse-bad-{}", std::process::id())); + std::fs::write(&path, vec![7u8; 5 * 4096]).unwrap(); + let size = Some(5 * 4096); + for bad in [ + vec![Extent::new(0, 0)], + vec![Extent::new(1, 4096)], + vec![Extent::new(4096, 4096), Extent::new(0, 4096)], + vec![Extent::new(0, 8192), Extent::new(4096, 4096)], + vec![Extent::new(4 * 4096, 2 * 4096)], + vec![Extent::new(u64::MAX - 4095, 4096)], + ] { + let e = seal_extents(&path, size, &bad, &mut |_, _| {}) + .err() + .unwrap_or_else(|| panic!("{bad:?} accepted")); + assert!(e.contains("extent"), "{e}"); + } + assert!(seal_extents(&path, Some(1), &[Extent::new(0, 4096)], &mut |_, _| {}).is_err()); + // no extents at all is a valid (empty) sparse memfd, not the full copy + let (empty, _) = seal_extents(&path, size, &[], &mut |_, _| {}).unwrap(); + assert_eq!(blocks_bytes(&empty), 0); + assert_eq!(empty.metadata().unwrap().len(), 5 * 4096); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn exec_inherit_needs_a_command() { + assert!(exec_inherit(&[]).is_err()); + assert!(exec_inherit(&["--".into()]).is_err()); + assert!(exec_inherit(&["cmd".into()]).is_err()); +} diff --git a/crates/deploy/src/sealed/unsupported_host.rs b/crates/deploy/src/sealed/unsupported_host.rs new file mode 100644 index 00000000..9cfc744c --- /dev/null +++ b/crates/deploy/src/sealed/unsupported_host.rs @@ -0,0 +1,81 @@ +//! Sealing on a host without memfd: every operation answers that sealed archives require Linux. + +#[allow(unused_imports)] +use super::*; + +#[cfg(not(target_os = "linux"))] +pub fn seal_file( + _path: &std::path::Path, + _expect_bytes: Option, + _progress: &mut dyn FnMut(u64, u64), +) -> Result { + Err("sealed memfd archives require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn seal_file_with_identity( + _path: &std::path::Path, + _expect_bytes: Option, + _progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + std::fs::File, + Option, + ), + String, +> { + Err("sealed memfd archives require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn seal_file_report( + _path: &std::path::Path, + _expect_bytes: Option, + _progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + std::fs::File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + Err("sealed memfd archives require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn seal_extents_report( + _path: &std::path::Path, + _expect_bytes: Option, + _extents: &[leleka_model_format::kar::Extent], + _progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + std::fs::File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + Err("sealed memfd archives require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> { + Err("inherited descriptors require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn open_inherited(_fd: u32) -> Result { + Err("inherited descriptors require Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn exec_inherit(_args: &[String]) -> Result { + Err("exec-inherit requires Linux".into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn seal_exec(_args: &[String]) -> Result { + Err("seal-exec requires Linux".into()) +} diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index 38742585..6c3ef123 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -36,15 +36,6 @@ const LOG_ROTATE_BYTES: u64 = 64 << 20; /// Set by `--hidden` (the Windows logon task): the children get no console window. pub static HIDDEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Windows: the long-lived children (engine, gateway, API) get their own process group, so that Ctrl-C typed in the -/// supervisor's terminal reaches only the supervisor, which then stops them in order with Ctrl-Break (`interrupt`). No-op elsewhere. -pub fn own_group(command: &mut Command) { - #[cfg(windows)] - command.creation_flags(0x0000_0200); - #[cfg(not(windows))] - let _ = command; -} - #[derive(Clone, Debug)] pub struct Options { pub config: PathBuf, @@ -119,191 +110,14 @@ struct StatusDoc<'a> { log_bytes: u64, } -/// Seconds since the epoch. -fn unix_now() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_secs()) -} - -/// `YYYY-MM-DDTHH:MM:SSZ` without a date library (days-from-civil, Howard Hinnant). -pub fn format_utc(unix: u64) -> String { - let days = (unix / 86_400) as i64; - let secs = unix % 86_400; - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let year = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = doy - (153 * mp + 2) / 5 + 1; - let month = if mp < 10 { mp + 3 } else { mp - 9 }; - let year = if month <= 2 { year + 1 } else { year }; - format!( - "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", - secs / 3600, - secs % 3600 / 60, - secs % 60 - ) -} - -/// Move a log that grew past the limit to `NAME.1` (one generation is kept). -pub fn rotate_log(path: &Path, limit: u64) -> std::io::Result { - match std::fs::metadata(path) { - Ok(meta) if meta.len() > limit => { - let mut old = path.as_os_str().to_owned(); - old.push(".1"); - std::fs::rename(path, PathBuf::from(old))?; - Ok(true) - } - _ => Ok(false), - } -} - -fn open_log(path: &Path) -> std::io::Result { - rotate_log(path, LOG_ROTATE_BYTES)?; - private_append(path) -} - -fn private_append(path: &Path) -> std::io::Result { - let mut options = std::fs::OpenOptions::new(); - options.create(true).append(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - options.open(path) -} - -/// Write `contents` atomically with mode 0600. -pub fn write_private(path: &Path, contents: &str) -> std::io::Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(format!(".tmp{}", std::process::id())); - let tmp = PathBuf::from(tmp); - { - let mut options = std::fs::OpenOptions::new(); - options.create(true).truncate(true).write(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(&tmp)?; - file.write_all(contents.as_bytes())?; - file.sync_all()?; - } - std::fs::rename(tmp, path) -} - struct Log { file: std::sync::Mutex, } -impl Log { - /// A free-text note of the supervisor (the text is the message of a `msg` event). - fn line(&self, message: &str) { - self.event(leleka_obs::Level::Info, "msg", &[("msg", message.into())]); - } - - /// One structured event: JSON in `leleka.log`, and on standard error (the journal, or the terminal as key=value text). - /// Lifecycle events are rare by nature, so they are not sampled. - fn event(&self, level: leleka_obs::Level, ev: &str, fields: &[leleka_obs::Field<'_>]) { - let now = leleka_obs::now_ms(); - let file_format = leleka_obs::Settings { - min_level: leleka_obs::Level::Debug, - format: leleka_obs::Format::Json, - debug: false, - legacy: false, - }; - let file_line = - leleka_obs::format_line(&file_format, now, level, "supervisor", ev, fields, 0) + "\n"; - if level >= leleka_obs::settings().min_level { - let shown = leleka_obs::format_line( - leleka_obs::settings(), - now, - level, - "supervisor", - ev, - fields, - 0, - ) + "\n"; - let _ = std::io::stderr().write_all(shown.as_bytes()); - } - if let Ok(mut file) = self.file.lock() { - let _ = file.write_all(file_line.as_bytes()); - } - } -} - -/// `model_ready` of the runtime `id` in `leleka-cli status` output; `connected` is the second value. -pub fn parse_runtime_status(text: &str, id: &str) -> Option<(bool, bool)> { - let value: serde_json::Value = serde_json::from_str(text).ok()?; - let runtime = value - .get("runtimes")? - .as_array()? - .iter() - .find(|r| r.get("id").and_then(|v| v.as_str()) == Some(id))?; - Some(( - runtime - .get("connected") - .and_then(|v| v.as_bool()) - .unwrap_or(false), - runtime - .get("model_ready") - .and_then(|v| v.as_bool()) - .unwrap_or(false), - )) -} - /// `runtime.proto` `OperationResult.State`. const OPERATION_FAILED: i64 = 3; const OPERATION_INDETERMINATE: i64 = 4; -/// The operation id and epoch that `leleka-cli load-mtp` prints before it sends the command. -pub fn parse_operation(text: &str) -> Option<(String, String)> { - text.lines().find_map(|line| { - let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?; - Some(( - value.get("operation_id")?.as_str()?.to_owned(), - value.get("epoch")?.as_str()?.to_owned(), - )) - }) -} - -/// `state` of the pretty JSON that `leleka-cli operation` prints (the numeric `OperationResult.State`). -pub fn parse_operation_state(text: &str) -> Option { - let value: serde_json::Value = serde_json::from_str(text.trim()).ok()?; - value.get("state")?.as_i64() -} - -/// The last `lines` lines of a text file (empty when it cannot be read; only the last 256 KiB are looked at). -pub fn tail_of(path: &Path, lines: usize) -> String { - use std::io::{Read, Seek, SeekFrom}; - let Ok(mut file) = File::open(path) else { - return String::new(); - }; - let len = file.metadata().map_or(0, |m| m.len()); - let from = len.saturating_sub(256 << 10); - let mut bytes = Vec::new(); - if file.seek(SeekFrom::Start(from)).is_err() || file.read_to_end(&mut bytes).is_err() { - return String::new(); - } - let text = String::from_utf8_lossy(&bytes); - let all: Vec<&str> = text.lines().collect(); - all[all.len().saturating_sub(lines)..] - .iter() - .map(|l| l.chars().take(240).collect::()) - .collect::>() - .join("\n") -} - -/// Token rule of the runtime: 32..4096 printable ASCII bytes. -pub fn valid_token(token: &str) -> bool { - (32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b)) -} - struct Supervisor { config: RunConfig, paths: Paths, @@ -337,1527 +151,62 @@ struct Supervisor { health_note: String, } -pub async fn run(options: Options) -> i32 { - match run_inner(options).await { - Ok(()) => 0, - Err(failure) => { - eprintln!("leleka: {}", failure.message); - failure.code - } - } -} - -async fn run_inner(options: Options) -> Result<(), Failure> { - let config = - RunConfig::read(&options.config).map_err(|message| Failure { code: 2, message })?; - let paths = config.paths(); - let stamps_dir = paths.engine_stamps(); - for dir in [ - paths.logs(), - paths.run_dir(), - paths.mtp_staging(), - stamps_dir.clone(), - ] { - std::fs::create_dir_all(&dir).map_err(|e| Failure { - code: 2, - message: format!("cannot create {}: {e}", dir.display()), - })?; - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - for private in [paths.mtp_staging(), stamps_dir.clone()] { - let _ = std::fs::set_permissions(private, std::fs::Permissions::from_mode(0o700)); - } - } - let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| Failure { - code: 2, - message: format!( - "cannot read {}: {e}; run `leleka up`", - paths.env_file().display() - ), - })?; - let env = parse_env_file(&env_text); - let (runtime_token, gateway_token) = (env.get(RUNTIME_TOKEN_ENV), env.get(GATEWAY_TOKEN_ENV)); - match (runtime_token, gateway_token) { - (Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => {} - _ => { - return Err(Failure { - code: 2, - message: format!( - "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} values of 32..4096 printable ASCII bytes", - paths.env_file().display() - ), - }); - } - } - let api_key = std::fs::read_to_string(paths.api_key()) - .map_err(|e| Failure { - code: 2, - message: format!("cannot read {}: {e}", paths.api_key().display()), - })? - .trim_end_matches(['\r', '\n']) - .to_owned(); - for name in [ - "leleka", - "strata-next", - "leleka-inference", - "leleka-daemon", - "leleka-cli", - ] { - if !paths.bin(name).is_file() { - return Err(Failure { - code: 2, - message: format!("{} is missing; run `leleka up`", paths.bin(name).display()), - }); - } - } - let parse = |label: &str, text: &str| -> Result { - text.parse().map_err(|_| Failure { - code: 2, - message: format!("ports.{label} is not an ip:port"), - }) - }; - let (api_addr, engine_addr, daemon_addr) = ( - crate::config::probe_address(&config.ports.api).ok_or(Failure { - code: 2, - message: "ports.api is not an ip:port".into(), - })?, - parse("engine", &config.ports.engine)?, - parse("daemon", &config.ports.daemon)?, - ); - // No log line of this process or of its children may ever contain the key or a token. - leleka_obs::register_secret(&api_key); - for value in env.values() { - leleka_obs::register_secret(value); - } - let log_file = open_log(&paths.logs().join("leleka.log")).map_err(|e| Failure { - code: 2, - message: format!("cannot open the log: {e}"), - })?; - - let (stop_tx, stop_rx) = watch::channel(false); - spawn_signal_task(stop_tx, paths.run_dir()); - let mut supervisor = Supervisor { - status_path: paths.status_file(), - config, - paths, - env, - api_key, - log: Log { - file: std::sync::Mutex::new(log_file), - }, - shutdown: stop_rx, - archive: None, - source_identity: None, - archive_attested: false, - archive_sparse_pin: None, - stamps: VerifyStamps::new(stamps_dir, false), - api_addr, - engine_addr, - daemon_addr, - engine_restarts: 0, - pids: [None; 3], - phase: Phase::Starting, - message: String::new(), - beats: 0, - started_unix: unix_now(), - restarts_total: 0, - last_restart: None, - health_note: "starting".into(), - }; - supervisor.set_phase(Phase::Starting, "starting"); - let outcome = supervisor.drive(options.kar_fd).await; - let result = match outcome { - Ok(()) | Err(Flow::Stopped) => Ok(()), - Err(Flow::Fatal(failure)) => { - supervisor.log.event( - leleka_obs::Level::Error, - "fatal", - &[ - ("code", failure.code.into()), - ("msg", format!("fatal: {}", failure.message).as_str().into()), - ], - ); - supervisor.set_phase(Phase::Failed, &failure.message); - Err(failure) - } - }; - if result.is_ok() { - supervisor.set_phase(Phase::Stopped, "stopped"); - } - result -} - -#[cfg(windows)] -fn leleka_libc_shim_dll_dirs_env() -> &'static str { - "LELEKA_DLL_DIRS" -} - /// The file `leleka down` creates on Windows (there is no signal to send to a supervisor in another console). pub const STOP_REQUEST_FILE: &str = "stop.request"; -fn spawn_signal_task(stop: watch::Sender, run_dir: PathBuf) { - // Windows: Ctrl-C / Ctrl-Break / console close in this terminal, or `leleka down` from another one (a stop file). - #[cfg(windows)] - { - let request = run_dir.join(STOP_REQUEST_FILE); - let _ = std::fs::remove_file(&request); - tokio::spawn(async move { - let mut ctrl_break = tokio::signal::windows::ctrl_break().ok(); - let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); - loop { - tokio::select! { - _ = tokio::signal::ctrl_c() => break, - _ = async { match ctrl_break.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, - _ = async { match ctrl_close.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, - _ = tokio::time::sleep(Duration::from_millis(500)) => { - if request.exists() { - let _ = std::fs::remove_file(&request); - break; - } - } - } - } - let _ = stop.send(true); - }); - } - #[cfg(not(windows))] - let _ = run_dir; - #[cfg(unix)] - tokio::spawn(async move { - use tokio::signal::unix::{SignalKind, signal}; - let (Ok(mut term), Ok(mut int)) = ( - signal(SignalKind::terminate()), - signal(SignalKind::interrupt()), - ) else { - return; - }; - tokio::select! { - _ = term.recv() => {} - _ = int.recv() => {} - } - let _ = stop.send(true); - }); - #[cfg(not(any(unix, windows)))] - drop(stop); -} - -impl Supervisor { - fn set_phase(&mut self, phase: Phase, message: &str) { - self.phase = phase; - self.message = message.to_owned(); - self.write_status(); - } - - /// Rewrite the status file as it is, so that its `updated_unix` shows that the supervisor is alive (`leleka status` calls a - /// status that is minutes old stale). - fn heartbeat(&mut self) { - self.write_status(); - } - - fn write_status(&self) { - let (phase, message) = (self.phase, self.message.as_str()); - let endpoint = format!("http://{}", self.api_addr); - let doc = StatusDoc { - schema_version: 1, - phase, - ready: phase == Phase::Ready, - message, - updated_unix: unix_now(), - supervisor_pid: std::process::id(), - engine_pid: self.pids[0], - gateway_pid: self.pids[1], - api_pid: self.pids[2], - engine_restarts: self.engine_restarts, - endpoint: &endpoint, - model: &self.config.model_id, - model_digest: &self.config.model_digest, - profile: &self.config.profile.name, - kar_source: self.config.profile.kar_source.as_str(), - memfd_extents: self.config.profile.memfd_extents.as_str(), - started_unix: self.started_unix, - restarts_total: self.restarts_total, - last_restart_unix: self.last_restart.as_ref().map(|(at, _)| *at), - last_restart_reason: self.last_restart.as_ref().map(|(_, why)| why.as_str()), - health: &self.health_note, - log_bytes: logs::total_bytes(&self.paths.logs()), - }; - if let Ok(text) = serde_json::to_string_pretty(&doc) { - let _ = write_private(&self.status_path, &(text + "\n")); - } - } - - fn stopping(&self) -> bool { - *self.shutdown.borrow() - } - - /// Sleep unless a stop arrives first. False: stop requested. - async fn pause(&mut self, duration: Duration) -> bool { - tokio::select! { - _ = sleep(duration) => !self.stopping(), - _ = self.shutdown.changed() => false, - } - } - - fn child_env(&self, command: &mut Command, extra: &BTreeMap) { - command.env_remove("HF_TOKEN"); - // Observability (docs in `leleka --help`): the API writes one record per request to its own rotated file, every process logs - // JSON lines (their standard error is a file), and the API can read the supervisor's restart counters for /metrics. - command.env("LELEKA_REQUEST_LOG", self.paths.logs().join("requests.log")); - command.env("LELEKA_STATUS_FILE", &self.status_path); - command.env("LELEKA_PROFILE", &self.config.profile.name); - command.env("LELEKA_LOG_FORMAT", "json"); - for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] { - if let Some(value) = self.env.get(key) { - command.env(key, value); - } - } - #[cfg(windows)] - if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH").filter(|p| !p.is_empty()) { - // The loader flags of the engine search the application directory and System32 plus the directories named - // here (`leleka-libc-shim` registers them), so the cuBLAS DLLs can stay where the operator keeps them. - command.env(leleka_libc_shim_dll_dirs_env(), extra_path); - let existing = std::env::var("PATH").unwrap_or_default(); - command.env("PATH", format!("{extra_path};{existing}")); - } - #[cfg(not(windows))] - if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH") { - let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default(); - let joined = if existing.is_empty() { - extra_path.clone() - } else { - format!("{extra_path}:{existing}") - }; - command.env("LD_LIBRARY_PATH", joined); - } - for (key, value) in extra { - command.env(key, value); - } - } - - fn spawn( - &self, - name: &str, - program: &Path, - args: &[String], - extra: &BTreeMap, - stdin: Option, - ) -> Result { - let log = private_append(&self.paths.logs().join(format!("{name}.log"))) - .and_then(|f| f.try_clone().map(|g| (f, g))) - .map_err(|e| format!("cannot open the {name} log: {e}")); - let (out, err) = match log { - Ok(pair) => pair, - Err(message) => return fail(1, message), - }; - let mut command = Command::new(program); - own_group(&mut command); - command - .args(args) - .stdout(Stdio::from(out)) - .stderr(Stdio::from(err)) - .kill_on_drop(true); - command.stdin(match stdin { - Some(file) => Stdio::from(file), - None => Stdio::null(), - }); - self.child_env(&mut command, extra); - match command.spawn() { - Ok(child) => Ok(child), - Err(error) => fail( - 1, - format!("cannot start {name} ({}): {error}", program.display()), - ), - } - } - - /// Are both shards stamped as verified in their present state? (Then an engine start hashes neither.) - fn shard_stamps_current(&self) -> bool { - (0..2).all(|index| { - let digest = { - let mut out = [0u8; 32]; - hex::decode_to_slice(crate::profile::SHARD_SHA256_HEX[index], &mut out) - .is_ok() - .then_some(out) - }; - let identity = std::fs::File::open(self.paths.shard(index)) - .and_then(|f| f.metadata()) - .ok() - .and_then(|m| FileIdentity::of(&m)); - matches!((digest, identity), (Some(d), Some(id)) if self.stamps.trusts("gguf", &d, &id)) - }) - } - - /// While the supervisor fills the sealed memfd (reading 55 GB), a CPU-only `leleka-inference --verify-only` - /// hashes the two shards and records their stamps, so the engine that starts right after finds them verified. - /// The two reads overlap instead of following each other. Same verification, same refusals: a shard that does - /// not match its pin fails the start here, and a shard that changes before the engine opens it is hashed again - /// by the engine because the stamp no longer matches. - fn spawn_shard_preverify(&self) -> Option { - if !self.config.verify_stamps || self.shard_stamps_current() { - return None; - } - let program = self.paths.bin("leleka-inference"); - let args = self.config.verify_args(false); - match self.spawn("preverify", &program, &args, &BTreeMap::new(), None) { - Ok(child) => { - self.log.line( - "hashing the shards while the archive is copied (stamps are not current)", - ); - Some(child) - } - Err(_) => None, - } - } - - /// The pin of the extents when the profile asks for a sparse memfd (`None` for the full copy); refuses to start without one. - fn sparse_pin(&self) -> Result, Flow> { - if self.config.profile.memfd_extents != MemfdExtents::PleOnly { - return Ok(None); - } - match extents_sha256(&|key| std::env::var(key).ok()) { - Ok((pin, source)) => { - self.log.line(&format!( - "memfd_extents=ple_only: only the byte ranges the serve path reads are in the sealed memfd; the engine verifies them against the extents digest {}{}", - pin.iter().map(|b| format!("{b:02x}")).collect::(), - match source { - PinSource::Compiled => " (pinned in the binary)", - PinSource::Operator => " (supplied by LELEKA_KAR_EXTENTS_SHA256, not pinned in the binary)", - } - )); - Ok(Some(pin)) - } - Err(message) => fail(1, message), - } - } - - /// The page-aligned ranges of the archive file the serve path reads, from its header and directory (about a megabyte of reads). - fn serve_extents(kar: &Path) -> Result, Flow> { - match sealed::archive_serve_extents(kar, ARCHIVE_BYTES) { - Ok(extents) => Ok(extents), - Err(message) => fail(1, message), - } - } - - async fn drive(&mut self, kar_fd: Option) -> Result<(), Flow> { - // 1. the archive - self.archive = match (kar_fd, self.config.profile.kar_source) { - (Some(fd), KarSource::None) => { - return fail( - 2, - format!( - "descriptor {fd} was inherited but profile {} has kar_source none (no archive is used)", - self.config.profile.name - ), - ); - } - (None, KarSource::None) => { - self.log.line("kar_source none: no KAR archive; the PLE rows are read from the GGUF shard (qwen4exp-native-mtp-v1)"); - None - } - (Some(fd), _) => { - self.log.line(&format!( - "using the sealed archive descriptor {fd} inherited from the parent" - )); - self.archive_sparse_pin = self.sparse_pin()?; - Some( - sealed::open_inherited(fd) - .map_err(|message| Flow::Fatal(Failure { code: 2, message }))?, - ) - } - (None, KarSource::Memfd) => { - let kar = self.paths.kar(); - // `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd. - let sparse = self.sparse_pin()?; - let extents = match sparse { - Some(_) => Some(Self::serve_extents(&kar)?), - None => None, - }; - match &extents { - Some(list) => { - self.set_phase( - Phase::Sealing, - "copying the archive extents the serve path reads into a sealed memfd", - ); - self.log.line(&format!( - "sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest of the memfd is a hole (once per service life)", - list.len(), - leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0, - ARCHIVE_BYTES as f64 / 1073741824.0, - kar.display() - )); - } - None => { - self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); - self.log.line(&format!( - "sealing {} into RAM (once per service life)", - kar.display() - )); - } - } - let started = Instant::now(); - let mut preverify = self.spawn_shard_preverify(); - // A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine - // skip the hash of the memfd; it applies only if the file is still in the stamped state before - // AND after the copy. - let before = std::fs::File::open(&kar) - .and_then(|f| f.metadata()) - .ok() - .and_then(|m| FileIdentity::of(&m)); - let stamped = self.config.verify_stamps - && before - .is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id)); - let log = &self.log; - let mut progress = |done: u64, total: u64| { - log.line(&format!( - "sealing archive: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - )); - }; - let sealed = match &extents { - Some(list) => { - sealed::seal_extents_report(&kar, Some(ARCHIVE_BYTES), list, &mut progress) - } - None => sealed::seal_file_report(&kar, Some(ARCHIVE_BYTES), &mut progress), - }; - if let Some(child) = preverify.as_mut() { - let waited = Instant::now(); - match child.wait().await { - Ok(status) if status.success() => self.log.line(&format!( - "shards verified ({:.1}s after the copy ended)", - waited.elapsed().as_secs_f32() - )), - Ok(status) => { - return fail( - 1, - format!( - "a shard does not match its pinned digest ({status}); see {}", - self.paths.logs().join("preverify.log").display() - ), - ); - } - Err(error) => { - return fail(1, format!("shard verification did not finish: {error}")); - } - } - } - match sealed { - Ok((file, identity, read)) => { - self.log.line(&format!( - "sealed memfd ready in {:.1}s (read: {} blocks, {:.0} MB/s)", - started.elapsed().as_secs_f32(), - read.strategy.as_str(), - read.mb_per_s() - )); - if sparse.is_some() { - // A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation. - self.archive_sparse_pin = sparse; - self.source_identity = None; - self.archive_attested = false; - } else { - self.source_identity = identity; - self.archive_attested = stamped && identity == before; - } - if self.archive_attested { - self.log.line("the archive file matches its verification stamp: the engine will not hash the copy again"); - } - Some(file) - } - Err(message) => return fail(1, format!("cannot seal the archive: {message}")), - } - } - (None, KarSource::File) => None, - }; - if self.stopping() { - return Err(Flow::Stopped); - } - - // 2. gateway (needed for the typed load) - self.set_phase(Phase::StartingGateway, "starting the gateway"); - let daemon_args = vec![ - "--config".to_owned(), - self.paths.daemon_config().display().to_string(), - ]; - let mut gateway = self.spawn( - "gateway", - &self.paths.bin("leleka-daemon"), - &daemon_args, - &BTreeMap::new(), - None, - )?; - self.pids[1] = gateway.id(); - let mut engine = match self.start_engine(&mut gateway).await { - Ok(engine) => engine, - Err(flow) => { - self.kill_children(&mut [Some(&mut gateway)]).await; - return Err(flow); - } - }; - - // 3. public API - self.set_phase(Phase::StartingApi, "starting the API"); - let api_args = vec![ - "serve".to_owned(), - "--config".to_owned(), - self.paths.strata_config().display().to_string(), - ]; - let mut api = match self.spawn( - "api", - &self.paths.bin("strata-next"), - &api_args, - &BTreeMap::new(), - None, - ) { - Ok(child) => child, - Err(flow) => { - self.kill_children(&mut [Some(&mut engine), Some(&mut gateway)]) - .await; - return Err(flow); - } - }; - self.pids[2] = api.id(); - if let Err(flow) = self.wait_api_ready(&mut api).await { - self.kill_children(&mut [Some(&mut api), Some(&mut engine), Some(&mut gateway)]) - .await; - return Err(flow); - } - self.set_phase(Phase::Ready, "ready"); - self.log.line(&format!( - "ready: http://{} model {} (profile {}, logs {})", - self.api_addr, - self.config.model_id, - self.config.profile.name, - self.paths.logs().display() - )); - let mut ready_since = Instant::now(); - // Gateway and API restarts in a row; like the engine's they are forgotten after a stable period, so that a service that - // runs for weeks is not ended by the sixth API crash of the month. - let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32); - let (mut gateway_since, mut api_since) = (Instant::now(), Instant::now()); - let stable = Duration::from_secs(self.config.restart.stable_after_s); - // `leleka reconfigure` leaves a request file; look for it once a second. - let mut requests = tokio::time::interval(Duration::from_secs(1)); - requests.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut logs_tick = tokio::time::interval(Duration::from_secs(10)); - logs_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let health = self.config.health.clone(); - let mut health_tick = tokio::time::interval(Duration::from_secs(health.interval_s.max(1))); - health_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut watchdog = watchdog::Watchdog::new(watchdog::Limits { - fail: Duration::from_secs(health.fail_s), - max_request: Duration::from_secs(health.max_request_s), - }); - - // 4. supervise - let result: Result<(), Flow> = loop { - tokio::select! { - _ = self.shutdown.changed() => break Ok(()), - _ = requests.tick() => { - let Some(taken) = reconfigure::take_request(&self.paths) else { continue }; - match taken { - Err(message) => { - self.log.line(&format!("reconfigure: {message}")); - self.answer("", reconfigure::State::Refused, message, false); - } - Ok(request) => match self.reconfigure(request, &mut engine, &mut gateway, &mut api).await { - Ok(()) => { - ready_since = Instant::now(); - watchdog.reset(); - } - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - }, - } - } - status = engine.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - self.log.event( - leleka_obs::Level::Warn, - "engine_exit", - &[("status", text.as_str().into()), ("restarts_total", self.restarts_total.into()), ("msg", "the API reports not-ready until the engine is back".into())], - ); - match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, format!("the engine process exited ({text})")).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - _ = logs_tick.tick() => { - self.enforce_logs(); - self.beats += 1; - if self.beats.is_multiple_of(3) { - self.heartbeat(); - } - } - _ = health_tick.tick(), if self.config.health.enabled => { - let sample = self.sample_health().await; - match watchdog.observe(Instant::now(), &sample) { - watchdog::Verdict::Healthy => self.note_health("healthy"), - watchdog::Verdict::Suspect(why) => { - if self.health_note != why { - self.log.event(leleka_obs::Level::Warn, "health", &[("finding", why.as_str().into())]); - } - self.note_health(&why); - } - watchdog::Verdict::RestartApi(why) => { - self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "api".into()), ("reason", why.as_str().into())]); - self.restarts_total += 1; - self.last_restart = Some((unix_now(), why)); - api_since = Instant::now(); - match self.restart_api(&mut api).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - watchdog::Verdict::RestartEngine(why) => { - self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "engine".into()), ("reason", why.as_str().into())]); - if let Err(flow) = self.hard_kill(&mut engine).await { - break Err(flow); - } - match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, why).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - } - } - status = gateway.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - if gateway_since.elapsed() >= stable { - gateway_restarts = 0; - } - gateway_restarts += 1; - self.log.event( - leleka_obs::Level::Warn, - "gateway_exit", - &[("status", text.as_str().into()), ("restart", gateway_restarts.into()), ("of", 3u32.into())], - ); - if gateway_restarts > 3 { - break fail(1, "the gateway keeps dying"); - } - if !self.pause(Duration::from_secs(2)).await { - break Ok(()); - } - gateway = self.spawn("gateway", &self.paths.bin("leleka-daemon"), &daemon_args, &BTreeMap::new(), None)?; - self.pids[1] = gateway.id(); - gateway_since = Instant::now(); - } - status = api.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - if api_since.elapsed() >= stable { - api_restarts = 0; - } - api_restarts += 1; - self.log.event( - leleka_obs::Level::Warn, - "api_exit", - &[("status", text.as_str().into()), ("restart", api_restarts.into()), ("of", 5u32.into())], - ); - if api_restarts > 5 { - break fail(1, "the API keeps dying"); - } - if !self.pause(Duration::from_secs(2)).await { - break Ok(()); - } - api = self.spawn("api", &self.paths.bin("strata-next"), &api_args, &BTreeMap::new(), None)?; - self.pids[2] = api.id(); - api_since = Instant::now(); - } - } - }; - - // 5. drain: API first so streams end with a terminal event, then the gateway and the engine. - self.set_phase(Phase::Draining, "draining"); - self.log.line("stopping: API, gateway, engine"); - self.kill_children(&mut [Some(&mut api), Some(&mut gateway), Some(&mut engine)]) - .await; - self.pids = [None; 3]; - result - } - - /// Engine process -> port -> gateway connected -> typed load -> model_ready. - async fn start_engine(&mut self, gateway: &mut Child) -> Result { - self.set_phase(Phase::StartingEngine, "starting the engine"); - // The expert tier is re-checked at every start: a missing or changed table is logged loudly and the engine is - // not handed the switches that name it (`expert_profile::start_environment`). - let (env, tier) = - crate::expert_profile::start_environment(&self.config, &self.paths.dirs.assets); - self.log.line(&tier.line()); - let inference = self.paths.bin("leleka-inference"); - let (kar_arg, stdin) = match &self.archive { - Some(file) => ( - KarArg::Fd, - Some(file.try_clone().map_err(|e| { - Flow::Fatal(Failure { - code: 1, - message: format!("cannot duplicate the sealed descriptor: {e}"), - }) - })?), - ), - None if self.config.profile.kar_source == KarSource::None => (KarArg::None, None), - None => (KarArg::File, None), - }; - let mut engine_args = self.config.engine_args(kar_arg); - if let Some(pin) = self.archive_sparse_pin - && stdin.is_some() - { - engine_args.push("--kar-sparse-extents-sha256".into()); - engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect()); - } else if self.archive_attested && stdin.is_some() { - engine_args.push("--kar-attested-by-stamp".into()); - } - let mut engine = if stdin.is_some() { - let mut args = vec![ - "exec-inherit".to_owned(), - "--".to_owned(), - inference.display().to_string(), - ]; - args.extend(engine_args); - self.spawn("engine", &self.paths.bin("leleka"), &args, &env, stdin)? - } else { - self.spawn("engine", &inference, &engine_args, &env, None)? - }; - self.pids[0] = engine.id(); - self.log.line(&format!( - "engine started (pid {:?}); the log is {}", - engine.id(), - self.paths.logs().join("engine.log").display() - )); - let result = self.load_model(&mut engine, gateway).await; - if let Err(flow) = result { - self.kill_children(&mut [Some(&mut engine)]).await; - self.pids[0] = None; - return Err(flow); - } - // The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the - // life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file - // in a stable state, record that state so the next start of the service can skip the hash too. - if self.config.verify_stamps && self.archive.is_some() && self.archive_sparse_pin.is_none() - { - if !self.archive_attested - && let Some(identity) = self.source_identity - { - match self - .stamps - .record("kar-source", &archive_sha256(), &identity) - { - Ok(()) => self - .log - .line("recorded the verification stamp of the archive file"), - Err(error) => self - .log - .line(&format!("could not record the archive stamp: {error}")), - } - } - self.archive_attested = true; - } - Ok(engine) - } - - async fn wait_port( - &mut self, - address: SocketAddr, - watched: &mut Child, - what: &str, - limit: Duration, - ) -> Result<(), Flow> { - let started = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = watched.try_wait() { - return fail( - 1, - format!( - "{what} exited ({status}) before listening on {address}; see {}", - self.paths.logs().display() - ), - ); - } - if tokio::net::TcpStream::connect(address).await.is_ok() { - return Ok(()); - } - if started.elapsed() > limit { - return fail( - 1, - format!( - "{what} did not listen on {address} within {}s", - limit.as_secs() - ), - ); - } - if !self.pause(Duration::from_millis(500)).await { - return Err(Flow::Stopped); - } - } - } - - async fn cli(&self, args: &[&str]) -> Result<(bool, String), String> { - let mut command = Command::new(self.paths.bin("leleka-cli")); - command - .arg("--config") - .arg(self.paths.daemon_config()) - .args(args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .kill_on_drop(true); - self.child_env(&mut command, &BTreeMap::new()); - let output = timeout(Duration::from_secs(60), command.output()) - .await - .map_err(|_| "leleka-cli timed out".to_owned())? - .map_err(|e| format!("cannot run leleka-cli: {e}"))?; - Ok(( - output.status.success(), - String::from_utf8_lossy(&output.stdout).into_owned(), - )) - } - - async fn load_model(&mut self, engine: &mut Child, gateway: &mut Child) -> Result<(), Flow> { - let engine_addr = self.engine_addr; - self.wait_port(engine_addr, engine, "the engine", Duration::from_secs(300)) - .await?; - let daemon_addr = self.daemon_addr; - self.wait_port(daemon_addr, gateway, "the gateway", Duration::from_secs(60)) - .await?; - let id = self.config.model_id.clone(); - // The gateway connects to the engine lazily; wait until it reports the runtime connected. - let started = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = engine.try_wait() { - return fail( - 1, - format!("the engine exited ({status}) before the gateway connected"), - ); - } - if let Ok((true, text)) = self.cli(&["status"]).await - && parse_runtime_status(&text, &id).is_some_and(|(connected, _)| connected) - { - break; - } - if started.elapsed() > Duration::from_secs(120) { - return fail(1, "the gateway did not connect to the engine within 120 s"); - } - if !self.pause(Duration::from_secs(2)).await { - return Err(Flow::Stopped); - } - } - self.set_phase( - Phase::Loading, - "loading the model (verifies the shards and the archive)", - ); - self.log.line("loading the model: leleka-cli load-mtp (the engine verifies SHA-256 of shards and archive; this takes minutes)"); - let operation: Option<(String, String)> = - match self.cli(&["load-mtp", &id, self.config.mtp_profile()]).await { - Ok((true, text)) => parse_operation(&text), - // The CLI never retries an uncertain command; neither do we. - Ok((false, text)) => { - return fail( - 1, - format!( - "load-mtp was refused: {}", - text.lines().last().unwrap_or("no output") - ), - ); - } - Err(message) => return fail(1, message), - }; - let started = Instant::now(); - let mut last_report = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = engine.try_wait() { - return fail( - 1, - format!( - "the engine exited ({status}) while loading; see {}", - self.paths.logs().join("engine.log").display() - ), - ); - } - if let Ok((true, text)) = self.cli(&["status"]).await - && parse_runtime_status(&text, &id).is_some_and(|(_, ready)| ready) - { - self.log.line(&format!( - "model loaded in {:.0}s", - started.elapsed().as_secs_f32() - )); - return Ok(()); - } - // The engine process stays up when its load fails; the operation record says so. Do not wait - // out the timeout for a load that has already been refused. - if let Some((operation_id, epoch)) = &operation - && let Ok((true, text)) = self.cli(&["operation", &id, operation_id, epoch]).await - && let Some(state) = parse_operation_state(&text) - && matches!(state, OPERATION_FAILED | OPERATION_INDETERMINATE) - { - return fail( - 1, - format!( - "the engine {} the load; the last lines of {}: -{}", - if state == OPERATION_FAILED { - "refused" - } else { - "lost" - }, - self.paths.logs().join("engine.log").display(), - tail_of(&self.paths.logs().join("engine.log"), 8) - ), - ); - } - if started.elapsed() > Duration::from_secs(self.config.load_timeout_s) { - return fail( - 1, - format!( - "the model was not ready within {} s; see {}", - self.config.load_timeout_s, - self.paths.logs().join("engine.log").display() - ), - ); - } - if last_report.elapsed() >= Duration::from_secs(30) { - last_report = Instant::now(); - self.log.line(&format!( - "still loading ({:.0}s)", - started.elapsed().as_secs_f32() - )); - } - if !self.pause(Duration::from_secs(3)).await { - return Err(Flow::Stopped); - } - } - } - - async fn wait_api_ready(&mut self, api: &mut Child) -> Result<(), Flow> { - let started = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = api.try_wait() { - return fail( - 1, - format!( - "the API exited ({status}); see {}", - self.paths.logs().join("api.log").display() - ), - ); - } - if let Ok(response) = http::get( - self.api_addr, - "/ready", - Some(&self.api_key), - Duration::from_secs(5), - ) - .await - { - if response.status == 200 { - return Ok(()); - } - if response.status == 401 || response.status == 403 { - return fail(1, "the API rejected the key in the api-key file"); - } - } - if started.elapsed() > Duration::from_secs(180) { - return fail( - 1, - "the API was not ready within 180 s after the model loaded", - ); - } - if !self.pause(Duration::from_secs(1)).await { - return Err(Flow::Stopped); - } - } - } - - /// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one). - fn answer( - &self, - id: &str, - state: reconfigure::State, - message: impl Into, - persisted: bool, - ) { - let outcome = reconfigure::Outcome { - id: id.to_owned(), - state, - message: message.into(), - effective: Some(reconfigure::effective(&self.config)), - persisted, - }; - if let Err(error) = reconfigure::write_outcome(&self.paths, &outcome) { - self.log - .line(&format!("reconfigure: cannot write the answer: {error}")); - } - } - - /// What the host offers now, for the resource planner. - fn host_facts(&self) -> crate::facts::Facts { - crate::facts::probe(&crate::facts::ProbeRequest { - dirs: Vec::new(), - ports: Vec::new(), - binary_dir: None, - binaries: Vec::new(), - extra_library_dirs: Vec::new(), - }) - } - - /// Stop the API process and start it again (its configuration changed). The port stays the same. - async fn restart_api(&mut self, api: &mut Child) -> Result<(), Flow> { - self.kill_children(&mut [Some(&mut *api)]).await; - let args = vec![ - "serve".to_owned(), - "--config".to_owned(), - self.paths.strata_config().display().to_string(), - ]; - *api = self.spawn( - "api", - &self.paths.bin("strata-next"), - &args, - &BTreeMap::new(), - None, - )?; - self.pids[2] = api.id(); - self.wait_api_ready(api).await - } - - /// A `leleka reconfigure` request. - /// - /// Settings alone were applied to the live engine by the CLI; only the configuration in force is updated (and written when - /// asked). A budget or preset change restarts the engine process, and only that: the sealed archive descriptor this - /// process holds goes to the new engine, the gateway and the API keep their processes and ports. The planner checks the - /// request twice, first without disturbing the service (only what is impossible even with the engine gone is refused), then - /// with the engine stopped and the real free memory of the host. Whatever goes wrong after the stop, the previous settings - /// are started again. `Err` only when no engine can be started at all. - async fn reconfigure( - &mut self, - request: reconfigure::Request, - engine: &mut Child, - gateway: &mut Child, - api: &mut Child, - ) -> Result<(), Flow> { - let id = request.id.clone(); - self.log.line(&format!( - "reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}", - request.gpu_budget_gib, - request.preset.map(|p| p.as_str()), - serde_json::Value::Object(request.settings.clone()), - request.persist - )); - if !request.needs_restart() { - let mut next = self.config.clone(); - match reconfigure::record_settings(&mut next, &request.settings) { - Err(why) => self.answer(&id, reconfigure::State::Refused, why, false), - Ok(changed) => { - self.config = next; - let (persisted, note) = if request.persist { - match reconfigure::persist(&self.paths, &self.config) { - Ok(()) => (true, "written to leleka.json".to_owned()), - Err(why) => (false, format!("not persisted: {why}")), - } - } else { - (false, "in force until the service restarts".to_owned()) - }; - self.answer( - &id, - reconfigure::State::Done, - format!("recorded {changed:?}; {note}"), - persisted, - ); - } - } - return Ok(()); - } - let resident = self.archive.is_some(); - let facts = self.host_facts(); - match reconfigure::plan( - &self.config, - &request, - &reconfigure::optimistic(&facts), - resident, - ) { - Err(why) => { - self.log.line(&format!( - "reconfigure {id} refused before any change: {why}" - )); - self.answer( - &id, - reconfigure::State::Refused, - format!("{why}; nothing was changed"), - false, - ); - return Ok(()); - } - Ok(planned) if planned.unchanged => { - self.answer( - &id, - reconfigure::State::Done, - "the engine already runs with these settings", - false, - ); - return Ok(()); - } - Ok(_) => {} - } - self.answer( - &id, - reconfigure::State::Running, - "stopping the engine", - false, - ); - self.set_phase( - Phase::EngineRestarting, - "reconfiguring: restarting the engine", - ); - self.log.line( - "reconfigure: stopping the engine (the sealed archive stays with the supervisor)", - ); - self.kill_children(&mut [Some(&mut *engine)]).await; - self.pids[0] = None; - // The memory of the card returns when the process is gone; give the driver a moment before asking what is free. - let mut verdict = Err(String::new()); - for attempt in 0..10 { - if !self.pause(Duration::from_secs(1)).await { - return Err(Flow::Stopped); - } - verdict = reconfigure::plan(&self.config, &request, &self.host_facts(), resident); - let waiting_for_vram = matches!(&verdict, Err(why) if why.starts_with("GPU memory")); - if !waiting_for_vram || attempt == 9 { - break; - } - } - let previous = self.config.clone(); - let refusal = match verdict { - Ok(planned) => { - self.config = planned.config; - self.log.line(&format!( - "reconfigure: starting the engine with {}", - reconfigure::effective(&self.config) - )); - match self.start_engine(gateway).await { - Ok(child) => { - *engine = child; - let mut persisted = false; - let mut note = "in force until the service restarts".to_owned(); - if request.persist { - match reconfigure::persist(&self.paths, &self.config) { - Ok(()) => { - persisted = true; - note = "written to leleka.json".to_owned(); - // the API advertises the context of strata.json: follow it - if self.config.profile.context_tokens - != previous.profile.context_tokens - { - self.restart_api(api).await?; - } - } - Err(why) => note = format!("not persisted: {why}"), - } - } - self.set_phase(Phase::Ready, "ready (engine reconfigured)"); - self.log.line("reconfigure: done"); - self.answer( - &id, - reconfigure::State::Done, - format!("the engine runs with the new settings; {note}"), - persisted, - ); - return Ok(()); - } - Err(Flow::Stopped) => return Err(Flow::Stopped), - Err(Flow::Fatal(failure)) => failure.message, - } - } - Err(why) => why, - }; - // Refused on the stopped host, or the new engine did not come up: put the previous engine back. - self.config = previous; - self.log.line(&format!( - "reconfigure {id}: {refusal}; restoring the previous settings" - )); - let child = match self.start_engine(gateway).await { - Ok(child) => child, - Err(flow) => { - let why = format!("{refusal}; the previous settings could not be restored either"); - self.answer(&id, reconfigure::State::Failed, why, false); - return Err(flow); - } - }; - *engine = child; - self.set_phase(Phase::Ready, "ready (previous settings restored)"); - self.answer( - &id, - reconfigure::State::Refused, - format!("{refusal}; the previous settings are back"), - false, - ); - Ok(()) - } - - /// The engine process is gone (it exited, or `hard_kill` ended it): start it again, waiting longer after each attempt in a - /// row, until it is ready, or give up after `restart.max_engine_restarts` and let the caller end the service (systemd - /// then starts everything afresh). A start that fails (the load is refused, the port is taken) counts as an attempt. - async fn recover_engine( - &mut self, - engine: &mut Child, - gateway: &mut Child, - ready_since: &mut Instant, - reason: String, - ) -> Result<(), Flow> { - self.pids[0] = None; - self.restarts_total += 1; - self.last_restart = Some((unix_now(), reason.clone())); - if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) { - self.engine_restarts = 0; - } - loop { - if self.engine_restarts >= self.config.restart.max_engine_restarts { - return fail( - 1, - format!( - "the engine failed {} times in a row (last: {reason}); see {}", - self.engine_restarts, - self.paths.logs().join("engine.log").display() - ), - ); - } - self.engine_restarts += 1; - let wait = self.config.restart.backoff(self.engine_restarts); - self.set_phase( - Phase::EngineRestarting, - &format!( - "restarting the engine (attempt {} of {}, in {} s): {reason}", - self.engine_restarts, - self.config.restart.max_engine_restarts, - wait.as_secs() - ), - ); - if !self.pause(wait).await { - return Err(Flow::Stopped); - } - match self.start_engine(gateway).await { - Ok(child) => { - *engine = child; - self.set_phase(Phase::Ready, "ready (engine restarted)"); - *ready_since = Instant::now(); - return Ok(()); - } - Err(Flow::Stopped) => return Err(Flow::Stopped), - Err(Flow::Fatal(failure)) => { - self.log.line(&format!( - "the engine did not come back: {}", - failure.message - )); - } - } - } - } - - /// End a hung engine without ceremony: SIGKILL, and wait for the kernel to reap it (which frees the pinned memory - /// and the VRAM). A process that stays in uninterruptible sleep cannot be removed from here: that ends the service - /// with a message, because only a reboot helps. - async fn hard_kill(&mut self, engine: &mut Child) -> Result<(), Flow> { - let _ = engine.start_kill(); - match timeout(Duration::from_secs(60), engine.wait()).await { - Ok(_) => Ok(()), - Err(_) => fail( - 1, - "the hung engine does not die after SIGKILL (uninterruptible driver call?); the host needs a reboot", - ), - } - } - - /// One look at `GET /metrics` (the control plane's own view of the worker and the active request) for the hang detector. - async fn sample_health(&self) -> watchdog::Sample { - match http::get( - self.api_addr, - "/metrics", - Some(&self.api_key), - Duration::from_secs(5), - ) - .await - { - Ok(response) if response.status == 200 => watchdog::parse_metrics(&response.body), - Ok(response) => watchdog::Sample::Unreachable(format!("HTTP {}", response.status)), - Err(why) => watchdog::Sample::Unreachable(why), - } - } - - fn note_health(&mut self, note: &str) { - if self.health_note != note { - self.health_note = note.to_owned(); - self.write_status(); - } - } - - /// Keep the log directory bounded (`logs.rs`). - fn enforce_logs(&self) { - let policy = logs::Policy { - limit: self - .config - .logs - .limit_mib - .saturating_mul(1 << 20) - .max(1 << 20), - keep: self.config.logs.keep, - }; - for (path, outcome) in logs::enforce(&self.paths.logs(), policy) { - match outcome { - Ok(true) => self.log.event( - leleka_obs::Level::Info, - "log_rotated", - &[("file", path.display().to_string().as_str().into())], - ), - Ok(false) => {} - Err(error) => self - .log - .line(&format!("cannot rotate {}: {error}", path.display())), - } - } - } - - /// SIGINT (graceful for all three programs), then SIGKILL after the grace period. - async fn kill_children(&self, children: &mut [Option<&mut Child>]) { - for child in children.iter_mut().flatten() { - let grace = Duration::from_secs(self.config.shutdown_grace_s + 20); - interrupt(child); - if timeout(grace, child.wait()).await.is_err() { - self.log.line("a child ignored SIGINT; killing it"); - let _ = child.start_kill(); - let _ = child.wait().await; - } - } - } -} - -#[cfg(target_os = "linux")] -fn interrupt(child: &Child) { - if let Some(pid) = child - .id() - .and_then(|pid| i32::try_from(pid).ok()) - .and_then(rustix::process::Pid::from_raw) - { - let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT); - } -} - -#[cfg(windows)] -fn interrupt(child: &Child) { - // The child leads its own process group (`own_group`), so its pid is the group id Ctrl-Break is aimed at. - if let Some(pid) = child.id() { - let _ = crate::winsys::send_ctrl_break(pid); - } -} - -#[cfg(not(any(target_os = "linux", windows)))] -fn interrupt(_child: &Child) {} - #[cfg(test)] -mod tests { - use super::*; +mod tests; - #[test] - fn utc_formatting() { - assert_eq!(format_utc(0), "1970-01-01T00:00:00Z"); - assert_eq!(format_utc(1_760_700_000), "2025-10-17T11:20:00Z"); - assert_eq!(format_utc(951_782_400), "2000-02-29T00:00:00Z"); - } - - #[test] - fn status_parsing_matches_the_gateway_document() { - let text = r#"{"schema_version":1,"runtimes":[{"id":"qwen-iq3","connected":true,"epoch":"e","loaded_handle":null,"model_ready":false,"configuration_action_required":false}]}"#; - assert_eq!(parse_runtime_status(text, "qwen-iq3"), Some((true, false))); - assert_eq!(parse_runtime_status(text, "other"), None); - assert_eq!(parse_runtime_status("not json", "qwen-iq3"), None); - let ready = text.replace("\"model_ready\":false", "\"model_ready\":true"); - assert_eq!(parse_runtime_status(&ready, "qwen-iq3"), Some((true, true))); - } - - #[test] - fn operation_records_are_parsed_from_the_cli_output() { - let load = "{\"operation_id\":\"0f0e\",\"epoch\":\"ab\",\"model\":\"qwen-iq3\"} -{ - \"state\": 1 -} -"; - assert_eq!(parse_operation(load), Some(("0f0e".into(), "ab".into()))); - assert_eq!(parse_operation("nothing"), None); - assert_eq!( - parse_operation_state( - "{ - \"state\": 3, - \"reason\": \"load_failed\" -}" - ), - Some(3) - ); - assert_eq!(parse_operation_state("Error: x"), None); - let dir = std::env::temp_dir().join(format!("leleka-tail-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write( - dir.join("e.log"), - "a -b -c -d -", - ) - .unwrap(); - assert_eq!( - tail_of(&dir.join("e.log"), 2), - "c -d" - ); - assert_eq!(tail_of(&dir.join("missing.log"), 2), ""); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn token_rule() { - assert!(valid_token(&"a".repeat(32))); - assert!(!valid_token(&"a".repeat(31)) && !valid_token(&format!("{} b", "a".repeat(40)))); - } - - #[test] - fn log_rotation_keeps_one_generation() { - let dir = std::env::temp_dir().join(format!("leleka-rot-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let log = dir.join("engine.log"); - std::fs::write(&log, vec![b'x'; 100]).unwrap(); - assert!(!rotate_log(&log, 1000).unwrap()); - assert!(rotate_log(&log, 50).unwrap()); - assert!(!log.exists() && dir.join("engine.log.1").exists()); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn private_files_are_written_atomically_with_mode_0600() { - let dir = std::env::temp_dir().join(format!("leleka-priv-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("status.json"); - write_private(&file, "one").unwrap(); - write_private(&file, "two").unwrap(); - assert_eq!(std::fs::read_to_string(&file).unwrap(), "two"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - assert_eq!( - std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, - 0o600 - ); - } - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); - std::fs::remove_dir_all(dir).unwrap(); - } -} +mod logfile; +#[allow(unused_imports)] +pub use logfile::format_utc; +#[allow(unused_imports)] +use logfile::open_log; +#[allow(unused_imports)] +use logfile::private_append; +#[allow(unused_imports)] +pub use logfile::rotate_log; +#[allow(unused_imports)] +use logfile::unix_now; +#[allow(unused_imports)] +pub use logfile::write_private; +mod cli_output; +#[allow(unused_imports)] +pub use cli_output::parse_operation; +#[allow(unused_imports)] +pub use cli_output::parse_operation_state; +#[allow(unused_imports)] +pub use cli_output::parse_runtime_status; +#[allow(unused_imports)] +pub use cli_output::tail_of; +#[allow(unused_imports)] +pub use cli_output::valid_token; +mod startup; +#[cfg(windows)] +#[allow(unused_imports)] +use startup::leleka_libc_shim_dll_dirs_env; +#[allow(unused_imports)] +pub use startup::run; +#[allow(unused_imports)] +use startup::run_inner; +mod signals; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +use signals::interrupt; +#[cfg(windows)] +#[allow(unused_imports)] +use signals::interrupt; +#[cfg(not(any(target_os = "linux", windows)))] +#[allow(unused_imports)] +use signals::interrupt; +#[allow(unused_imports)] +use signals::spawn_signal_task; +mod children; +mod status; +#[allow(unused_imports)] +pub use children::own_group; +mod api; +mod engine; +mod live_reconfigure; +mod sparse; +mod supervise; diff --git a/crates/deploy/src/supervisor/api.rs b/crates/deploy/src/supervisor/api.rs new file mode 100644 index 00000000..4f0226d7 --- /dev/null +++ b/crates/deploy/src/supervisor/api.rs @@ -0,0 +1,88 @@ +//! The public API process: readiness wait, answers to the operator and restart. + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + pub(super) async fn wait_api_ready(&mut self, api: &mut Child) -> Result<(), Flow> { + let started = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + if let Ok(Some(status)) = api.try_wait() { + return fail( + 1, + format!( + "the API exited ({status}); see {}", + self.paths.logs().join("api.log").display() + ), + ); + } + if let Ok(response) = http::get( + self.api_addr, + "/ready", + Some(&self.api_key), + Duration::from_secs(5), + ) + .await + { + if response.status == 200 { + return Ok(()); + } + if response.status == 401 || response.status == 403 { + return fail(1, "the API rejected the key in the api-key file"); + } + } + if started.elapsed() > Duration::from_secs(180) { + return fail( + 1, + "the API was not ready within 180 s after the model loaded", + ); + } + if !self.pause(Duration::from_secs(1)).await { + return Err(Flow::Stopped); + } + } + } + + /// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one). + pub(super) fn answer( + &self, + id: &str, + state: reconfigure::State, + message: impl Into, + persisted: bool, + ) { + let outcome = reconfigure::Outcome { + id: id.to_owned(), + state, + message: message.into(), + effective: Some(reconfigure::effective(&self.config)), + persisted, + }; + if let Err(error) = reconfigure::write_outcome(&self.paths, &outcome) { + self.log + .line(&format!("reconfigure: cannot write the answer: {error}")); + } + } + + /// Stop the API process and start it again (its configuration changed). The port stays the same. + pub(super) async fn restart_api(&mut self, api: &mut Child) -> Result<(), Flow> { + self.kill_children(&mut [Some(&mut *api)]).await; + let args = vec![ + "serve".to_owned(), + "--config".to_owned(), + self.paths.strata_config().display().to_string(), + ]; + *api = self.spawn( + "api", + &self.paths.bin("strata-next"), + &args, + &BTreeMap::new(), + None, + )?; + self.pids[2] = api.id(); + self.wait_api_ready(api).await + } +} diff --git a/crates/deploy/src/supervisor/children.rs b/crates/deploy/src/supervisor/children.rs new file mode 100644 index 00000000..a6ad5084 --- /dev/null +++ b/crates/deploy/src/supervisor/children.rs @@ -0,0 +1,125 @@ +//! Spawning, pausing and killing the child processes (gateway, engine, API). + +#[allow(unused_imports)] +use super::*; + +/// Windows: the long-lived children (engine, gateway, API) get their own process group, so that Ctrl-C typed in the +/// supervisor's terminal reaches only the supervisor, which then stops them in order with Ctrl-Break (`interrupt`). No-op elsewhere. +pub fn own_group(command: &mut Command) { + #[cfg(windows)] + command.creation_flags(0x0000_0200); + #[cfg(not(windows))] + let _ = command; +} +impl Supervisor { + pub(super) fn stopping(&self) -> bool { + *self.shutdown.borrow() + } + + /// Sleep unless a stop arrives first. False: stop requested. + pub(super) async fn pause(&mut self, duration: Duration) -> bool { + tokio::select! { + _ = sleep(duration) => !self.stopping(), + _ = self.shutdown.changed() => false, + } + } + + pub(super) fn child_env(&self, command: &mut Command, extra: &BTreeMap) { + command.env_remove("HF_TOKEN"); + // Observability (docs in `leleka --help`): the API writes one record per request to its own rotated file, every process logs + // JSON lines (their standard error is a file), and the API can read the supervisor's restart counters for /metrics. + command.env("LELEKA_REQUEST_LOG", self.paths.logs().join("requests.log")); + command.env("LELEKA_STATUS_FILE", &self.status_path); + command.env("LELEKA_PROFILE", &self.config.profile.name); + command.env("LELEKA_LOG_FORMAT", "json"); + for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] { + if let Some(value) = self.env.get(key) { + command.env(key, value); + } + } + #[cfg(windows)] + if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH").filter(|p| !p.is_empty()) { + // The loader flags of the engine search the application directory and System32 plus the directories named + // here (`leleka-libc-shim` registers them), so the cuBLAS DLLs can stay where the operator keeps them. + command.env(leleka_libc_shim_dll_dirs_env(), extra_path); + let existing = std::env::var("PATH").unwrap_or_default(); + command.env("PATH", format!("{extra_path};{existing}")); + } + #[cfg(not(windows))] + if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH") { + let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default(); + let joined = if existing.is_empty() { + extra_path.clone() + } else { + format!("{extra_path}:{existing}") + }; + command.env("LD_LIBRARY_PATH", joined); + } + for (key, value) in extra { + command.env(key, value); + } + } + + pub(super) fn spawn( + &self, + name: &str, + program: &Path, + args: &[String], + extra: &BTreeMap, + stdin: Option, + ) -> Result { + let log = private_append(&self.paths.logs().join(format!("{name}.log"))) + .and_then(|f| f.try_clone().map(|g| (f, g))) + .map_err(|e| format!("cannot open the {name} log: {e}")); + let (out, err) = match log { + Ok(pair) => pair, + Err(message) => return fail(1, message), + }; + let mut command = Command::new(program); + own_group(&mut command); + command + .args(args) + .stdout(Stdio::from(out)) + .stderr(Stdio::from(err)) + .kill_on_drop(true); + command.stdin(match stdin { + Some(file) => Stdio::from(file), + None => Stdio::null(), + }); + self.child_env(&mut command, extra); + match command.spawn() { + Ok(child) => Ok(child), + Err(error) => fail( + 1, + format!("cannot start {name} ({}): {error}", program.display()), + ), + } + } + + /// End a hung engine without ceremony: SIGKILL, and wait for the kernel to reap it (which frees the pinned memory + /// and the VRAM). A process that stays in uninterruptible sleep cannot be removed from here: that ends the service + /// with a message, because only a reboot helps. + pub(super) async fn hard_kill(&mut self, engine: &mut Child) -> Result<(), Flow> { + let _ = engine.start_kill(); + match timeout(Duration::from_secs(60), engine.wait()).await { + Ok(_) => Ok(()), + Err(_) => fail( + 1, + "the hung engine does not die after SIGKILL (uninterruptible driver call?); the host needs a reboot", + ), + } + } + + /// SIGINT (graceful for all three programs), then SIGKILL after the grace period. + pub(super) async fn kill_children(&self, children: &mut [Option<&mut Child>]) { + for child in children.iter_mut().flatten() { + let grace = Duration::from_secs(self.config.shutdown_grace_s + 20); + interrupt(child); + if timeout(grace, child.wait()).await.is_err() { + self.log.line("a child ignored SIGINT; killing it"); + let _ = child.start_kill(); + let _ = child.wait().await; + } + } + } +} diff --git a/crates/deploy/src/supervisor/cli_output.rs b/crates/deploy/src/supervisor/cli_output.rs new file mode 100644 index 00000000..10da4cb5 --- /dev/null +++ b/crates/deploy/src/supervisor/cli_output.rs @@ -0,0 +1,67 @@ +//! Parsers of what `leleka-cli` and the gateway print (runtime status, operation records, log tails, token rule). + +#[allow(unused_imports)] +use super::*; + +/// `model_ready` of the runtime `id` in `leleka-cli status` output; `connected` is the second value. +pub fn parse_runtime_status(text: &str, id: &str) -> Option<(bool, bool)> { + let value: serde_json::Value = serde_json::from_str(text).ok()?; + let runtime = value + .get("runtimes")? + .as_array()? + .iter() + .find(|r| r.get("id").and_then(|v| v.as_str()) == Some(id))?; + Some(( + runtime + .get("connected") + .and_then(|v| v.as_bool()) + .unwrap_or(false), + runtime + .get("model_ready") + .and_then(|v| v.as_bool()) + .unwrap_or(false), + )) +} + +/// The operation id and epoch that `leleka-cli load-mtp` prints before it sends the command. +pub fn parse_operation(text: &str) -> Option<(String, String)> { + text.lines().find_map(|line| { + let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?; + Some(( + value.get("operation_id")?.as_str()?.to_owned(), + value.get("epoch")?.as_str()?.to_owned(), + )) + }) +} + +/// `state` of the pretty JSON that `leleka-cli operation` prints (the numeric `OperationResult.State`). +pub fn parse_operation_state(text: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(text.trim()).ok()?; + value.get("state")?.as_i64() +} + +/// The last `lines` lines of a text file (empty when it cannot be read; only the last 256 KiB are looked at). +pub fn tail_of(path: &Path, lines: usize) -> String { + use std::io::{Read, Seek, SeekFrom}; + let Ok(mut file) = File::open(path) else { + return String::new(); + }; + let len = file.metadata().map_or(0, |m| m.len()); + let from = len.saturating_sub(256 << 10); + let mut bytes = Vec::new(); + if file.seek(SeekFrom::Start(from)).is_err() || file.read_to_end(&mut bytes).is_err() { + return String::new(); + } + let text = String::from_utf8_lossy(&bytes); + let all: Vec<&str> = text.lines().collect(); + all[all.len().saturating_sub(lines)..] + .iter() + .map(|l| l.chars().take(240).collect::()) + .collect::>() + .join("\n") +} + +/// Token rule of the runtime: 32..4096 printable ASCII bytes. +pub fn valid_token(token: &str) -> bool { + (32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} diff --git a/crates/deploy/src/supervisor/engine.rs b/crates/deploy/src/supervisor/engine.rs new file mode 100644 index 00000000..38330a26 --- /dev/null +++ b/crates/deploy/src/supervisor/engine.rs @@ -0,0 +1,331 @@ +//! Starting the engine, loading the model through `leleka-cli` and recovering a dead engine. + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + /// Engine process -> port -> gateway connected -> typed load -> model_ready. + pub(super) async fn start_engine(&mut self, gateway: &mut Child) -> Result { + self.set_phase(Phase::StartingEngine, "starting the engine"); + // The expert tier is re-checked at every start: a missing or changed table is logged loudly and the engine is + // not handed the switches that name it (`expert_profile::start_environment`). + let (env, tier) = + crate::expert_profile::start_environment(&self.config, &self.paths.dirs.assets); + self.log.line(&tier.line()); + let inference = self.paths.bin("leleka-inference"); + let (kar_arg, stdin) = match &self.archive { + Some(file) => ( + KarArg::Fd, + Some(file.try_clone().map_err(|e| { + Flow::Fatal(Failure { + code: 1, + message: format!("cannot duplicate the sealed descriptor: {e}"), + }) + })?), + ), + None if self.config.profile.kar_source == KarSource::None => (KarArg::None, None), + None => (KarArg::File, None), + }; + let mut engine_args = self.config.engine_args(kar_arg); + if let Some(pin) = self.archive_sparse_pin + && stdin.is_some() + { + engine_args.push("--kar-sparse-extents-sha256".into()); + engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect()); + } else if self.archive_attested && stdin.is_some() { + engine_args.push("--kar-attested-by-stamp".into()); + } + let mut engine = if stdin.is_some() { + let mut args = vec![ + "exec-inherit".to_owned(), + "--".to_owned(), + inference.display().to_string(), + ]; + args.extend(engine_args); + self.spawn("engine", &self.paths.bin("leleka"), &args, &env, stdin)? + } else { + self.spawn("engine", &inference, &engine_args, &env, None)? + }; + self.pids[0] = engine.id(); + self.log.line(&format!( + "engine started (pid {:?}); the log is {}", + engine.id(), + self.paths.logs().join("engine.log").display() + )); + let result = self.load_model(&mut engine, gateway).await; + if let Err(flow) = result { + self.kill_children(&mut [Some(&mut engine)]).await; + self.pids[0] = None; + return Err(flow); + } + // The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the + // life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file + // in a stable state, record that state so the next start of the service can skip the hash too. + if self.config.verify_stamps && self.archive.is_some() && self.archive_sparse_pin.is_none() + { + if !self.archive_attested + && let Some(identity) = self.source_identity + { + match self + .stamps + .record("kar-source", &archive_sha256(), &identity) + { + Ok(()) => self + .log + .line("recorded the verification stamp of the archive file"), + Err(error) => self + .log + .line(&format!("could not record the archive stamp: {error}")), + } + } + self.archive_attested = true; + } + Ok(engine) + } + + pub(super) async fn wait_port( + &mut self, + address: SocketAddr, + watched: &mut Child, + what: &str, + limit: Duration, + ) -> Result<(), Flow> { + let started = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + if let Ok(Some(status)) = watched.try_wait() { + return fail( + 1, + format!( + "{what} exited ({status}) before listening on {address}; see {}", + self.paths.logs().display() + ), + ); + } + if tokio::net::TcpStream::connect(address).await.is_ok() { + return Ok(()); + } + if started.elapsed() > limit { + return fail( + 1, + format!( + "{what} did not listen on {address} within {}s", + limit.as_secs() + ), + ); + } + if !self.pause(Duration::from_millis(500)).await { + return Err(Flow::Stopped); + } + } + } + + pub(super) async fn cli(&self, args: &[&str]) -> Result<(bool, String), String> { + let mut command = Command::new(self.paths.bin("leleka-cli")); + command + .arg("--config") + .arg(self.paths.daemon_config()) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + self.child_env(&mut command, &BTreeMap::new()); + let output = timeout(Duration::from_secs(60), command.output()) + .await + .map_err(|_| "leleka-cli timed out".to_owned())? + .map_err(|e| format!("cannot run leleka-cli: {e}"))?; + Ok(( + output.status.success(), + String::from_utf8_lossy(&output.stdout).into_owned(), + )) + } + + pub(super) async fn load_model( + &mut self, + engine: &mut Child, + gateway: &mut Child, + ) -> Result<(), Flow> { + let engine_addr = self.engine_addr; + self.wait_port(engine_addr, engine, "the engine", Duration::from_secs(300)) + .await?; + let daemon_addr = self.daemon_addr; + self.wait_port(daemon_addr, gateway, "the gateway", Duration::from_secs(60)) + .await?; + let id = self.config.model_id.clone(); + // The gateway connects to the engine lazily; wait until it reports the runtime connected. + let started = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + if let Ok(Some(status)) = engine.try_wait() { + return fail( + 1, + format!("the engine exited ({status}) before the gateway connected"), + ); + } + if let Ok((true, text)) = self.cli(&["status"]).await + && parse_runtime_status(&text, &id).is_some_and(|(connected, _)| connected) + { + break; + } + if started.elapsed() > Duration::from_secs(120) { + return fail(1, "the gateway did not connect to the engine within 120 s"); + } + if !self.pause(Duration::from_secs(2)).await { + return Err(Flow::Stopped); + } + } + self.set_phase( + Phase::Loading, + "loading the model (verifies the shards and the archive)", + ); + self.log.line("loading the model: leleka-cli load-mtp (the engine verifies SHA-256 of shards and archive; this takes minutes)"); + let operation: Option<(String, String)> = match self + .cli(&["load-mtp", &id, self.config.mtp_profile()]) + .await + { + Ok((true, text)) => parse_operation(&text), + // The CLI never retries an uncertain command; neither do we. + Ok((false, text)) => { + return fail( + 1, + format!( + "load-mtp was refused: {}", + text.lines().last().unwrap_or("no output") + ), + ); + } + Err(message) => return fail(1, message), + }; + let started = Instant::now(); + let mut last_report = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + if let Ok(Some(status)) = engine.try_wait() { + return fail( + 1, + format!( + "the engine exited ({status}) while loading; see {}", + self.paths.logs().join("engine.log").display() + ), + ); + } + if let Ok((true, text)) = self.cli(&["status"]).await + && parse_runtime_status(&text, &id).is_some_and(|(_, ready)| ready) + { + self.log.line(&format!( + "model loaded in {:.0}s", + started.elapsed().as_secs_f32() + )); + return Ok(()); + } + // The engine process stays up when its load fails; the operation record says so. Do not wait + // out the timeout for a load that has already been refused. + if let Some((operation_id, epoch)) = &operation + && let Ok((true, text)) = self.cli(&["operation", &id, operation_id, epoch]).await + && let Some(state) = parse_operation_state(&text) + && matches!(state, OPERATION_FAILED | OPERATION_INDETERMINATE) + { + return fail( + 1, + format!( + "the engine {} the load; the last lines of {}: +{}", + if state == OPERATION_FAILED { + "refused" + } else { + "lost" + }, + self.paths.logs().join("engine.log").display(), + tail_of(&self.paths.logs().join("engine.log"), 8) + ), + ); + } + if started.elapsed() > Duration::from_secs(self.config.load_timeout_s) { + return fail( + 1, + format!( + "the model was not ready within {} s; see {}", + self.config.load_timeout_s, + self.paths.logs().join("engine.log").display() + ), + ); + } + if last_report.elapsed() >= Duration::from_secs(30) { + last_report = Instant::now(); + self.log.line(&format!( + "still loading ({:.0}s)", + started.elapsed().as_secs_f32() + )); + } + if !self.pause(Duration::from_secs(3)).await { + return Err(Flow::Stopped); + } + } + } + + /// The engine process is gone (it exited, or `hard_kill` ended it): start it again, waiting longer after each attempt in a + /// row, until it is ready, or give up after `restart.max_engine_restarts` and let the caller end the service (systemd + /// then starts everything afresh). A start that fails (the load is refused, the port is taken) counts as an attempt. + pub(super) async fn recover_engine( + &mut self, + engine: &mut Child, + gateway: &mut Child, + ready_since: &mut Instant, + reason: String, + ) -> Result<(), Flow> { + self.pids[0] = None; + self.restarts_total += 1; + self.last_restart = Some((unix_now(), reason.clone())); + if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) { + self.engine_restarts = 0; + } + loop { + if self.engine_restarts >= self.config.restart.max_engine_restarts { + return fail( + 1, + format!( + "the engine failed {} times in a row (last: {reason}); see {}", + self.engine_restarts, + self.paths.logs().join("engine.log").display() + ), + ); + } + self.engine_restarts += 1; + let wait = self.config.restart.backoff(self.engine_restarts); + self.set_phase( + Phase::EngineRestarting, + &format!( + "restarting the engine (attempt {} of {}, in {} s): {reason}", + self.engine_restarts, + self.config.restart.max_engine_restarts, + wait.as_secs() + ), + ); + if !self.pause(wait).await { + return Err(Flow::Stopped); + } + match self.start_engine(gateway).await { + Ok(child) => { + *engine = child; + self.set_phase(Phase::Ready, "ready (engine restarted)"); + *ready_since = Instant::now(); + return Ok(()); + } + Err(Flow::Stopped) => return Err(Flow::Stopped), + Err(Flow::Fatal(failure)) => { + self.log.line(&format!( + "the engine did not come back: {}", + failure.message + )); + } + } + } + } +} diff --git a/crates/deploy/src/supervisor/live_reconfigure.rs b/crates/deploy/src/supervisor/live_reconfigure.rs new file mode 100644 index 00000000..0940c3fc --- /dev/null +++ b/crates/deploy/src/supervisor/live_reconfigure.rs @@ -0,0 +1,179 @@ +//! Applying a reconfigure request to the running service (budget changes restart only the engine). + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + /// A `leleka reconfigure` request. + /// + /// Settings alone were applied to the live engine by the CLI; only the configuration in force is updated (and written when + /// asked). A budget or preset change restarts the engine process, and only that: the sealed archive descriptor this + /// process holds goes to the new engine, the gateway and the API keep their processes and ports. The planner checks the + /// request twice, first without disturbing the service (only what is impossible even with the engine gone is refused), then + /// with the engine stopped and the real free memory of the host. Whatever goes wrong after the stop, the previous settings + /// are started again. `Err` only when no engine can be started at all. + pub(super) async fn reconfigure( + &mut self, + request: reconfigure::Request, + engine: &mut Child, + gateway: &mut Child, + api: &mut Child, + ) -> Result<(), Flow> { + let id = request.id.clone(); + self.log.line(&format!( + "reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}", + request.gpu_budget_gib, + request.preset.map(|p| p.as_str()), + serde_json::Value::Object(request.settings.clone()), + request.persist + )); + if !request.needs_restart() { + let mut next = self.config.clone(); + match reconfigure::record_settings(&mut next, &request.settings) { + Err(why) => self.answer(&id, reconfigure::State::Refused, why, false), + Ok(changed) => { + self.config = next; + let (persisted, note) = if request.persist { + match reconfigure::persist(&self.paths, &self.config) { + Ok(()) => (true, "written to leleka.json".to_owned()), + Err(why) => (false, format!("not persisted: {why}")), + } + } else { + (false, "in force until the service restarts".to_owned()) + }; + self.answer( + &id, + reconfigure::State::Done, + format!("recorded {changed:?}; {note}"), + persisted, + ); + } + } + return Ok(()); + } + let resident = self.archive.is_some(); + let facts = self.host_facts(); + match reconfigure::plan( + &self.config, + &request, + &reconfigure::optimistic(&facts), + resident, + ) { + Err(why) => { + self.log.line(&format!( + "reconfigure {id} refused before any change: {why}" + )); + self.answer( + &id, + reconfigure::State::Refused, + format!("{why}; nothing was changed"), + false, + ); + return Ok(()); + } + Ok(planned) if planned.unchanged => { + self.answer( + &id, + reconfigure::State::Done, + "the engine already runs with these settings", + false, + ); + return Ok(()); + } + Ok(_) => {} + } + self.answer( + &id, + reconfigure::State::Running, + "stopping the engine", + false, + ); + self.set_phase( + Phase::EngineRestarting, + "reconfiguring: restarting the engine", + ); + self.log.line( + "reconfigure: stopping the engine (the sealed archive stays with the supervisor)", + ); + self.kill_children(&mut [Some(&mut *engine)]).await; + self.pids[0] = None; + // The memory of the card returns when the process is gone; give the driver a moment before asking what is free. + let mut verdict = Err(String::new()); + for attempt in 0..10 { + if !self.pause(Duration::from_secs(1)).await { + return Err(Flow::Stopped); + } + verdict = reconfigure::plan(&self.config, &request, &self.host_facts(), resident); + let waiting_for_vram = matches!(&verdict, Err(why) if why.starts_with("GPU memory")); + if !waiting_for_vram || attempt == 9 { + break; + } + } + let previous = self.config.clone(); + let refusal = match verdict { + Ok(planned) => { + self.config = planned.config; + self.log.line(&format!( + "reconfigure: starting the engine with {}", + reconfigure::effective(&self.config) + )); + match self.start_engine(gateway).await { + Ok(child) => { + *engine = child; + let mut persisted = false; + let mut note = "in force until the service restarts".to_owned(); + if request.persist { + match reconfigure::persist(&self.paths, &self.config) { + Ok(()) => { + persisted = true; + note = "written to leleka.json".to_owned(); + // the API advertises the context of strata.json: follow it + if self.config.profile.context_tokens + != previous.profile.context_tokens + { + self.restart_api(api).await?; + } + } + Err(why) => note = format!("not persisted: {why}"), + } + } + self.set_phase(Phase::Ready, "ready (engine reconfigured)"); + self.log.line("reconfigure: done"); + self.answer( + &id, + reconfigure::State::Done, + format!("the engine runs with the new settings; {note}"), + persisted, + ); + return Ok(()); + } + Err(Flow::Stopped) => return Err(Flow::Stopped), + Err(Flow::Fatal(failure)) => failure.message, + } + } + Err(why) => why, + }; + // Refused on the stopped host, or the new engine did not come up: put the previous engine back. + self.config = previous; + self.log.line(&format!( + "reconfigure {id}: {refusal}; restoring the previous settings" + )); + let child = match self.start_engine(gateway).await { + Ok(child) => child, + Err(flow) => { + let why = format!("{refusal}; the previous settings could not be restored either"); + self.answer(&id, reconfigure::State::Failed, why, false); + return Err(flow); + } + }; + *engine = child; + self.set_phase(Phase::Ready, "ready (previous settings restored)"); + self.answer( + &id, + reconfigure::State::Refused, + format!("{refusal}; the previous settings are back"), + false, + ); + Ok(()) + } +} diff --git a/crates/deploy/src/supervisor/logfile.rs b/crates/deploy/src/supervisor/logfile.rs new file mode 100644 index 00000000..cab7523c --- /dev/null +++ b/crates/deploy/src/supervisor/logfile.rs @@ -0,0 +1,122 @@ +//! The supervisor's own log file: UTC time stamps, rotation and private (mode 0600) appends. + +#[allow(unused_imports)] +use super::*; + +/// Seconds since the epoch. +pub(super) fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// `YYYY-MM-DDTHH:MM:SSZ` without a date library (days-from-civil, Howard Hinnant). +pub fn format_utc(unix: u64) -> String { + let days = (unix / 86_400) as i64; + let secs = unix % 86_400; + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let year = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if month <= 2 { year + 1 } else { year }; + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + secs / 3600, + secs % 3600 / 60, + secs % 60 + ) +} + +/// Move a log that grew past the limit to `NAME.1` (one generation is kept). +pub fn rotate_log(path: &Path, limit: u64) -> std::io::Result { + match std::fs::metadata(path) { + Ok(meta) if meta.len() > limit => { + let mut old = path.as_os_str().to_owned(); + old.push(".1"); + std::fs::rename(path, PathBuf::from(old))?; + Ok(true) + } + _ => Ok(false), + } +} + +pub(super) fn open_log(path: &Path) -> std::io::Result { + rotate_log(path, LOG_ROTATE_BYTES)?; + private_append(path) +} + +pub(super) fn private_append(path: &Path) -> std::io::Result { + let mut options = std::fs::OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options.open(path) +} + +/// Write `contents` atomically with mode 0600. +pub fn write_private(path: &Path, contents: &str) -> std::io::Result<()> { + let mut tmp = path.as_os_str().to_owned(); + tmp.push(format!(".tmp{}", std::process::id())); + let tmp = PathBuf::from(tmp); + { + let mut options = std::fs::OpenOptions::new(); + options.create(true).truncate(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&tmp)?; + file.write_all(contents.as_bytes())?; + file.sync_all()?; + } + std::fs::rename(tmp, path) +} +impl Log { + /// A free-text note of the supervisor (the text is the message of a `msg` event). + pub(super) fn line(&self, message: &str) { + self.event(leleka_obs::Level::Info, "msg", &[("msg", message.into())]); + } + + /// One structured event: JSON in `leleka.log`, and on standard error (the journal, or the terminal as key=value text). + /// Lifecycle events are rare by nature, so they are not sampled. + pub(super) fn event( + &self, + level: leleka_obs::Level, + ev: &str, + fields: &[leleka_obs::Field<'_>], + ) { + let now = leleka_obs::now_ms(); + let file_format = leleka_obs::Settings { + min_level: leleka_obs::Level::Debug, + format: leleka_obs::Format::Json, + debug: false, + legacy: false, + }; + let file_line = + leleka_obs::format_line(&file_format, now, level, "supervisor", ev, fields, 0) + "\n"; + if level >= leleka_obs::settings().min_level { + let shown = leleka_obs::format_line( + leleka_obs::settings(), + now, + level, + "supervisor", + ev, + fields, + 0, + ) + "\n"; + let _ = std::io::stderr().write_all(shown.as_bytes()); + } + if let Ok(mut file) = self.file.lock() { + let _ = file.write_all(file_line.as_bytes()); + } + } +} diff --git a/crates/deploy/src/supervisor/signals.rs b/crates/deploy/src/supervisor/signals.rs new file mode 100644 index 00000000..0b63f4c5 --- /dev/null +++ b/crates/deploy/src/supervisor/signals.rs @@ -0,0 +1,72 @@ +//! Stop requests (SIGTERM/SIGINT, Ctrl-C, a stop file) and the interrupt sent to a child. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn spawn_signal_task(stop: watch::Sender, run_dir: PathBuf) { + // Windows: Ctrl-C / Ctrl-Break / console close in this terminal, or `leleka down` from another one (a stop file). + #[cfg(windows)] + { + let request = run_dir.join(STOP_REQUEST_FILE); + let _ = std::fs::remove_file(&request); + tokio::spawn(async move { + let mut ctrl_break = tokio::signal::windows::ctrl_break().ok(); + let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => break, + _ = async { match ctrl_break.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, + _ = async { match ctrl_close.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, + _ = tokio::time::sleep(Duration::from_millis(500)) => { + if request.exists() { + let _ = std::fs::remove_file(&request); + break; + } + } + } + } + let _ = stop.send(true); + }); + } + #[cfg(not(windows))] + let _ = run_dir; + #[cfg(unix)] + tokio::spawn(async move { + use tokio::signal::unix::{SignalKind, signal}; + let (Ok(mut term), Ok(mut int)) = ( + signal(SignalKind::terminate()), + signal(SignalKind::interrupt()), + ) else { + return; + }; + tokio::select! { + _ = term.recv() => {} + _ = int.recv() => {} + } + let _ = stop.send(true); + }); + #[cfg(not(any(unix, windows)))] + drop(stop); +} + +#[cfg(target_os = "linux")] +pub(super) fn interrupt(child: &Child) { + if let Some(pid) = child + .id() + .and_then(|pid| i32::try_from(pid).ok()) + .and_then(rustix::process::Pid::from_raw) + { + let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT); + } +} + +#[cfg(windows)] +pub(super) fn interrupt(child: &Child) { + // The child leads its own process group (`own_group`), so its pid is the group id Ctrl-Break is aimed at. + if let Some(pid) = child.id() { + let _ = crate::winsys::send_ctrl_break(pid); + } +} + +#[cfg(not(any(target_os = "linux", windows)))] +pub(super) fn interrupt(_child: &Child) {} diff --git a/crates/deploy/src/supervisor/sparse.rs b/crates/deploy/src/supervisor/sparse.rs new file mode 100644 index 00000000..a63b374c --- /dev/null +++ b/crates/deploy/src/supervisor/sparse.rs @@ -0,0 +1,74 @@ +//! The sparse archive: shard stamps, the pre-verification process and the served extents. + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + /// Are both shards stamped as verified in their present state? (Then an engine start hashes neither.) + pub(super) fn shard_stamps_current(&self) -> bool { + (0..2).all(|index| { + let digest = { + let mut out = [0u8; 32]; + hex::decode_to_slice(crate::profile::SHARD_SHA256_HEX[index], &mut out) + .is_ok() + .then_some(out) + }; + let identity = std::fs::File::open(self.paths.shard(index)) + .and_then(|f| f.metadata()) + .ok() + .and_then(|m| FileIdentity::of(&m)); + matches!((digest, identity), (Some(d), Some(id)) if self.stamps.trusts("gguf", &d, &id)) + }) + } + + /// While the supervisor fills the sealed memfd (reading 55 GB), a CPU-only `leleka-inference --verify-only` + /// hashes the two shards and records their stamps, so the engine that starts right after finds them verified. + /// The two reads overlap instead of following each other. Same verification, same refusals: a shard that does + /// not match its pin fails the start here, and a shard that changes before the engine opens it is hashed again + /// by the engine because the stamp no longer matches. + pub(super) fn spawn_shard_preverify(&self) -> Option { + if !self.config.verify_stamps || self.shard_stamps_current() { + return None; + } + let program = self.paths.bin("leleka-inference"); + let args = self.config.verify_args(false); + match self.spawn("preverify", &program, &args, &BTreeMap::new(), None) { + Ok(child) => { + self.log.line( + "hashing the shards while the archive is copied (stamps are not current)", + ); + Some(child) + } + Err(_) => None, + } + } + + /// The pin of the extents when the profile asks for a sparse memfd (`None` for the full copy); refuses to start without one. + pub(super) fn sparse_pin(&self) -> Result, Flow> { + if self.config.profile.memfd_extents != MemfdExtents::PleOnly { + return Ok(None); + } + match extents_sha256(&|key| std::env::var(key).ok()) { + Ok((pin, source)) => { + self.log.line(&format!( + "memfd_extents=ple_only: only the byte ranges the serve path reads are in the sealed memfd; the engine verifies them against the extents digest {}{}", + pin.iter().map(|b| format!("{b:02x}")).collect::(), + match source { + PinSource::Compiled => " (pinned in the binary)", + PinSource::Operator => " (supplied by LELEKA_KAR_EXTENTS_SHA256, not pinned in the binary)", + } + )); + Ok(Some(pin)) + } + Err(message) => fail(1, message), + } + } + + /// The page-aligned ranges of the archive file the serve path reads, from its header and directory (about a megabyte of reads). + pub(super) fn serve_extents(kar: &Path) -> Result, Flow> { + match sealed::archive_serve_extents(kar, ARCHIVE_BYTES) { + Ok(extents) => Ok(extents), + Err(message) => fail(1, message), + } + } +} diff --git a/crates/deploy/src/supervisor/startup.rs b/crates/deploy/src/supervisor/startup.rs new file mode 100644 index 00000000..7d9f84e0 --- /dev/null +++ b/crates/deploy/src/supervisor/startup.rs @@ -0,0 +1,161 @@ +//! Entry of `leleka run`: build the supervisor, seal the archive and run until a stop request. + +#[allow(unused_imports)] +use super::*; + +pub async fn run(options: Options) -> i32 { + match run_inner(options).await { + Ok(()) => 0, + Err(failure) => { + eprintln!("leleka: {}", failure.message); + failure.code + } + } +} + +pub(super) async fn run_inner(options: Options) -> Result<(), Failure> { + let config = + RunConfig::read(&options.config).map_err(|message| Failure { code: 2, message })?; + let paths = config.paths(); + let stamps_dir = paths.engine_stamps(); + for dir in [ + paths.logs(), + paths.run_dir(), + paths.mtp_staging(), + stamps_dir.clone(), + ] { + std::fs::create_dir_all(&dir).map_err(|e| Failure { + code: 2, + message: format!("cannot create {}: {e}", dir.display()), + })?; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for private in [paths.mtp_staging(), stamps_dir.clone()] { + let _ = std::fs::set_permissions(private, std::fs::Permissions::from_mode(0o700)); + } + } + let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| Failure { + code: 2, + message: format!( + "cannot read {}: {e}; run `leleka up`", + paths.env_file().display() + ), + })?; + let env = parse_env_file(&env_text); + let (runtime_token, gateway_token) = (env.get(RUNTIME_TOKEN_ENV), env.get(GATEWAY_TOKEN_ENV)); + match (runtime_token, gateway_token) { + (Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => {} + _ => { + return Err(Failure { + code: 2, + message: format!( + "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} values of 32..4096 printable ASCII bytes", + paths.env_file().display() + ), + }); + } + } + let api_key = std::fs::read_to_string(paths.api_key()) + .map_err(|e| Failure { + code: 2, + message: format!("cannot read {}: {e}", paths.api_key().display()), + })? + .trim_end_matches(['\r', '\n']) + .to_owned(); + for name in [ + "leleka", + "strata-next", + "leleka-inference", + "leleka-daemon", + "leleka-cli", + ] { + if !paths.bin(name).is_file() { + return Err(Failure { + code: 2, + message: format!("{} is missing; run `leleka up`", paths.bin(name).display()), + }); + } + } + let parse = |label: &str, text: &str| -> Result { + text.parse().map_err(|_| Failure { + code: 2, + message: format!("ports.{label} is not an ip:port"), + }) + }; + let (api_addr, engine_addr, daemon_addr) = ( + crate::config::probe_address(&config.ports.api).ok_or(Failure { + code: 2, + message: "ports.api is not an ip:port".into(), + })?, + parse("engine", &config.ports.engine)?, + parse("daemon", &config.ports.daemon)?, + ); + // No log line of this process or of its children may ever contain the key or a token. + leleka_obs::register_secret(&api_key); + for value in env.values() { + leleka_obs::register_secret(value); + } + let log_file = open_log(&paths.logs().join("leleka.log")).map_err(|e| Failure { + code: 2, + message: format!("cannot open the log: {e}"), + })?; + + let (stop_tx, stop_rx) = watch::channel(false); + spawn_signal_task(stop_tx, paths.run_dir()); + let mut supervisor = Supervisor { + status_path: paths.status_file(), + config, + paths, + env, + api_key, + log: Log { + file: std::sync::Mutex::new(log_file), + }, + shutdown: stop_rx, + archive: None, + source_identity: None, + archive_attested: false, + archive_sparse_pin: None, + stamps: VerifyStamps::new(stamps_dir, false), + api_addr, + engine_addr, + daemon_addr, + engine_restarts: 0, + pids: [None; 3], + phase: Phase::Starting, + message: String::new(), + beats: 0, + started_unix: unix_now(), + restarts_total: 0, + last_restart: None, + health_note: "starting".into(), + }; + supervisor.set_phase(Phase::Starting, "starting"); + let outcome = supervisor.drive(options.kar_fd).await; + let result = match outcome { + Ok(()) | Err(Flow::Stopped) => Ok(()), + Err(Flow::Fatal(failure)) => { + supervisor.log.event( + leleka_obs::Level::Error, + "fatal", + &[ + ("code", failure.code.into()), + ("msg", format!("fatal: {}", failure.message).as_str().into()), + ], + ); + supervisor.set_phase(Phase::Failed, &failure.message); + Err(failure) + } + }; + if result.is_ok() { + supervisor.set_phase(Phase::Stopped, "stopped"); + } + result +} + +#[cfg(windows)] +pub(super) fn leleka_libc_shim_dll_dirs_env() -> &'static str { + "LELEKA_DLL_DIRS" +} diff --git a/crates/deploy/src/supervisor/status.rs b/crates/deploy/src/supervisor/status.rs new file mode 100644 index 00000000..56f36c03 --- /dev/null +++ b/crates/deploy/src/supervisor/status.rs @@ -0,0 +1,68 @@ +//! The status document, its phases and the health notes of the running supervisor. + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + pub(super) fn set_phase(&mut self, phase: Phase, message: &str) { + self.phase = phase; + self.message = message.to_owned(); + self.write_status(); + } + + /// Rewrite the status file as it is, so that its `updated_unix` shows that the supervisor is alive (`leleka status` calls a + /// status that is minutes old stale). + pub(super) fn heartbeat(&mut self) { + self.write_status(); + } + + pub(super) fn write_status(&self) { + let (phase, message) = (self.phase, self.message.as_str()); + let endpoint = format!("http://{}", self.api_addr); + let doc = StatusDoc { + schema_version: 1, + phase, + ready: phase == Phase::Ready, + message, + updated_unix: unix_now(), + supervisor_pid: std::process::id(), + engine_pid: self.pids[0], + gateway_pid: self.pids[1], + api_pid: self.pids[2], + engine_restarts: self.engine_restarts, + endpoint: &endpoint, + model: &self.config.model_id, + model_digest: &self.config.model_digest, + profile: &self.config.profile.name, + kar_source: self.config.profile.kar_source.as_str(), + memfd_extents: self.config.profile.memfd_extents.as_str(), + started_unix: self.started_unix, + restarts_total: self.restarts_total, + last_restart_unix: self.last_restart.as_ref().map(|(at, _)| *at), + last_restart_reason: self.last_restart.as_ref().map(|(_, why)| why.as_str()), + health: &self.health_note, + log_bytes: logs::total_bytes(&self.paths.logs()), + }; + if let Ok(text) = serde_json::to_string_pretty(&doc) { + let _ = write_private(&self.status_path, &(text + "\n")); + } + } + + /// What the host offers now, for the resource planner. + pub(super) fn host_facts(&self) -> crate::facts::Facts { + crate::facts::probe(&crate::facts::ProbeRequest { + dirs: Vec::new(), + ports: Vec::new(), + binary_dir: None, + binaries: Vec::new(), + extra_library_dirs: Vec::new(), + }) + } + + pub(super) fn note_health(&mut self, note: &str) { + if self.health_note != note { + self.health_note = note.to_owned(); + self.write_status(); + } + } +} diff --git a/crates/deploy/src/supervisor/supervise.rs b/crates/deploy/src/supervisor/supervise.rs new file mode 100644 index 00000000..a0cde24d --- /dev/null +++ b/crates/deploy/src/supervisor/supervise.rs @@ -0,0 +1,387 @@ +//! The supervision loop of a running service and its health sampling. + +#[allow(unused_imports)] +use super::*; + +impl Supervisor { + pub(super) async fn drive(&mut self, kar_fd: Option) -> Result<(), Flow> { + // 1. the archive + self.archive = match (kar_fd, self.config.profile.kar_source) { + (Some(fd), KarSource::None) => { + return fail( + 2, + format!( + "descriptor {fd} was inherited but profile {} has kar_source none (no archive is used)", + self.config.profile.name + ), + ); + } + (None, KarSource::None) => { + self.log.line("kar_source none: no KAR archive; the PLE rows are read from the GGUF shard (qwen4exp-native-mtp-v1)"); + None + } + (Some(fd), _) => { + self.log.line(&format!( + "using the sealed archive descriptor {fd} inherited from the parent" + )); + self.archive_sparse_pin = self.sparse_pin()?; + Some( + sealed::open_inherited(fd) + .map_err(|message| Flow::Fatal(Failure { code: 2, message }))?, + ) + } + (None, KarSource::Memfd) => { + let kar = self.paths.kar(); + // `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd. + let sparse = self.sparse_pin()?; + let extents = match sparse { + Some(_) => Some(Self::serve_extents(&kar)?), + None => None, + }; + match &extents { + Some(list) => { + self.set_phase( + Phase::Sealing, + "copying the archive extents the serve path reads into a sealed memfd", + ); + self.log.line(&format!( + "sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest of the memfd is a hole (once per service life)", + list.len(), + leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0, + ARCHIVE_BYTES as f64 / 1073741824.0, + kar.display() + )); + } + None => { + self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); + self.log.line(&format!( + "sealing {} into RAM (once per service life)", + kar.display() + )); + } + } + let started = Instant::now(); + let mut preverify = self.spawn_shard_preverify(); + // A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine + // skip the hash of the memfd; it applies only if the file is still in the stamped state before + // AND after the copy. + let before = std::fs::File::open(&kar) + .and_then(|f| f.metadata()) + .ok() + .and_then(|m| FileIdentity::of(&m)); + let stamped = self.config.verify_stamps + && before + .is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id)); + let log = &self.log; + let mut progress = |done: u64, total: u64| { + log.line(&format!( + "sealing archive: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + )); + }; + let sealed = match &extents { + Some(list) => { + sealed::seal_extents_report(&kar, Some(ARCHIVE_BYTES), list, &mut progress) + } + None => sealed::seal_file_report(&kar, Some(ARCHIVE_BYTES), &mut progress), + }; + if let Some(child) = preverify.as_mut() { + let waited = Instant::now(); + match child.wait().await { + Ok(status) if status.success() => self.log.line(&format!( + "shards verified ({:.1}s after the copy ended)", + waited.elapsed().as_secs_f32() + )), + Ok(status) => { + return fail( + 1, + format!( + "a shard does not match its pinned digest ({status}); see {}", + self.paths.logs().join("preverify.log").display() + ), + ); + } + Err(error) => { + return fail(1, format!("shard verification did not finish: {error}")); + } + } + } + match sealed { + Ok((file, identity, read)) => { + self.log.line(&format!( + "sealed memfd ready in {:.1}s (read: {} blocks, {:.0} MB/s)", + started.elapsed().as_secs_f32(), + read.strategy.as_str(), + read.mb_per_s() + )); + if sparse.is_some() { + // A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation. + self.archive_sparse_pin = sparse; + self.source_identity = None; + self.archive_attested = false; + } else { + self.source_identity = identity; + self.archive_attested = stamped && identity == before; + } + if self.archive_attested { + self.log.line("the archive file matches its verification stamp: the engine will not hash the copy again"); + } + Some(file) + } + Err(message) => return fail(1, format!("cannot seal the archive: {message}")), + } + } + (None, KarSource::File) => None, + }; + if self.stopping() { + return Err(Flow::Stopped); + } + + // 2. gateway (needed for the typed load) + self.set_phase(Phase::StartingGateway, "starting the gateway"); + let daemon_args = vec![ + "--config".to_owned(), + self.paths.daemon_config().display().to_string(), + ]; + let mut gateway = self.spawn( + "gateway", + &self.paths.bin("leleka-daemon"), + &daemon_args, + &BTreeMap::new(), + None, + )?; + self.pids[1] = gateway.id(); + let mut engine = match self.start_engine(&mut gateway).await { + Ok(engine) => engine, + Err(flow) => { + self.kill_children(&mut [Some(&mut gateway)]).await; + return Err(flow); + } + }; + + // 3. public API + self.set_phase(Phase::StartingApi, "starting the API"); + let api_args = vec![ + "serve".to_owned(), + "--config".to_owned(), + self.paths.strata_config().display().to_string(), + ]; + let mut api = match self.spawn( + "api", + &self.paths.bin("strata-next"), + &api_args, + &BTreeMap::new(), + None, + ) { + Ok(child) => child, + Err(flow) => { + self.kill_children(&mut [Some(&mut engine), Some(&mut gateway)]) + .await; + return Err(flow); + } + }; + self.pids[2] = api.id(); + if let Err(flow) = self.wait_api_ready(&mut api).await { + self.kill_children(&mut [Some(&mut api), Some(&mut engine), Some(&mut gateway)]) + .await; + return Err(flow); + } + self.set_phase(Phase::Ready, "ready"); + self.log.line(&format!( + "ready: http://{} model {} (profile {}, logs {})", + self.api_addr, + self.config.model_id, + self.config.profile.name, + self.paths.logs().display() + )); + let mut ready_since = Instant::now(); + // Gateway and API restarts in a row; like the engine's they are forgotten after a stable period, so that a service that + // runs for weeks is not ended by the sixth API crash of the month. + let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32); + let (mut gateway_since, mut api_since) = (Instant::now(), Instant::now()); + let stable = Duration::from_secs(self.config.restart.stable_after_s); + // `leleka reconfigure` leaves a request file; look for it once a second. + let mut requests = tokio::time::interval(Duration::from_secs(1)); + requests.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut logs_tick = tokio::time::interval(Duration::from_secs(10)); + logs_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let health = self.config.health.clone(); + let mut health_tick = tokio::time::interval(Duration::from_secs(health.interval_s.max(1))); + health_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut watchdog = watchdog::Watchdog::new(watchdog::Limits { + fail: Duration::from_secs(health.fail_s), + max_request: Duration::from_secs(health.max_request_s), + }); + + // 4. supervise + let result: Result<(), Flow> = loop { + tokio::select! { + _ = self.shutdown.changed() => break Ok(()), + _ = requests.tick() => { + let Some(taken) = reconfigure::take_request(&self.paths) else { continue }; + match taken { + Err(message) => { + self.log.line(&format!("reconfigure: {message}")); + self.answer("", reconfigure::State::Refused, message, false); + } + Ok(request) => match self.reconfigure(request, &mut engine, &mut gateway, &mut api).await { + Ok(()) => { + ready_since = Instant::now(); + watchdog.reset(); + } + Err(Flow::Stopped) => break Ok(()), + Err(flow) => break Err(flow), + }, + } + } + status = engine.wait() => { + let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); + self.log.event( + leleka_obs::Level::Warn, + "engine_exit", + &[("status", text.as_str().into()), ("restarts_total", self.restarts_total.into()), ("msg", "the API reports not-ready until the engine is back".into())], + ); + match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, format!("the engine process exited ({text})")).await { + Ok(()) => watchdog.reset(), + Err(Flow::Stopped) => break Ok(()), + Err(flow) => break Err(flow), + } + } + _ = logs_tick.tick() => { + self.enforce_logs(); + self.beats += 1; + if self.beats.is_multiple_of(3) { + self.heartbeat(); + } + } + _ = health_tick.tick(), if self.config.health.enabled => { + let sample = self.sample_health().await; + match watchdog.observe(Instant::now(), &sample) { + watchdog::Verdict::Healthy => self.note_health("healthy"), + watchdog::Verdict::Suspect(why) => { + if self.health_note != why { + self.log.event(leleka_obs::Level::Warn, "health", &[("finding", why.as_str().into())]); + } + self.note_health(&why); + } + watchdog::Verdict::RestartApi(why) => { + self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "api".into()), ("reason", why.as_str().into())]); + self.restarts_total += 1; + self.last_restart = Some((unix_now(), why)); + api_since = Instant::now(); + match self.restart_api(&mut api).await { + Ok(()) => watchdog.reset(), + Err(Flow::Stopped) => break Ok(()), + Err(flow) => break Err(flow), + } + } + watchdog::Verdict::RestartEngine(why) => { + self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "engine".into()), ("reason", why.as_str().into())]); + if let Err(flow) = self.hard_kill(&mut engine).await { + break Err(flow); + } + match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, why).await { + Ok(()) => watchdog.reset(), + Err(Flow::Stopped) => break Ok(()), + Err(flow) => break Err(flow), + } + } + } + } + status = gateway.wait() => { + let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); + if gateway_since.elapsed() >= stable { + gateway_restarts = 0; + } + gateway_restarts += 1; + self.log.event( + leleka_obs::Level::Warn, + "gateway_exit", + &[("status", text.as_str().into()), ("restart", gateway_restarts.into()), ("of", 3u32.into())], + ); + if gateway_restarts > 3 { + break fail(1, "the gateway keeps dying"); + } + if !self.pause(Duration::from_secs(2)).await { + break Ok(()); + } + gateway = self.spawn("gateway", &self.paths.bin("leleka-daemon"), &daemon_args, &BTreeMap::new(), None)?; + self.pids[1] = gateway.id(); + gateway_since = Instant::now(); + } + status = api.wait() => { + let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); + if api_since.elapsed() >= stable { + api_restarts = 0; + } + api_restarts += 1; + self.log.event( + leleka_obs::Level::Warn, + "api_exit", + &[("status", text.as_str().into()), ("restart", api_restarts.into()), ("of", 5u32.into())], + ); + if api_restarts > 5 { + break fail(1, "the API keeps dying"); + } + if !self.pause(Duration::from_secs(2)).await { + break Ok(()); + } + api = self.spawn("api", &self.paths.bin("strata-next"), &api_args, &BTreeMap::new(), None)?; + self.pids[2] = api.id(); + api_since = Instant::now(); + } + } + }; + + // 5. drain: API first so streams end with a terminal event, then the gateway and the engine. + self.set_phase(Phase::Draining, "draining"); + self.log.line("stopping: API, gateway, engine"); + self.kill_children(&mut [Some(&mut api), Some(&mut gateway), Some(&mut engine)]) + .await; + self.pids = [None; 3]; + result + } + + /// One look at `GET /metrics` (the control plane's own view of the worker and the active request) for the hang detector. + pub(super) async fn sample_health(&self) -> watchdog::Sample { + match http::get( + self.api_addr, + "/metrics", + Some(&self.api_key), + Duration::from_secs(5), + ) + .await + { + Ok(response) if response.status == 200 => watchdog::parse_metrics(&response.body), + Ok(response) => watchdog::Sample::Unreachable(format!("HTTP {}", response.status)), + Err(why) => watchdog::Sample::Unreachable(why), + } + } + + /// Keep the log directory bounded (`logs.rs`). + pub(super) fn enforce_logs(&self) { + let policy = logs::Policy { + limit: self + .config + .logs + .limit_mib + .saturating_mul(1 << 20) + .max(1 << 20), + keep: self.config.logs.keep, + }; + for (path, outcome) in logs::enforce(&self.paths.logs(), policy) { + match outcome { + Ok(true) => self.log.event( + leleka_obs::Level::Info, + "log_rotated", + &[("file", path.display().to_string().as_str().into())], + ), + Ok(false) => {} + Err(error) => self + .log + .line(&format!("cannot rotate {}: {error}", path.display())), + } + } + } +} diff --git a/crates/deploy/src/supervisor/tests.rs b/crates/deploy/src/supervisor/tests.rs new file mode 100644 index 00000000..d6e587fd --- /dev/null +++ b/crates/deploy/src/supervisor/tests.rs @@ -0,0 +1,97 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn utc_formatting() { + assert_eq!(format_utc(0), "1970-01-01T00:00:00Z"); + assert_eq!(format_utc(1_760_700_000), "2025-10-17T11:20:00Z"); + assert_eq!(format_utc(951_782_400), "2000-02-29T00:00:00Z"); +} + +#[test] +fn status_parsing_matches_the_gateway_document() { + let text = r#"{"schema_version":1,"runtimes":[{"id":"qwen-iq3","connected":true,"epoch":"e","loaded_handle":null,"model_ready":false,"configuration_action_required":false}]}"#; + assert_eq!(parse_runtime_status(text, "qwen-iq3"), Some((true, false))); + assert_eq!(parse_runtime_status(text, "other"), None); + assert_eq!(parse_runtime_status("not json", "qwen-iq3"), None); + let ready = text.replace("\"model_ready\":false", "\"model_ready\":true"); + assert_eq!(parse_runtime_status(&ready, "qwen-iq3"), Some((true, true))); +} + +#[test] +fn operation_records_are_parsed_from_the_cli_output() { + let load = "{\"operation_id\":\"0f0e\",\"epoch\":\"ab\",\"model\":\"qwen-iq3\"} +{ + \"state\": 1 +} +"; + assert_eq!(parse_operation(load), Some(("0f0e".into(), "ab".into()))); + assert_eq!(parse_operation("nothing"), None); + assert_eq!( + parse_operation_state( + "{ + \"state\": 3, + \"reason\": \"load_failed\" +}" + ), + Some(3) + ); + assert_eq!(parse_operation_state("Error: x"), None); + let dir = std::env::temp_dir().join(format!("leleka-tail-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("e.log"), + "a +b +c +d +", + ) + .unwrap(); + assert_eq!( + tail_of(&dir.join("e.log"), 2), + "c +d" + ); + assert_eq!(tail_of(&dir.join("missing.log"), 2), ""); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn token_rule() { + assert!(valid_token(&"a".repeat(32))); + assert!(!valid_token(&"a".repeat(31)) && !valid_token(&format!("{} b", "a".repeat(40)))); +} + +#[test] +fn log_rotation_keeps_one_generation() { + let dir = std::env::temp_dir().join(format!("leleka-rot-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("engine.log"); + std::fs::write(&log, vec![b'x'; 100]).unwrap(); + assert!(!rotate_log(&log, 1000).unwrap()); + assert!(rotate_log(&log, 50).unwrap()); + assert!(!log.exists() && dir.join("engine.log.1").exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn private_files_are_written_atomically_with_mode_0600() { + let dir = std::env::temp_dir().join(format!("leleka-priv-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("status.json"); + write_private(&file, "one").unwrap(); + write_private(&file, "two").unwrap(); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "two"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs deleted file mode 100644 index 06cc641e..00000000 --- a/crates/deploy/tests/e2e.rs +++ /dev/null @@ -1,2120 +0,0 @@ -//! Black-box and flow tests with a test double for the runtime programs (no GPU, no model). -//! Run with `cargo test -p leleka-deploy --features test-fakes`. -#![cfg(all(target_os = "linux", feature = "test-fakes"))] - -use leleka_deploy::{ - app::run_up, - cli::{Command, Environment, UpOptions, parse}, - config::{GATEWAY_TOKEN_ENV, Ports, RUNTIME_TOKEN_ENV, RunConfig, to_file_text}, - facts::{DirFact, Gpu, Memory}, - layout::{BINARIES, Dirs, MTP_FILES}, - plan::{Context, FsState, gather, plan_steps}, - preflight::evaluate, - profile::{KarSource, Profile}, - steps::gather_fs, -}; -use std::{ - collections::BTreeMap, - fs, - net::TcpListener, - os::unix::fs::{PermissionsExt, symlink}, - path::{Path, PathBuf}, - process::{Child, Command as Process, Stdio}, - time::{Duration, Instant}, -}; - -const FAKE: &str = env!("CARGO_BIN_EXE_leleka-fake-runtime"); -const LELEKA: &str = env!("CARGO_BIN_EXE_leleka"); -const KEY: &str = "fake-api-key-0123456789abcdef0123456789abcdef"; - -/// A port from the range below the ephemeral one (32768+), so that the source ports of the many short -/// connections the tests make cannot collide with a port a fixture reserved but has not bound yet. -fn free_port() -> u16 { - use std::sync::atomic::{AtomicU16, Ordering}; - static NEXT: AtomicU16 = AtomicU16::new(0); - loop { - let step = NEXT.fetch_add(1, Ordering::Relaxed); - let candidate = 20_000 - + ((std::process::id() as u16) - .wrapping_mul(31) - .wrapping_add(step.wrapping_mul(7))) - % 9_000; - if TcpListener::bind(("127.0.0.1", candidate)).is_ok() { - return candidate; - } - } -} - -struct Fixture { - root: PathBuf, - dirs: Dirs, - ports: Ports, -} - -impl Fixture { - fn new(name: &str) -> Fixture { - let root = std::env::temp_dir().join(format!("leleka-e2e-{}-{name}", std::process::id())); - let _ = fs::remove_dir_all(&root); - fs::create_dir_all(&root).unwrap(); - let dirs = Dirs { - prefix: root.join("prefix"), - state: root.join("state"), - assets: root.join("assets"), - }; - let ports = Ports { - api: format!("127.0.0.1:{}", free_port()), - engine: format!("127.0.0.1:{}", free_port()), - daemon: format!("127.0.0.1:{}", free_port()), - }; - Fixture { root, dirs, ports } - } - - fn fake_dir(&self) -> PathBuf { - self.dirs.prefix.join("fake") - } - - /// `PREFIX/bin` with the real `leleka` and fakes for the other five (symlinks named like the programs). - fn install_fake_binaries(&self, bin: &Path) { - fs::create_dir_all(bin).unwrap(); - for name in BINARIES { - let target = if name == "leleka" { LELEKA } else { FAKE }; - let _ = fs::remove_file(bin.join(name)); - symlink(target, bin.join(name)).unwrap(); - } - } - - fn write_state(&self, profile: Profile) -> PathBuf { - let paths = self.dirs.paths(); - fs::create_dir_all(paths.logs()).unwrap(); - fs::create_dir_all(paths.run_dir()).unwrap(); - fs::write( - paths.env_file(), - format!( - "{RUNTIME_TOKEN_ENV}={}\n{GATEWAY_TOKEN_ENV}={}\n", - "r".repeat(40), - "g".repeat(40) - ), - ) - .unwrap(); - fs::write(paths.api_key(), KEY).unwrap(); - let mut config = - RunConfig::new(&self.dirs, self.ports.clone(), 0, profile, BTreeMap::new()); - config.shutdown_grace_s = 2; - // The flow tests are not about the expert tier (it has no table here): it is off on purpose, as after `--no-expert-tier`. - config.expert_tier = false; - fs::write(paths.run_config(), to_file_text(&config)).unwrap(); - fs::write(paths.daemon_config(), to_file_text(&config.daemon_json())).unwrap(); - fs::write(paths.strata_config(), to_file_text(&config.strata_json())).unwrap(); - paths.run_config() - } - - fn status(&self) -> Option { - fs::read_to_string(self.dirs.paths().status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()) - } - - fn wait_for( - &self, - what: &str, - limit: Duration, - mut done: impl FnMut(&serde_json::Value) -> bool, - ) -> serde_json::Value { - let started = Instant::now(); - loop { - if let Some(status) = self.status() - && done(&status) - { - return status; - } - assert!( - started.elapsed() < limit, - "timed out waiting for {what}; status {:?}; logs:\n{}", - self.status(), - self.logs() - ); - std::thread::sleep(Duration::from_millis(200)); - } - } - - fn logs(&self) -> String { - let mut out = String::new(); - if let Ok(entries) = fs::read_dir(self.dirs.paths().logs()) { - for entry in entries.flatten() { - out.push_str(&format!( - "--- {} ---\n{}\n", - entry.path().display(), - fs::read_to_string(entry.path()).unwrap_or_default() - )); - } - } - out - } - - fn http_status(&self, path: &str) -> u16 { - use std::io::{Read, Write}; - let Ok(mut stream) = std::net::TcpStream::connect(&self.ports.api) else { - return 0; - }; - let _ = stream.set_read_timeout(Some(Duration::from_secs(3))); - write!(stream, "GET {path} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {KEY}\r\nConnection: close\r\n\r\n").unwrap(); - let mut text = String::new(); - let _ = stream.read_to_string(&mut text); - text.split_whitespace() - .nth(1) - .and_then(|s| s.parse().ok()) - .unwrap_or(0) - } -} - -impl Drop for Fixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.root); - } -} - -fn signal(pid: u64, name: &str) { - let _ = Process::new("kill") - .arg(format!("-{name}")) - .arg(pid.to_string()) - .status(); -} - -fn pid_alive(pid: u64) -> bool { - Path::new(&format!("/proc/{pid}")).exists() - && fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| !s.contains(") Z ")) -} - -fn wait_exit(child: &mut Child, limit: Duration) -> Option { - let started = Instant::now(); - while started.elapsed() < limit { - if let Some(status) = child.try_wait().unwrap() { - return Some(status); - } - std::thread::sleep(Duration::from_millis(100)); - } - None -} - -/// Make a sealed memfd that `leleka run` inherits (no close-on-exec). -fn inheritable_sealed_memfd(bytes: &[u8]) -> fs::File { - use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; - use std::io::Write; - let mut file = fs::File::from(memfd_create("test-archive", MemfdFlags::ALLOW_SEALING).unwrap()); - file.write_all(bytes).unwrap(); - fcntl_add_seals( - &file, - SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL, - ) - .unwrap(); - file -} - -fn start_supervisor(fixture: &Fixture, config: &Path, kar_fd: Option) -> Child { - start_supervisor_with_env(fixture, config, kar_fd, &[]) -} - -fn start_supervisor_with_env( - fixture: &Fixture, - config: &Path, - kar_fd: Option, - env: &[(&str, &str)], -) -> Child { - let mut command = Process::new(LELEKA); - command.arg("run").arg("--config").arg(config); - command.envs(env.iter().copied()); - if let Some(fd) = kar_fd { - command.arg("--kar-fd").arg(fd.to_string()); - } - // A token in the environment of the supervisor must not reach any child. - command - .env("HF_TOKEN", "hf_test_value_that_must_not_leak") - .stdin(Stdio::null()); - let log = fs::File::create(fixture.root.join("supervisor.out")).unwrap(); - command.stdout(log.try_clone().unwrap()).stderr(log); - command.spawn().unwrap() -} - -fn lifecycle(source: KarSource) { - let fixture = Fixture::new(match source { - KarSource::Memfd => "memfd", - KarSource::File => "file", - KarSource::None => "none", - }); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = source; - let config = fixture.write_state(profile); - let paths = fixture.dirs.paths(); - let memfd = (source == KarSource::Memfd).then(|| inheritable_sealed_memfd(&vec![7u8; 100_000])); - if source == KarSource::File { - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(paths.kar(), b"archive").unwrap(); - } - let fd = memfd.as_ref().map(std::os::fd::AsRawFd::as_raw_fd); - let mut supervisor = start_supervisor(&fixture, &config, fd); - - let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); - assert_eq!(ready["engine_restarts"], 0); - assert_eq!(fixture.http_status("/ready"), 200); - let (engine_pid, gateway_pid, api_pid) = ( - ready["engine_pid"].as_u64().unwrap(), - ready["gateway_pid"].as_u64().unwrap(), - ready["api_pid"].as_u64().unwrap(), - ); - let engine_log = fs::read_to_string(paths.logs().join("engine.log")).unwrap(); - match source { - KarSource::Memfd => assert!(engine_log.contains("kar fd "), "{engine_log}"), - KarSource::File => assert!(engine_log.contains("listening"), "{engine_log}"), - KarSource::None => {} - } - // The status file is private and never holds a secret. - let mode = fs::metadata(paths.status_file()) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o600); - assert!( - !fs::read_to_string(paths.status_file()) - .unwrap() - .contains(KEY) - ); - - // Kill the engine: the API reports not ready, the supervisor restarts it and loads again. - signal(engine_pid, "KILL"); - let again = fixture.wait_for("engine restart", Duration::from_secs(60), |s| { - s["phase"] == "ready" && s["engine_restarts"] == 1 - }); - assert_ne!(again["engine_pid"].as_u64().unwrap(), engine_pid); - assert_eq!( - again["gateway_pid"].as_u64().unwrap(), - gateway_pid, - "the gateway must survive an engine restart" - ); - assert_eq!( - again["api_pid"].as_u64().unwrap(), - api_pid, - "the API must survive an engine restart" - ); - assert_eq!(fixture.http_status("/ready"), 200); - let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); - assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}"); - assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}"); - // The first engine hashed the sealed archive; the restarted one is told the same memfd was verified already - // (stamps are on by default), and both get the stamp directory. - let starts: Vec<&str> = calls - .lines() - .filter(|l| l.starts_with("leleka-inference ")) - .collect(); - assert!( - starts.iter().all(|l| l.contains("--verify-stamps")), - "{calls}" - ); - assert!( - !starts[0].contains("--kar-attested-by-stamp"), - "{}", - starts[0] - ); - assert_eq!( - starts[1].contains("--kar-attested-by-stamp"), - source == KarSource::Memfd, - "{}", - starts[1] - ); - // The sealed descriptor was reused, not copied again (one process held it the whole time). - assert!(!supervisor.try_wait().unwrap().is_some()); - - // SIGTERM drains and stops everything with status 0. - let new_engine = again["engine_pid"].as_u64().unwrap(); - signal(u64::from(supervisor.id()), "TERM"); - let status = wait_exit(&mut supervisor, Duration::from_secs(60)) - .expect("the supervisor must exit after SIGTERM"); - assert!(status.success(), "exit {status:?}\n{}", fixture.logs()); - assert_eq!(fixture.status().unwrap()["phase"], "stopped"); - for pid in [new_engine, gateway_pid, api_pid] { - assert!(!pid_alive(pid), "pid {pid} outlived the supervisor"); - } - assert_eq!( - fixture.http_status("/ready"), - 0, - "the API port must be closed" - ); - // No child ever saw the Hugging Face token (the fake engine exits 3 if it does). - assert!( - !fs::read_to_string(paths.logs().join("engine.log")) - .unwrap() - .contains("leaked") - ); -} - -#[test] -fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() { - lifecycle(KarSource::Memfd); -} - -/// `memfd_extents: ple_only` profile of the test double (the laptop profile with a sealed memfd and an explicit prefix cap). -fn sparse_profile() -> Profile { - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::Memfd; - profile.memfd_extents = leleka_deploy::profile::MemfdExtents::PleOnly; - profile.memory.prefix_cache_mib = Some("4096".into()); - profile.validate().unwrap(); - profile -} - -#[test] -fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims_the_archive_was_verified() - { - let fixture = Fixture::new("sparse"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let config = fixture.write_state(sparse_profile()); - let paths = fixture.dirs.paths(); - let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); - let pin = "ab".repeat(32); - let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; - let expected: String = if compiled == [0u8; 32] { - pin.clone() - } else { - compiled.iter().map(|b| format!("{b:02x}")).collect() - }; - let mut supervisor = start_supervisor_with_env( - &fixture, - &config, - Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), - &[("LELEKA_KAR_EXTENTS_SHA256", &pin)], - ); - let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); - assert_eq!(ready["memfd_extents"], "ple_only"); - signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); - fixture.wait_for("engine restart", Duration::from_secs(60), |s| { - s["phase"] == "ready" && s["engine_restarts"] == 1 - }); - let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); - let starts: Vec<&str> = calls - .lines() - .filter(|l| l.starts_with("leleka-inference ")) - .collect(); - assert_eq!(starts.len(), 2, "{calls}"); - for (i, line) in starts.iter().enumerate() { - assert!( - line.contains(&format!("--kar-sparse-extents-sha256 {expected}")), - "engine {i}: {line}" - ); - assert!(line.contains("--kar-archive-fd"), "{line}"); - // the memfd is not the archive: no attestation by a stamp of the archive file, not even for the restarted engine - assert!( - !line.contains("--kar-attested-by-stamp"), - "engine {i}: {line}" - ); - } - // and no stamp of the archive was recorded from it - let stamps: Vec = fs::read_dir(paths.stamps()) - .map(|d| { - d.flatten() - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect() - }) - .unwrap_or_default(); - assert!( - !stamps.iter().any(|name| name.starts_with("kar")), - "{stamps:?}" - ); - let log = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap_or_default() - + &fixture.logs(); - // (the sparse memfd was EXPERIMENTAL until it became the rtx5090-32g form; the digest line is the contract) - assert!(log.contains(&expected), "{log}"); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), - "{}", - fixture.logs() - ); -} - -#[test] -fn a_sparse_memfd_profile_starts_on_the_compiled_digest_and_refuses_when_none_is_pinned() { - let fixture = Fixture::new("sparse-nopin"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let config = fixture.write_state(sparse_profile()); - let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); - let mut supervisor = start_supervisor_with_env( - &fixture, - &config, - Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), - &[], - ); - if leleka_model_format::kar::PLE_EXTENTS_SHA256 != [0u8; 32] { - // the extents digest is pinned in the binary (the release form): no operator pin is needed and the supervisor starts - fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), - "{}", - fixture.logs() - ); - return; - } - let status = - wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must refuse"); - { - assert_eq!(status.code(), Some(1)); - let message = fixture.status().unwrap()["message"] - .as_str() - .unwrap() - .to_owned(); - assert!( - message.contains("kar_census") && message.contains("--hash-extents"), - "{message}" - ); - // no engine was started - let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default(); - assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}"); - } -} - -#[test] -fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_cannot_seal() { - let dir = std::env::temp_dir().join(format!("leleka-seal-exec-{}", std::process::id())); - fs::create_dir_all(&dir).unwrap(); - let file = dir.join("archive.bin"); - let bytes: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); - fs::write(&file, &bytes).unwrap(); - let run = |extra: &[&str]| { - Process::new(LELEKA) - .args(["seal-exec", "--file"]) - .arg(&file) - .args(extra) - .output() - .unwrap() - }; - let ok = run(&[ - "--expect-bytes", - "300000", - "--", - "sh", - "-c", - "wc -c < /proc/self/fd/{FD}; readlink /proc/self/fd/{FD}; cksum < /proc/self/fd/{FD}", - ]); - let out = String::from_utf8_lossy(&ok.stdout); - assert!( - ok.status.success(), - "{}{}", - out, - String::from_utf8_lossy(&ok.stderr) - ); - assert!( - out.contains("300000") && out.contains("/memfd:leleka-sealed-archive"), - "{out}" - ); - let want = Process::new("cksum") - .stdin(fs::File::open(&file).unwrap()) - .output() - .unwrap(); - assert!( - out.contains(String::from_utf8_lossy(&want.stdout).trim()), - "the descriptor holds the file byte for byte: {out}" - ); - // a wrong length, a missing command and the sparse form without its length are refused (exit 2), nothing is run - for extra in [ - vec!["--expect-bytes", "1", "--", "true"], - vec!["--expect-bytes", "300000"], - vec!["--sparse-ple", "--", "true"], - ] { - let refused = run(&extra); - assert_eq!( - refused.status.code(), - Some(2), - "{extra:?}: {}", - String::from_utf8_lossy(&refused.stderr) - ); - } - // a file that is not a KAR archive cannot be sealed sparse - let sparse = run(&["--sparse-ple", "--expect-bytes", "300000", "--", "true"]); - assert_eq!(sparse.status.code(), Some(2)); - assert!( - String::from_utf8_lossy(&sparse.stderr).contains("not a valid KAR archive"), - "{}", - String::from_utf8_lossy(&sparse.stderr) - ); - fs::remove_dir_all(&dir).unwrap(); -} - -#[test] -fn supervisor_lifecycle_with_a_read_only_archive_file() { - lifecycle(KarSource::File); -} - -/// Rewrite `leleka.json` with `change` applied (the fixture writes the defaults). -fn tune(config: &Path, change: impl FnOnce(&mut serde_json::Value)) { - let mut value: serde_json::Value = - serde_json::from_str(&fs::read_to_string(config).unwrap()).unwrap(); - change(&mut value); - fs::write(config, serde_json::to_string_pretty(&value).unwrap()).unwrap(); -} - -fn file_profile() -> Profile { - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::File; - profile -} - -#[test] -fn a_hung_engine_is_killed_and_restarted_by_the_health_check() { - // `max_request_s` is 3 here; the fake API reports a request that has been active for 600 s. - let fixture = Fixture::new("hang"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - tune(&config, |c| { - c["health"] = - serde_json::json!({"enabled": true, "interval_s": 1, "fail_s": 30, "max_request_s": 3}); - c["restart"]["backoff_initial_s"] = serde_json::json!(1); - }); - let mut supervisor = start_supervisor(&fixture, &config, None); - let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - assert_eq!(ready["restarts_total"], 0); - let hung_pid = ready["engine_pid"].as_u64().unwrap(); - // The process lives and the API answers, but a request has been active for ten minutes. - fs::write(fixture.fake_dir().join("hang-decode"), "").unwrap(); - let again = fixture.wait_for("restart after the stall", Duration::from_secs(60), |s| { - s["phase"] == "ready" - && s["restarts_total"] == 1 - && s["engine_pid"].as_u64() != Some(hung_pid) - }); - let reason = again["last_restart_reason"].as_str().unwrap(); - assert!( - reason.contains("request has been active") && reason.contains("600"), - "{reason}" - ); - assert!(!pid_alive(hung_pid), "the hung engine must be gone"); - // The fake reports the hang once; afterwards the new engine is judged healthy. - let healthy = fixture.wait_for("healthy again", Duration::from_secs(30), |s| { - s["health"] == "healthy" - }); - assert_eq!( - healthy["restarts_total"], 1, - "no second restart without a second stall" - ); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); -} - -#[test] -fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() { - let fixture = Fixture::new("backoff"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - tune(&config, |c| { - c["health"]["enabled"] = serde_json::json!(false); - c["restart"] = serde_json::json!({"max_engine_restarts": 3, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); - }); - let mut supervisor = start_supervisor(&fixture, &config, None); - let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - // Crash it and make every restart fail: three attempts in a row, then the service ends with a message. - fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); - signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); - let status = - wait_exit(&mut supervisor, Duration::from_secs(90)).expect("the supervisor must give up"); - assert_eq!(status.code(), Some(1)); - let state = fixture.status().unwrap(); - assert_eq!(state["phase"], "failed"); - let message = state["message"].as_str().unwrap(); - assert!(message.contains("failed 3 times in a row"), "{message}"); - assert_eq!(state["restarts_total"], 1); - let log = fs::read_to_string(fixture.dirs.paths().logs().join("leleka.log")).unwrap(); - assert!( - log.matches("the engine did not come back").count() >= 3, - "{log}" - ); - - // A restart that fails once and then works is just a slower restart. - let fixture = Fixture::new("backoff2"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - tune(&config, |c| { - c["health"]["enabled"] = serde_json::json!(false); - c["restart"] = serde_json::json!({"max_engine_restarts": 5, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); - }); - let mut supervisor = start_supervisor(&fixture, &config, None); - let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); - signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); - fixture.wait_for("restart attempts", Duration::from_secs(30), |s| { - s["phase"] == "engine_restarting" - }); - std::thread::sleep(Duration::from_millis(2500)); - fs::remove_file(fixture.fake_dir().join("fail-engine")).unwrap(); - let again = fixture.wait_for("recovered", Duration::from_secs(60), |s| { - s["phase"] == "ready" && s["restarts_total"] == 1 - }); - assert!(again["engine_restarts"].as_u64().unwrap() >= 2, "{again}"); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); -} - -#[test] -fn logs_past_their_limit_are_rotated_while_the_service_runs() { - let fixture = Fixture::new("logs"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - tune(&config, |c| { - c["logs"] = serde_json::json!({"limit_mib": 1, "keep": 2}) - }); - let big = fixture.dirs.paths().logs().join("api.log"); - fs::write(&big, "x".repeat(300) + "\n").unwrap(); - { - use std::io::Write; - let mut file = fs::OpenOptions::new().append(true).open(&big).unwrap(); - for _ in 0..(3 << 20) / 100 { - writeln!(file, "{}", "y".repeat(99)).unwrap(); - } - } - let mut supervisor = start_supervisor(&fixture, &config, None); - fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - let rotated = fixture.dirs.paths().logs().join("api.log.1"); - let started = Instant::now(); - while !rotated.exists() && started.elapsed() < Duration::from_secs(30) { - std::thread::sleep(Duration::from_millis(200)); - } - assert!(rotated.exists(), "{}", fixture.logs()); - assert!(fs::metadata(&rotated).unwrap().len() <= 1 << 20); - assert!(fs::metadata(&big).unwrap().len() < 1 << 20); - let doc = fixture.status().unwrap(); - assert!(doc["log_bytes"].as_u64().unwrap() > 0); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); -} - -#[test] -fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model() { - let fixture = Fixture::new("quick"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - let paths = fixture.dirs.paths(); - fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap(); - for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] { - fs::File::create(paths.shard(index)) - .unwrap() - .set_len(size) - .unwrap(); - } - fs::File::create(paths.kar()) - .unwrap() - .set_len(55_295_529_472) - .unwrap(); - let quick = || { - Process::new(LELEKA) - .args(["verify", "--quick", "--state-dir"]) - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--assets") - .arg(&fixture.dirs.assets) - .output() - .unwrap() - }; - // Not running: the files are there (unstamped, a note), the service is not (a problem). - let before = quick(); - let text = String::from_utf8_lossy(&before.stdout).into_owned(); - assert_eq!(before.status.code(), Some(1), "{text}"); - assert!( - text.contains("not stamped") - && text.contains("PROBLEM: the API does not answer") - && text.contains("health: NOT OK"), - "{text}" - ); - // Running: healthy. - let mut supervisor = start_supervisor(&fixture, &config, None); - fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - let after = quick(); - let text = String::from_utf8_lossy(&after.stdout).into_owned(); - assert_eq!(after.status.code(), Some(0), "{text}"); - assert!( - text.contains("health: OK") - && text.contains("API answers /ready: yes") - && text.contains("engine restarts 0 in total"), - "{text}" - ); - // `leleka status` shows the same supervisor facts. - let status = Process::new(LELEKA) - .args(["status", "--state-dir"]) - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--assets") - .arg(&fixture.dirs.assets) - .output() - .unwrap(); - let text = String::from_utf8_lossy(&status.stdout).into_owned(); - assert!( - text.contains("supervisor: phase ready") && text.contains("health: "), - "{text}" - ); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); -} - -#[test] -fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone() { - let fixture = Fixture::new("sidecars"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - tune(&config, |c| { - c["health"]["enabled"] = serde_json::json!(false) - }); - let mut supervisor = start_supervisor(&fixture, &config, None); - let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); - let (engine, gateway, api) = ( - ready["engine_pid"].as_u64().unwrap(), - ready["gateway_pid"].as_u64().unwrap(), - ready["api_pid"].as_u64().unwrap(), - ); - signal(api, "KILL"); - let after_api = fixture.wait_for("a new API", Duration::from_secs(30), |s| { - s["api_pid"].as_u64().is_some_and(|p| p != api) && s["phase"] == "ready" - }); - assert_eq!(after_api["engine_pid"].as_u64(), Some(engine)); - assert_eq!( - after_api["restarts_total"], 0, - "an API restart is not an engine restart" - ); - signal(gateway, "KILL"); - let after_gateway = fixture.wait_for("a new gateway", Duration::from_secs(30), |s| { - s["gateway_pid"].as_u64().is_some_and(|p| p != gateway) - }); - assert_eq!(after_gateway["engine_pid"].as_u64(), Some(engine)); - let started = Instant::now(); - while fixture.http_status("/ready") != 200 && started.elapsed() < Duration::from_secs(30) { - std::thread::sleep(Duration::from_millis(200)); - } - assert_eq!(fixture.http_status("/ready"), 200); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); -} - -#[test] -fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() { - let fixture = Fixture::new("fail"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::File; - let config = fixture.write_state(profile); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - let mut supervisor = start_supervisor(&fixture, &config, None); - let status = - wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up"); - assert_eq!(status.code(), Some(1)); - let state = fixture.status().unwrap(); - assert_eq!(state["phase"], "failed"); - let message = state["message"].as_str().unwrap(); - assert!( - message.contains("engine") && message.contains("exited"), - "{message}" - ); - let output = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap(); - assert!(output.contains("fatal:"), "{output}"); - // The gateway started for the load is not left behind. - assert!(state["gateway_pid"].is_null() || !pid_alive(state["gateway_pid"].as_u64().unwrap())); -} - -#[test] -fn a_refused_load_fails_fast_and_shows_the_engine_log() { - // The real engine stays alive when its load fails; only the operation record says so. - let fixture = Fixture::new("refused"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - fs::write(fixture.fake_dir().join("fail-load"), "").unwrap(); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::File; - let config = fixture.write_state(profile); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); - let started = Instant::now(); - let mut supervisor = start_supervisor(&fixture, &config, None); - let status = - wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up"); - assert_eq!(status.code(), Some(1)); - assert!( - started.elapsed() < Duration::from_secs(40), - "a refused load must not wait for the load timeout" - ); - let state = fixture.status().unwrap(); - let message = state["message"].as_str().unwrap(); - assert!( - message.contains("refused the load") && message.contains("BackendUnavailable"), - "{message}" - ); - // The engine it started is gone. - let engine_pid = fs::read_to_string(fixture.fake_dir().join("engine.pid")) - .unwrap() - .trim() - .parse() - .unwrap(); - assert!(!pid_alive(engine_pid)); -} - -#[test] -fn verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure() { - let fixture = Fixture::new("verify"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::File; - fixture.write_state(profile); - let run = |fixture: &Fixture| { - Process::new(LELEKA) - .arg("verify") - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--assets") - .arg(&fixture.dirs.assets) - .output() - .unwrap() - }; - let output = run(&fixture); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); - let line = calls - .lines() - .find(|l| l.starts_with("leleka-inference ")) - .unwrap(); - assert!( - line.contains("--verify-only") - && line.contains("--verify-rehash") - && line.contains("--verify-stamps"), - "{line}" - ); - // The file profile hands the archive to the engine (which stamps it itself) and no serving switches. - assert!( - line.contains("--kar-archive-file") && !line.contains("--backend-mode"), - "{line}" - ); - assert!(fixture.dirs.paths().engine_stamps().is_dir()); - fs::write(fixture.fake_dir().join("fail-verify"), "").unwrap(); - let output = run(&fixture); - assert_eq!(output.status.code(), Some(1)); - assert!(String::from_utf8_lossy(&output.stderr).contains("verification FAILED")); -} - -#[test] -fn a_broken_configuration_is_exit_code_two_with_a_clear_message() { - let fixture = Fixture::new("badconfig"); - fs::create_dir_all(&fixture.root).unwrap(); - let missing = fixture.root.join("nope.json"); - let output = Process::new(LELEKA) - .arg("run") - .arg("--config") - .arg(&missing) - .output() - .unwrap(); - assert_eq!(output.status.code(), Some(2)); - let text = String::from_utf8_lossy(&output.stderr); - assert!(text.contains("run `leleka up` first"), "{text}"); - // Weak tokens are refused before anything starts. - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::File; - let config = fixture.write_state(profile); - fs::write( - fixture.dirs.paths().env_file(), - format!("{RUNTIME_TOKEN_ENV}=short\n{GATEWAY_TOKEN_ENV}=short\n"), - ) - .unwrap(); - let output = Process::new(LELEKA) - .arg("run") - .arg("--config") - .arg(&config) - .output() - .unwrap(); - assert_eq!(output.status.code(), Some(2)); - assert!(String::from_utf8_lossy(&output.stderr).contains("32..4096 printable ASCII")); -} - -// ----------------------------------------------------------------------------------------------------------- -// the `up` flow - -/// `up` options of the 3080 profile with the expert tier switched off on purpose: the flow tests must not download -/// the real table. The tier itself is covered by `up_installs_the_expert_profile_offline_and_reports_it`. -fn up_options( - fixture: &Fixture, - bin_src: &Path, - cublas: &Path, - mtp: &Path, - extra: &[&str], -) -> UpOptions { - let mut all = vec!["--no-expert-tier"]; - all.extend_from_slice(extra); - up_options_with(fixture, bin_src, cublas, mtp, "rtx3080-16g", &all) -} - -fn up_options_with( - fixture: &Fixture, - bin_src: &Path, - cublas: &Path, - mtp: &Path, - profile: &str, - extra: &[&str], -) -> UpOptions { - let var = |_: &str| None; - let args: Vec = [ - "up", - "--assets", - &fixture.dirs.assets.display().to_string(), - "--state-dir", - &fixture.dirs.state.display().to_string(), - "--prefix", - &fixture.dirs.prefix.display().to_string(), - "--bin-src", - &bin_src.display().to_string(), - "--cublas-dir", - &cublas.display().to_string(), - "--mtp-pack", - &mtp.display().to_string(), - "--api-port", - fixture.ports.api.rsplit(':').next().unwrap(), - "--engine-port", - fixture.ports.engine.rsplit(':').next().unwrap(), - "--daemon-port", - fixture.ports.daemon.rsplit(':').next().unwrap(), - "--profile", - profile, - "--mode", - "none", - ] - .iter() - .map(|s| s.to_string()) - .chain(extra.iter().map(|s| s.to_string())) - .collect(); - match parse( - &args, - &Environment { - root: false, - home: Some(fixture.root.clone()), - var: &var, - }, - ) - .unwrap() - { - Command::Up(options) => options, - _ => unreachable!(), - } -} - -/// A host that passes the preflight, whatever machine runs the test. -fn healthy_context(opts: &UpOptions) -> Context { - let mut ctx = gather(opts, &|_| None); - let gpu = Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15500, - sm: Some(86), - }; - ctx.facts.os = "linux".into(); - ctx.facts.arch = "x86_64".into(); - ctx.facts.gpus = vec![gpu]; - ctx.facts.memory = Memory { - total: 39 << 30, - available: 37 << 30, - swap_total: 0, - }; - ctx.facts.proc_fd = true; - ctx.facts.memfd_ok = true; - ctx.facts.busy_ports.clear(); - ctx.facts.libs.insert( - "libcuda.so.1".into(), - Some("/usr/lib/wsl/lib/libcuda.so.1".into()), - ); - for key in ["assets", "state", "prefix"] { - ctx.facts.dirs.insert( - key.into(), - DirFact { - path: PathBuf::from("/x"), - free_bytes: Some(2 << 40), - fs_type: Some("ext4".into()), - }, - ); - } - ctx.needs.binary_has_sm86 = Some(true); - let profile = ctx.profile.as_ref().unwrap().clone(); - ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs)); - assert!( - !ctx.report.as_ref().unwrap().failed(), - "{}", - ctx.report.as_ref().unwrap().render() - ); - ctx -} - -fn fake_libraries(dir: &Path) { - fs::create_dir_all(dir).unwrap(); - fs::write(dir.join("libcublas.so.12"), b"x").unwrap(); - fs::write(dir.join("libcublasLt.so.12"), b"x").unwrap(); -} - -fn mtp_source(dir: &Path) { - fs::create_dir_all(dir).unwrap(); - for name in MTP_FILES { - fs::write(dir.join(name), b"pack").unwrap(); - } -} - -fn count_calls(fixture: &Fixture, needle: &str) -> usize { - fs::read_to_string(fixture.fake_dir().join("calls.log")) - .unwrap_or_default() - .matches(needle) - .count() -} - -#[tokio::test] -async fn up_is_idempotent_resumable_and_never_rotates_secrets() { - let fixture = Fixture::new("up"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - // The fakes find their shared state through the *installed* bin directory. - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); - let paths = fixture.dirs.paths(); - - // First run: everything is a todo, then everything exists. - let ctx = healthy_context(&opts); - let fs0 = gather_fs(&ctx).await; - let steps = plan_steps(&ctx, &fs0); - assert!( - steps - .iter() - .filter(|s| matches!( - s.id, - "binaries" | "secrets" | "model" | "kar" | "tokenizer" | "config" | "mtp-pack" - )) - .all(|s| s.state.tag() == "todo") - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - for (what, file) in [ - ("binary", paths.bin("leleka-inference")), - ("run config", paths.run_config()), - ("env", paths.env_file()), - ("api key", paths.api_key()), - ("tokenizer", paths.tokenizer_dir()), - ("mtp", paths.mtp_pack().join("experts.bin")), - ("stamp", paths.stamps().join("model.json")), - ] { - assert!(file.exists(), "{what}: {} missing", file.display()); - } - assert_eq!( - fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777, - 0o600 - ); - assert_eq!( - fs::metadata(paths.kar()).unwrap().permissions().mode() & 0o222, - 0, - "the file-mode archive must have no write bits" - ); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!(config.profile.name, "rtx3080-16g"); - let env_first = fs::read_to_string(paths.env_file()).unwrap(); - assert!( - env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())), - "{env_first}" - ); - assert_eq!( - ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "api-key init") - ), - (0, 1, 1), - "the archive step fetches and verifies the shards itself" - ); - - // Second run: the plan has nothing to do and no tool is invoked again. - let ctx = healthy_context(&opts); - let fs1 = gather_fs(&ctx).await; - let steps = plan_steps(&ctx, &fs1); - for step in &steps { - assert!( - matches!(step.state.tag(), "done" | "skip") || step.id == "preflight", - "{} is {:?} on a re-run", - step.id, - step.state - ); - } - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!( - ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "model verify"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "extract-tokenizer") - ), - (0, 0, 1, 1) - ); - assert_eq!( - fs::read_to_string(paths.env_file()).unwrap(), - env_first, - "tokens must never rotate" - ); - - // Resumable: a lost archive is rebuilt, everything else is left alone. - fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap(); - fs::remove_file(paths.kar()).unwrap(); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps.iter().find(|s| s.id == "kar").unwrap().state.tag(), - "todo" - ); - assert_eq!( - steps.iter().find(|s| s.id == "model").unwrap().state.tag(), - "done" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!( - ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed") - ), - (0, 2) - ); - - // --reverify forces the verification again. - let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]); - let ctx = healthy_context(&reverify); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps.iter().find(|s| s.id == "model").unwrap().state.tag(), - "todo" - ); - let _ = FsState::default(); -} - -#[tokio::test] -async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() { - let fixture = Fixture::new("trust"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &["--trust-archive"]); - let paths = fixture.dirs.paths(); - // An archive of the pinned length with its provenance sidecar, as left by an earlier build. - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::File::create(paths.kar()) - .unwrap() - .set_len(55_295_529_472) - .unwrap(); - fs::write(paths.kar_provenance(), "{}").unwrap(); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let kar = steps.iter().find(|s| s.id == "kar").unwrap(); - assert_eq!(kar.state.tag(), "todo"); - assert!( - kar.state.why().contains("--trust-archive"), - "{:?}", - kar.state - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!( - ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "model verify"), - count_calls(&fixture, "ensure-sharded-streamed") - ), - (1, 1, 0) - ); - assert!(paths.stamps().join("kar.json").exists() && paths.stamps().join("model.json").exists()); - // Without the flag the same archive would be re-verified by the real tool. - let strict = healthy_context(&up_options( - &fixture, - &bin_src, - &cublas, - &mtp, - &["--reverify"], - )); - let steps = plan_steps(&strict, &gather_fs(&strict).await); - assert!( - !steps - .iter() - .find(|s| s.id == "kar") - .unwrap() - .state - .why() - .contains("--trust-archive") - ); -} - -#[tokio::test] -async fn up_installs_the_expert_profile_offline_and_reports_it() { - use leleka_deploy::expert_profile::{ - FileState, PROFILE_ENV, file_state, sha256_hex, tier_report, - }; - let fixture = Fixture::new("expert"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - // A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table. - let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); - let digest = sha256_hex(&table); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.expert_profile_sha256 = Some(digest.clone()); - let profile_file = fixture.root.join("profile.json"); - fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); - let local = fixture.root.join("table.bin"); - fs::write(&local, &table).unwrap(); - let paths = fixture.dirs.paths(); - let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); - let flags = [ - profile_file.display().to_string(), - local.display().to_string(), - ]; - - // No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-fetch"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); - assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); - assert!( - step.state.why().contains("--expert-profile-file") - && step.state.why().contains("--no-expert-tier") - ); - - // With the local copy: installed, verified, configured, reported ON. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--expert-profile-file", &flags[1]], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "todo" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!(file_state(&table_path, &digest), FileState::Valid); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!( - config.engine_env.get(PROFILE_ENV), - Some(&table_path.display().to_string()) - ); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - report.on && report.line().starts_with("expert tier ON"), - "{}", - report.line() - ); - - // Second run: done, nothing rewritten. - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "done" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - - // The file changes behind the service's back: the report turns OFF and the start drops the switches. - fs::write(&table_path, b"corrupted").unwrap(); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.line().starts_with("WARNING expert tier OFF"), - "{}", - report.line() - ); - let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets); - assert!(!env.contains_key(PROFILE_ENV)); - // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). - let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "BLOCKED" - ); - assert!( - run_up(&ctx, &steps) - .await - .unwrap_err() - .contains("expert-profile") - ); - - // The explicit opt-out is recorded and reported as such. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-expert-tier"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.opted_out && report.line().contains("explicit opt-out"), - "{}", - report.line() - ); -} - -#[tokio::test] -async fn first_start_installs_the_embedded_expert_profile_without_a_network() { - use leleka_deploy::expert_profile::{ - FileState, PINNED_BYTES, PINNED_SHA256, file_state, tier_report, - }; - let fixture = Fixture::new("embedded"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - // The real 3080 profile pins the upstream table; no --no-expert-tier, no --expert-profile-file, no network tool on PATH. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - "rtx3080-16g", - &["--no-fetch"], - ); - let mut ctx = healthy_context(&opts); - ctx.facts.tools.insert("curl".into(), false); - ctx.facts.tools.insert("wget".into(), false); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); - assert_eq!(step.state.tag(), "todo", "{step:?}"); - assert!( - step.state.why().contains("embedded in this binary"), - "{step:?}" - ); - leleka_deploy::steps::provision_expert_profile(&ctx).unwrap(); - let table = fixture.dirs.assets.join("data/expert-profile.bin"); - assert_eq!(file_state(&table, PINNED_SHA256), FileState::Valid); - assert_eq!(fs::metadata(&table).unwrap().len(), PINNED_BYTES); - let config = ctx.config.as_ref().unwrap(); - let report = tier_report(config, &fixture.dirs.assets); - assert!( - report.on && report.line().contains("8f59b4aa...388975baf"), - "{}", - report.line() - ); - // Re-planned: nothing left to do. - let steps = plan_steps(&healthy_context(&opts), &FsState::default()); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "done" - ); -} - -#[tokio::test] -async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() { - let fixture = Fixture::new("wrongkar"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); - // A pre-existing archive of the wrong length: the fake `ensure` reuses it, the size gate must object. - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"short").unwrap(); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let error = run_up(&ctx, &steps).await.unwrap_err(); - assert!(error.contains("engine only admits the pinned"), "{error}"); -} - -// ----------------------------------------------------------------------------------------------------------- -// the command line - -#[test] -fn dry_run_prints_the_plan_and_changes_nothing() { - let fixture = Fixture::new("dry"); - let bin = fixture.root.join("bin"); - fixture.install_fake_binaries(&bin); - let output = Process::new(LELEKA) - .args([ - "up", - "--dry-run", - "--profile", - "rtx5090-32g", - "--mode", - "foreground", - "--assets", - ]) - .arg(&fixture.dirs.assets) - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--bin-src") - .arg(&bin) - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stdout.contains("plan:") && stdout.contains("engine command the service runs:"), - "{stdout}" - ); - assert!( - stdout.contains("--kar-archive-fd {FD}") - && stdout.contains("nothing was changed (--dry-run)"), - "{stdout}" - ); - assert!( - stderr.contains("preflight (profile rtx5090-32g)"), - "{stderr}" - ); - for path in [ - &fixture.dirs.assets, - &fixture.dirs.state, - &fixture.dirs.prefix, - ] { - assert!(!path.exists(), "--dry-run created {}", path.display()); - } - // --json is one parseable document with the steps. - let output = Process::new(LELEKA) - .args([ - "up", - "--dry-run", - "--json", - "--profile", - "rtx5090-32g", - "--mode", - "foreground", - "--assets", - ]) - .arg(&fixture.dirs.assets) - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--bin-src") - .arg(&bin) - .output() - .unwrap(); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["profile"], "rtx5090-32g"); - assert!( - json["steps"] - .as_array() - .unwrap() - .iter() - .any(|s| s["id"] == "kar") - ); -} - -#[test] -fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() { - let fixture = Fixture::new("preflight-fail"); - let bin = fixture.root.join("bin"); - fixture.install_fake_binaries(&bin); - // The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check. - let output = Process::new(LELEKA) - .args([ - "up", - "--profile", - "rtx5090-32g", - "--mode", - "none", - "--assets", - ]) - .arg(&fixture.dirs.assets) - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--bin-src") - .arg(&bin) - .output() - .unwrap(); - assert_eq!(output.status.code(), Some(1)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("[FAIL]") && stderr.contains("fix:"), - "{stderr}" - ); - assert!(stderr.contains("nothing was changed"), "{stderr}"); - for path in [ - &fixture.dirs.assets, - &fixture.dirs.state, - &fixture.dirs.prefix, - ] { - assert!( - !path.exists(), - "a failed preflight created {}", - path.display() - ); - } -} - -#[test] -fn profiles_and_usage_commands() { - let list = Process::new(LELEKA).arg("profiles").output().unwrap(); - let text = String::from_utf8_lossy(&list.stdout); - assert!( - text.contains("rtx5090-32g") && text.contains("rtx3080-16g"), - "{text}" - ); - let show = Process::new(LELEKA) - .args(["profiles", "show", "rtx3080-16g"]) - .output() - .unwrap(); - let profile: Profile = serde_json::from_slice(&show.stdout).unwrap(); - assert_eq!( - profile.context_tokens, 262144, - "the shipped laptop profile is the owner's 256k workload (crates/deploy/src/profile.rs)" - ); - let bad = Process::new(LELEKA) - .args(["up", "--bogus"]) - .output() - .unwrap(); - assert_eq!(bad.status.code(), Some(2)); - assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option")); -} - -// ------------------------------------------------------------------------------------------------ leleka reconfigure - -mod reconfigure_flow { - use super::*; - use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request}; - use leleka_deploy::resources::Preset; - use serde_json::json; - - const GIB: u64 = 1 << 30; - - fn request( - id: &str, - budget_gib: Option, - preset: Option, - settings: serde_json::Value, - persist: bool, - ) -> Request { - Request { - id: id.to_owned(), - gpu_budget_gib: budget_gib, - preset, - settings: settings.as_object().cloned().unwrap_or_default(), - persist, - } - } - - fn ask(fixture: &Fixture, request: &Request, limit: Duration) -> Outcome { - write_request(&fixture.dirs.paths(), request).unwrap(); - let started = Instant::now(); - loop { - if let Some(outcome) = read_outcome(&fixture.dirs.paths(), &request.id) - && outcome.state != State::Running - { - return outcome; - } - assert!( - started.elapsed() < limit, - "no answer to {}; logs:\n{}", - request.id, - fixture.logs() - ); - std::thread::sleep(Duration::from_millis(200)); - } - } - - /// A supervisor with the fake runtime programs and an inherited sealed archive, ready. - struct Service { - fixture: Fixture, - supervisor: Child, - _memfd: fs::File, - first: serde_json::Value, - } - - fn start(name: &str) -> Service { - let fixture = Fixture::new(name); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.kar_source = KarSource::Memfd; - let config = fixture.write_state(profile); - let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); - let supervisor = start_supervisor( - &fixture, - &config, - Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), - ); - let first = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); - Service { - fixture, - supervisor, - _memfd: memfd, - first, - } - } - - impl Service { - fn starts(&self) -> Vec { - fs::read_to_string(self.fixture.fake_dir().join("calls.log")) - .unwrap() - .lines() - .filter(|line| line.starts_with("leleka-inference ")) - .map(str::to_owned) - .collect() - } - - fn stop(mut self) { - signal(u64::from(self.supervisor.id()), "TERM"); - assert!( - wait_exit(&mut self.supervisor, Duration::from_secs(60)) - .is_some_and(|s| s.success()), - "{}", - self.fixture.logs() - ); - } - } - - #[test] - fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { - let service = start("reconf-budget"); - let fixture = &service.fixture; - let (engine, gateway, api) = ( - service.first["engine_pid"].as_u64().unwrap(), - service.first["gateway_pid"].as_u64().unwrap(), - service.first["api_pid"].as_u64().unwrap(), - ); - let before = fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(); - let outcome = ask( - fixture, - &request("budget", Some(2), None, json!({}), false), - Duration::from_secs(120), - ); - assert_eq!( - outcome.state, - State::Done, - "{}\n{}", - outcome.message, - fixture.logs() - ); - assert!(!outcome.persisted); - assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0); - let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!( - after["engine_pid"].as_u64().unwrap(), - engine, - "the engine process is new" - ); - assert!(!pid_alive(engine), "the old engine is gone"); - assert_eq!( - after["gateway_pid"].as_u64().unwrap(), - gateway, - "the gateway keeps its process" - ); - assert_eq!( - after["api_pid"].as_u64().unwrap(), - api, - "the API keeps its process" - ); - assert_eq!( - after["engine_restarts"], 0, - "a planned restart is not a crash" - ); - assert_eq!(fixture.http_status("/ready"), 200); - let starts = service.starts(); - assert_eq!(starts.len(), 2, "{starts:?}"); - assert!( - starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), - "{}", - starts[0] - ); - assert!( - starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), - "{}", - starts[1] - ); - // the sealed descriptor of the first engine was handed on, and it is the one already verified - assert!( - starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), - "{}", - starts[1] - ); - let engine_log = - fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); - assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); - // not persisted: the file still has the old budget - assert_eq!( - fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), - before - ); - // asking for what is in force is answered at once, without another restart - let same = ask( - fixture, - &request("same", Some(2), None, json!({}), false), - Duration::from_secs(20), - ); - assert_eq!( - (same.state, same.message.contains("already")), - (State::Done, true), - "{}", - same.message - ); - assert_eq!(service.starts().len(), 2); - service.stop(); - } - - #[test] - fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { - let service = start("reconf-persist"); - let fixture = &service.fixture; - let gateway = service.first["gateway_pid"].as_u64().unwrap(); - let api = service.first["api_pid"].as_u64().unwrap(); - let outcome = ask( - fixture, - &request( - "persist", - Some(3), - Some(Preset::Workstation), - json!({"context_tokens": 4096, "cpu_workers": 3}), - true, - ), - Duration::from_secs(120), - ); - assert_eq!( - outcome.state, - State::Done, - "{}\n{}", - outcome.message, - fixture.logs() - ); - assert!(outcome.persisted, "{}", outcome.message); - let config = - leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB); - assert_eq!(config.profile.context_tokens, 4096); - assert_eq!(config.preset, Preset::Workstation); - assert!( - config.base_profile.is_some(), - "the unmodified profile is kept to undo the preset" - ); - assert_eq!( - config - .engine_environment() - .get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS") - .map(String::as_str), - Some("3") - ); - // the API advertises the new context: its process was restarted on the same port, the gateway was not - let strata: serde_json::Value = serde_json::from_str( - &fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap(), - ) - .unwrap(); - assert_eq!(strata["runtime"]["max_context"], 4096); - let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!(after["api_pid"].as_u64().unwrap(), api); - assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway); - assert_eq!(fixture.http_status("/ready"), 200); - // a crash of the new engine restarts it with the new numbers, not the old ones - signal(after["engine_pid"].as_u64().unwrap(), "KILL"); - let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| { - s["phase"] == "ready" && s["engine_restarts"] == 1 - }); - assert_ne!(again["engine_pid"], after["engine_pid"]); - let starts = service.starts(); - let last = starts.last().unwrap(); - assert!( - last.contains(&format!("--gpu-budget {}", 3 * GIB)) - && last.contains("--context-tokens 4096"), - "{last}" - ); - service.stop(); - } - - #[test] - fn settings_alone_are_recorded_and_persisted_without_a_restart() { - let service = start("reconf-record"); - let fixture = &service.fixture; - let engine = service.first["engine_pid"].as_u64().unwrap(); - let outcome = ask( - fixture, - &request( - "record", - None, - None, - json!({"prefix_cache_tail": "prompt", "spec_min_p": 0.25}), - true, - ), - Duration::from_secs(30), - ); - assert_eq!( - (outcome.state, outcome.persisted), - (State::Done, true), - "{}", - outcome.message - ); - let config = - leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_eq!( - config.profile.memory.prefix_cache_tail.as_deref(), - Some("prompt") - ); - assert_eq!(config.profile.spec_min_p, Some(0.25)); - assert_eq!( - fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), - engine, - "no restart" - ); - assert_eq!(service.starts().len(), 1); - // not persisted: in force for this supervisor only - let quiet = ask( - fixture, - &request("quiet", None, None, json!({"context_tokens": 2048}), false), - Duration::from_secs(30), - ); - assert_eq!((quiet.state, quiet.persisted), (State::Done, false)); - let file = - leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_ne!(file.profile.context_tokens, 2048); - // an invalid document is refused and changes nothing - let bad = ask( - fixture, - &request("bad", None, None, json!({"cpu_workers": 99}), true), - Duration::from_secs(30), - ); - assert_eq!(bad.state, State::Refused); - assert!(bad.message.contains("cpu_workers"), "{}", bad.message); - service.stop(); - } - - #[test] - fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one() { - let service = start("reconf-refuse"); - let fixture = &service.fixture; - let engine = service.first["engine_pid"].as_u64().unwrap(); - // refused before the engine is touched - let bad = ask( - fixture, - &request("bad", Some(2), None, json!({"cpu_workers": 99}), false), - Duration::from_secs(30), - ); - assert_eq!(bad.state, State::Refused); - assert!( - bad.message.contains("nothing was changed"), - "{}", - bad.message - ); - let unknown = ask( - fixture, - &request("unknown", Some(2), None, json!({"nonsense": 1}), false), - Duration::from_secs(30), - ); - assert_eq!(unknown.state, State::Refused); - assert_eq!( - fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), - engine, - "the engine was not stopped" - ); - assert!(pid_alive(engine)); - // a budget the new engine cannot start with: the previous engine is started again with the previous numbers - fs::write( - fixture.fake_dir().join("fail-engine-budget"), - (4 * GIB).to_string(), - ) - .unwrap(); - let outcome = ask( - fixture, - &request("fails", Some(4), None, json!({}), true), - Duration::from_secs(180), - ); - assert_eq!( - outcome.state, - State::Refused, - "{}\n{}", - outcome.message, - fixture.logs() - ); - assert!( - outcome.message.contains("previous settings are back"), - "{}", - outcome.message - ); - let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine); - assert_eq!(fixture.http_status("/ready"), 200); - let starts = service.starts(); - assert_eq!(starts.len(), 3, "{starts:?}"); - assert!( - starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) - && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), - "{starts:?}" - ); - // nothing was persisted from the failed attempt - let config = - leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); - service.stop(); - } - - #[test] - fn the_cli_asks_the_supervisor_and_prints_the_answer() { - let service = start("reconf-cli"); - let dirs = service.fixture.dirs.clone(); - let run = |args: &[&str]| { - Process::new(LELEKA) - .arg("reconfigure") - .args(args) - .arg("--state-dir") - .arg(&dirs.state) - .arg("--assets") - .arg(&dirs.assets) - .arg("--prefix") - .arg(&dirs.prefix) - .output() - .unwrap() - }; - let output = run(&["--gpu-budget-gib", "5", "--persist"]); - let text = String::from_utf8_lossy(&output.stdout).into_owned() - + &String::from_utf8_lossy(&output.stderr); - assert!( - output.status.success(), - "{text}\n{}", - service.fixture.logs() - ); - assert!( - text.contains("reconfigured") && text.contains("gpu_budget_gib"), - "{text}" - ); - let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap(); - assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB); - // a refusal is a non-zero exit with the reason - let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]); - assert!(!refused.status.success()); - let text = String::from_utf8_lossy(&refused.stderr); - assert!( - text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"), - "{text}" - ); - service.stop(); - // without a supervisor the restart path says what to do instead of hanging - let stopped = run(&["--preset", "workstation"]); - assert!(!stopped.status.success()); - assert!( - String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"), - "{}", - String::from_utf8_lossy(&stopped.stderr) - ); - } - - #[test] - fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer() { - let mut service = start("reconf-lost"); - let fixture = &service.fixture; - // from now on no engine starts at all: the new one fails, and so does the restored one - fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); - let outcome = ask( - fixture, - &request("lost", Some(4), None, json!({}), false), - Duration::from_secs(120), - ); - assert_eq!( - outcome.state, - State::Failed, - "{}\n{}", - outcome.message, - fixture.logs() - ); - assert!( - outcome.message.contains("could not be restored"), - "{}", - outcome.message - ); - let status = wait_exit(&mut service.supervisor, Duration::from_secs(60)) - .expect("the supervisor must give up"); - assert_eq!(status.code(), Some(1)); - assert_eq!(fixture.status().unwrap()["phase"], "failed"); - } -} diff --git a/crates/deploy/tests/e2e/dry_run_and_usage.rs b/crates/deploy/tests/e2e/dry_run_and_usage.rs new file mode 100644 index 00000000..76432cb8 --- /dev/null +++ b/crates/deploy/tests/e2e/dry_run_and_usage.rs @@ -0,0 +1,155 @@ +//! `--dry-run`, a failing preflight and the `profiles` and usage commands. + +use crate::harness::*; +use leleka_deploy::profile::Profile; +use std::process::Command as Process; + +// ----------------------------------------------------------------------------------------------------------- +// the command line + +#[test] +fn dry_run_prints_the_plan_and_changes_nothing() { + let fixture = Fixture::new("dry"); + let bin = fixture.root.join("bin"); + fixture.install_fake_binaries(&bin); + let output = Process::new(LELEKA) + .args([ + "up", + "--dry-run", + "--profile", + "rtx5090-32g", + "--mode", + "foreground", + "--assets", + ]) + .arg(&fixture.dirs.assets) + .arg("--state-dir") + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--bin-src") + .arg(&bin) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stdout.contains("plan:") && stdout.contains("engine command the service runs:"), + "{stdout}" + ); + assert!( + stdout.contains("--kar-archive-fd {FD}") + && stdout.contains("nothing was changed (--dry-run)"), + "{stdout}" + ); + assert!( + stderr.contains("preflight (profile rtx5090-32g)"), + "{stderr}" + ); + for path in [ + &fixture.dirs.assets, + &fixture.dirs.state, + &fixture.dirs.prefix, + ] { + assert!(!path.exists(), "--dry-run created {}", path.display()); + } + // --json is one parseable document with the steps. + let output = Process::new(LELEKA) + .args([ + "up", + "--dry-run", + "--json", + "--profile", + "rtx5090-32g", + "--mode", + "foreground", + "--assets", + ]) + .arg(&fixture.dirs.assets) + .arg("--state-dir") + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--bin-src") + .arg(&bin) + .output() + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(json["profile"], "rtx5090-32g"); + assert!( + json["steps"] + .as_array() + .unwrap() + .iter() + .any(|s| s["id"] == "kar") + ); +} + +#[test] +fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() { + let fixture = Fixture::new("preflight-fail"); + let bin = fixture.root.join("bin"); + fixture.install_fake_binaries(&bin); + // The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check. + let output = Process::new(LELEKA) + .args([ + "up", + "--profile", + "rtx5090-32g", + "--mode", + "none", + "--assets", + ]) + .arg(&fixture.dirs.assets) + .arg("--state-dir") + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--bin-src") + .arg(&bin) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("[FAIL]") && stderr.contains("fix:"), + "{stderr}" + ); + assert!(stderr.contains("nothing was changed"), "{stderr}"); + for path in [ + &fixture.dirs.assets, + &fixture.dirs.state, + &fixture.dirs.prefix, + ] { + assert!( + !path.exists(), + "a failed preflight created {}", + path.display() + ); + } +} + +#[test] +fn profiles_and_usage_commands() { + let list = Process::new(LELEKA).arg("profiles").output().unwrap(); + let text = String::from_utf8_lossy(&list.stdout); + assert!( + text.contains("rtx5090-32g") && text.contains("rtx3080-16g"), + "{text}" + ); + let show = Process::new(LELEKA) + .args(["profiles", "show", "rtx3080-16g"]) + .output() + .unwrap(); + let profile: Profile = serde_json::from_slice(&show.stdout).unwrap(); + assert_eq!( + profile.context_tokens, 262144, + "the shipped laptop profile is the owner's 256k workload (crates/deploy/src/profile.rs)" + ); + let bad = Process::new(LELEKA) + .args(["up", "--bogus"]) + .output() + .unwrap(); + assert_eq!(bad.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option")); +} diff --git a/crates/deploy/tests/e2e/engine_supervision.rs b/crates/deploy/tests/e2e/engine_supervision.rs new file mode 100644 index 00000000..8bbf2452 --- /dev/null +++ b/crates/deploy/tests/e2e/engine_supervision.rs @@ -0,0 +1,267 @@ +//! Health checks, restarts with back-off, log rotation and the failures that end the service. + +use crate::harness::*; +use leleka_deploy::profile::{KarSource, Profile}; +use std::{ + fs, + time::{Duration, Instant}, +}; + +#[test] +fn a_hung_engine_is_killed_and_restarted_by_the_health_check() { + // `max_request_s` is 3 here; the fake API reports a request that has been active for 600 s. + let fixture = Fixture::new("hang"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + tune(&config, |c| { + c["health"] = + serde_json::json!({"enabled": true, "interval_s": 1, "fail_s": 30, "max_request_s": 3}); + c["restart"]["backoff_initial_s"] = serde_json::json!(1); + }); + let mut supervisor = start_supervisor(&fixture, &config, None); + let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + assert_eq!(ready["restarts_total"], 0); + let hung_pid = ready["engine_pid"].as_u64().unwrap(); + // The process lives and the API answers, but a request has been active for ten minutes. + fs::write(fixture.fake_dir().join("hang-decode"), "").unwrap(); + let again = fixture.wait_for("restart after the stall", Duration::from_secs(60), |s| { + s["phase"] == "ready" + && s["restarts_total"] == 1 + && s["engine_pid"].as_u64() != Some(hung_pid) + }); + let reason = again["last_restart_reason"].as_str().unwrap(); + assert!( + reason.contains("request has been active") && reason.contains("600"), + "{reason}" + ); + assert!(!pid_alive(hung_pid), "the hung engine must be gone"); + // The fake reports the hang once; afterwards the new engine is judged healthy. + let healthy = fixture.wait_for("healthy again", Duration::from_secs(30), |s| { + s["health"] == "healthy" + }); + assert_eq!( + healthy["restarts_total"], 1, + "no second restart without a second stall" + ); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() { + let fixture = Fixture::new("backoff"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + tune(&config, |c| { + c["health"]["enabled"] = serde_json::json!(false); + c["restart"] = serde_json::json!({"max_engine_restarts": 3, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); + }); + let mut supervisor = start_supervisor(&fixture, &config, None); + let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + // Crash it and make every restart fail: three attempts in a row, then the service ends with a message. + fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); + signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); + let status = + wait_exit(&mut supervisor, Duration::from_secs(90)).expect("the supervisor must give up"); + assert_eq!(status.code(), Some(1)); + let state = fixture.status().unwrap(); + assert_eq!(state["phase"], "failed"); + let message = state["message"].as_str().unwrap(); + assert!(message.contains("failed 3 times in a row"), "{message}"); + assert_eq!(state["restarts_total"], 1); + let log = fs::read_to_string(fixture.dirs.paths().logs().join("leleka.log")).unwrap(); + assert!( + log.matches("the engine did not come back").count() >= 3, + "{log}" + ); + + // A restart that fails once and then works is just a slower restart. + let fixture = Fixture::new("backoff2"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + tune(&config, |c| { + c["health"]["enabled"] = serde_json::json!(false); + c["restart"] = serde_json::json!({"max_engine_restarts": 5, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); + }); + let mut supervisor = start_supervisor(&fixture, &config, None); + let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); + signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); + fixture.wait_for("restart attempts", Duration::from_secs(30), |s| { + s["phase"] == "engine_restarting" + }); + std::thread::sleep(Duration::from_millis(2500)); + fs::remove_file(fixture.fake_dir().join("fail-engine")).unwrap(); + let again = fixture.wait_for("recovered", Duration::from_secs(60), |s| { + s["phase"] == "ready" && s["restarts_total"] == 1 + }); + assert!(again["engine_restarts"].as_u64().unwrap() >= 2, "{again}"); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn logs_past_their_limit_are_rotated_while_the_service_runs() { + let fixture = Fixture::new("logs"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + tune(&config, |c| { + c["logs"] = serde_json::json!({"limit_mib": 1, "keep": 2}) + }); + let big = fixture.dirs.paths().logs().join("api.log"); + fs::write(&big, "x".repeat(300) + "\n").unwrap(); + { + use std::io::Write; + let mut file = fs::OpenOptions::new().append(true).open(&big).unwrap(); + for _ in 0..(3 << 20) / 100 { + writeln!(file, "{}", "y".repeat(99)).unwrap(); + } + } + let mut supervisor = start_supervisor(&fixture, &config, None); + fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + let rotated = fixture.dirs.paths().logs().join("api.log.1"); + let started = Instant::now(); + while !rotated.exists() && started.elapsed() < Duration::from_secs(30) { + std::thread::sleep(Duration::from_millis(200)); + } + assert!(rotated.exists(), "{}", fixture.logs()); + assert!(fs::metadata(&rotated).unwrap().len() <= 1 << 20); + assert!(fs::metadata(&big).unwrap().len() < 1 << 20); + let doc = fixture.status().unwrap(); + assert!(doc["log_bytes"].as_u64().unwrap() > 0); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone() { + let fixture = Fixture::new("sidecars"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + tune(&config, |c| { + c["health"]["enabled"] = serde_json::json!(false) + }); + let mut supervisor = start_supervisor(&fixture, &config, None); + let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + let (engine, gateway, api) = ( + ready["engine_pid"].as_u64().unwrap(), + ready["gateway_pid"].as_u64().unwrap(), + ready["api_pid"].as_u64().unwrap(), + ); + signal(api, "KILL"); + let after_api = fixture.wait_for("a new API", Duration::from_secs(30), |s| { + s["api_pid"].as_u64().is_some_and(|p| p != api) && s["phase"] == "ready" + }); + assert_eq!(after_api["engine_pid"].as_u64(), Some(engine)); + assert_eq!( + after_api["restarts_total"], 0, + "an API restart is not an engine restart" + ); + signal(gateway, "KILL"); + let after_gateway = fixture.wait_for("a new gateway", Duration::from_secs(30), |s| { + s["gateway_pid"].as_u64().is_some_and(|p| p != gateway) + }); + assert_eq!(after_gateway["engine_pid"].as_u64(), Some(engine)); + let started = Instant::now(); + while fixture.http_status("/ready") != 200 && started.elapsed() < Duration::from_secs(30) { + std::thread::sleep(Duration::from_millis(200)); + } + assert_eq!(fixture.http_status("/ready"), 200); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() { + let fixture = Fixture::new("fail"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::File; + let config = fixture.write_state(profile); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let mut supervisor = start_supervisor(&fixture, &config, None); + let status = + wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up"); + assert_eq!(status.code(), Some(1)); + let state = fixture.status().unwrap(); + assert_eq!(state["phase"], "failed"); + let message = state["message"].as_str().unwrap(); + assert!( + message.contains("engine") && message.contains("exited"), + "{message}" + ); + let output = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap(); + assert!(output.contains("fatal:"), "{output}"); + // The gateway started for the load is not left behind. + assert!(state["gateway_pid"].is_null() || !pid_alive(state["gateway_pid"].as_u64().unwrap())); +} + +#[test] +fn a_refused_load_fails_fast_and_shows_the_engine_log() { + // The real engine stays alive when its load fails; only the operation record says so. + let fixture = Fixture::new("refused"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + fs::write(fixture.fake_dir().join("fail-load"), "").unwrap(); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::File; + let config = fixture.write_state(profile); + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let started = Instant::now(); + let mut supervisor = start_supervisor(&fixture, &config, None); + let status = + wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up"); + assert_eq!(status.code(), Some(1)); + assert!( + started.elapsed() < Duration::from_secs(40), + "a refused load must not wait for the load timeout" + ); + let state = fixture.status().unwrap(); + let message = state["message"].as_str().unwrap(); + assert!( + message.contains("refused the load") && message.contains("BackendUnavailable"), + "{message}" + ); + // The engine it started is gone. + let engine_pid = fs::read_to_string(fixture.fake_dir().join("engine.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + assert!(!pid_alive(engine_pid)); +} diff --git a/crates/deploy/tests/e2e/expert_profile_install.rs b/crates/deploy/tests/e2e/expert_profile_install.rs new file mode 100644 index 00000000..df1fc84b --- /dev/null +++ b/crates/deploy/tests/e2e/expert_profile_install.rs @@ -0,0 +1,210 @@ +//! `leleka up` installs the expert profile offline (embedded table) and reports it. + +use crate::harness::*; +use leleka_deploy::{ + app::run_up, + config::RunConfig, + plan::{FsState, plan_steps}, + profile::Profile, + steps::gather_fs, +}; +use std::fs; + +#[tokio::test] +async fn up_installs_the_expert_profile_offline_and_reports_it() { + use leleka_deploy::expert_profile::{ + FileState, PROFILE_ENV, file_state, sha256_hex, tier_report, + }; + let fixture = Fixture::new("expert"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + // A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table. + let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); + let digest = sha256_hex(&table); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.expert_profile_sha256 = Some(digest.clone()); + let profile_file = fixture.root.join("profile.json"); + fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); + let local = fixture.root.join("table.bin"); + fs::write(&local, &table).unwrap(); + let paths = fixture.dirs.paths(); + let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); + let flags = [ + profile_file.display().to_string(), + local.display().to_string(), + ]; + + // No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. + let opts = up_options_with( + &fixture, + &bin_src, + &cublas, + &mtp, + &flags[0], + &["--no-fetch"], + ); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); + assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); + assert!( + step.state.why().contains("--expert-profile-file") + && step.state.why().contains("--no-expert-tier") + ); + + // With the local copy: installed, verified, configured, reported ON. + let opts = up_options_with( + &fixture, + &bin_src, + &cublas, + &mtp, + &flags[0], + &["--expert-profile-file", &flags[1]], + ); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!( + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag(), + "todo" + ); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!(file_state(&table_path, &digest), FileState::Valid); + let config = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!( + config.engine_env.get(PROFILE_ENV), + Some(&table_path.display().to_string()) + ); + let report = tier_report(&config, &fixture.dirs.assets); + assert!( + report.on && report.line().starts_with("expert tier ON"), + "{}", + report.line() + ); + + // Second run: done, nothing rewritten. + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!( + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag(), + "done" + ); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + + // The file changes behind the service's back: the report turns OFF and the start drops the switches. + fs::write(&table_path, b"corrupted").unwrap(); + let report = tier_report(&config, &fixture.dirs.assets); + assert!( + !report.on && report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets); + assert!(!env.contains_key(PROFILE_ENV)); + // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). + let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!( + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag(), + "BLOCKED" + ); + assert!( + run_up(&ctx, &steps) + .await + .unwrap_err() + .contains("expert-profile") + ); + + // The explicit opt-out is recorded and reported as such. + let opts = up_options_with( + &fixture, + &bin_src, + &cublas, + &mtp, + &flags[0], + &["--no-expert-tier"], + ); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + let config = RunConfig::read(&paths.run_config()).unwrap(); + assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); + let report = tier_report(&config, &fixture.dirs.assets); + assert!( + !report.on && report.opted_out && report.line().contains("explicit opt-out"), + "{}", + report.line() + ); +} + +#[tokio::test] +async fn first_start_installs_the_embedded_expert_profile_without_a_network() { + use leleka_deploy::expert_profile::{ + FileState, PINNED_BYTES, PINNED_SHA256, file_state, tier_report, + }; + let fixture = Fixture::new("embedded"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + // The real 3080 profile pins the upstream table; no --no-expert-tier, no --expert-profile-file, no network tool on PATH. + let opts = up_options_with( + &fixture, + &bin_src, + &cublas, + &mtp, + "rtx3080-16g", + &["--no-fetch"], + ); + let mut ctx = healthy_context(&opts); + ctx.facts.tools.insert("curl".into(), false); + ctx.facts.tools.insert("wget".into(), false); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); + assert_eq!(step.state.tag(), "todo", "{step:?}"); + assert!( + step.state.why().contains("embedded in this binary"), + "{step:?}" + ); + leleka_deploy::steps::provision_expert_profile(&ctx).unwrap(); + let table = fixture.dirs.assets.join("data/expert-profile.bin"); + assert_eq!(file_state(&table, PINNED_SHA256), FileState::Valid); + assert_eq!(fs::metadata(&table).unwrap().len(), PINNED_BYTES); + let config = ctx.config.as_ref().unwrap(); + let report = tier_report(config, &fixture.dirs.assets); + assert!( + report.on && report.line().contains("8f59b4aa...388975baf"), + "{}", + report.line() + ); + // Re-planned: nothing left to do. + let steps = plan_steps(&healthy_context(&opts), &FsState::default()); + assert_eq!( + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag(), + "done" + ); +} diff --git a/crates/deploy/tests/e2e/harness.rs b/crates/deploy/tests/e2e/harness.rs new file mode 100644 index 00000000..3324edea --- /dev/null +++ b/crates/deploy/tests/e2e/harness.rs @@ -0,0 +1,383 @@ +//! The fixture, the fake-runtime processes and the option builders that every flow test shares. + +use leleka_deploy::{ + cli::{Command, Environment, UpOptions, parse}, + config::{GATEWAY_TOKEN_ENV, Ports, RUNTIME_TOKEN_ENV, RunConfig, to_file_text}, + facts::{DirFact, Gpu, Memory}, + layout::{BINARIES, Dirs, MTP_FILES}, + plan::{Context, gather}, + preflight::evaluate, + profile::{KarSource, Profile}, +}; +use std::{ + collections::BTreeMap, + fs, + net::TcpListener, + os::unix::fs::symlink, + path::{Path, PathBuf}, + process::{Child, Command as Process, Stdio}, + time::{Duration, Instant}, +}; + +pub(super) const FAKE: &str = env!("CARGO_BIN_EXE_leleka-fake-runtime"); +pub(super) const LELEKA: &str = env!("CARGO_BIN_EXE_leleka"); +pub(super) const KEY: &str = "fake-api-key-0123456789abcdef0123456789abcdef"; + +/// A port from the range below the ephemeral one (32768+), so that the source ports of the many short +/// connections the tests make cannot collide with a port a fixture reserved but has not bound yet. +pub(super) fn free_port() -> u16 { + use std::sync::atomic::{AtomicU16, Ordering}; + static NEXT: AtomicU16 = AtomicU16::new(0); + loop { + let step = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = 20_000 + + ((std::process::id() as u16) + .wrapping_mul(31) + .wrapping_add(step.wrapping_mul(7))) + % 9_000; + if TcpListener::bind(("127.0.0.1", candidate)).is_ok() { + return candidate; + } + } +} + +pub(super) struct Fixture { + pub(super) root: PathBuf, + pub(super) dirs: Dirs, + pub(super) ports: Ports, +} + +impl Fixture { + pub(super) fn new(name: &str) -> Fixture { + let root = std::env::temp_dir().join(format!("leleka-e2e-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let dirs = Dirs { + prefix: root.join("prefix"), + state: root.join("state"), + assets: root.join("assets"), + }; + let ports = Ports { + api: format!("127.0.0.1:{}", free_port()), + engine: format!("127.0.0.1:{}", free_port()), + daemon: format!("127.0.0.1:{}", free_port()), + }; + Fixture { root, dirs, ports } + } + + pub(super) fn fake_dir(&self) -> PathBuf { + self.dirs.prefix.join("fake") + } + + /// `PREFIX/bin` with the real `leleka` and fakes for the other five (symlinks named like the programs). + pub(super) fn install_fake_binaries(&self, bin: &Path) { + fs::create_dir_all(bin).unwrap(); + for name in BINARIES { + let target = if name == "leleka" { LELEKA } else { FAKE }; + let _ = fs::remove_file(bin.join(name)); + symlink(target, bin.join(name)).unwrap(); + } + } + + pub(super) fn write_state(&self, profile: Profile) -> PathBuf { + let paths = self.dirs.paths(); + fs::create_dir_all(paths.logs()).unwrap(); + fs::create_dir_all(paths.run_dir()).unwrap(); + fs::write( + paths.env_file(), + format!( + "{RUNTIME_TOKEN_ENV}={}\n{GATEWAY_TOKEN_ENV}={}\n", + "r".repeat(40), + "g".repeat(40) + ), + ) + .unwrap(); + fs::write(paths.api_key(), KEY).unwrap(); + let mut config = + RunConfig::new(&self.dirs, self.ports.clone(), 0, profile, BTreeMap::new()); + config.shutdown_grace_s = 2; + // The flow tests are not about the expert tier (it has no table here): it is off on purpose, as after `--no-expert-tier`. + config.expert_tier = false; + fs::write(paths.run_config(), to_file_text(&config)).unwrap(); + fs::write(paths.daemon_config(), to_file_text(&config.daemon_json())).unwrap(); + fs::write(paths.strata_config(), to_file_text(&config.strata_json())).unwrap(); + paths.run_config() + } + + pub(super) fn status(&self) -> Option { + fs::read_to_string(self.dirs.paths().status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + } + + pub(super) fn wait_for( + &self, + what: &str, + limit: Duration, + mut done: impl FnMut(&serde_json::Value) -> bool, + ) -> serde_json::Value { + let started = Instant::now(); + loop { + if let Some(status) = self.status() + && done(&status) + { + return status; + } + assert!( + started.elapsed() < limit, + "timed out waiting for {what}; status {:?}; logs:\n{}", + self.status(), + self.logs() + ); + std::thread::sleep(Duration::from_millis(200)); + } + } + + pub(super) fn logs(&self) -> String { + let mut out = String::new(); + if let Ok(entries) = fs::read_dir(self.dirs.paths().logs()) { + for entry in entries.flatten() { + out.push_str(&format!( + "--- {} ---\n{}\n", + entry.path().display(), + fs::read_to_string(entry.path()).unwrap_or_default() + )); + } + } + out + } + + pub(super) fn http_status(&self, path: &str) -> u16 { + use std::io::{Read, Write}; + let Ok(mut stream) = std::net::TcpStream::connect(&self.ports.api) else { + return 0; + }; + let _ = stream.set_read_timeout(Some(Duration::from_secs(3))); + write!(stream, "GET {path} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {KEY}\r\nConnection: close\r\n\r\n").unwrap(); + let mut text = String::new(); + let _ = stream.read_to_string(&mut text); + text.split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .unwrap_or(0) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} + +pub(super) fn signal(pid: u64, name: &str) { + let _ = Process::new("kill") + .arg(format!("-{name}")) + .arg(pid.to_string()) + .status(); +} + +pub(super) fn pid_alive(pid: u64) -> bool { + Path::new(&format!("/proc/{pid}")).exists() + && fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| !s.contains(") Z ")) +} + +pub(super) fn wait_exit(child: &mut Child, limit: Duration) -> Option { + let started = Instant::now(); + while started.elapsed() < limit { + if let Some(status) = child.try_wait().unwrap() { + return Some(status); + } + std::thread::sleep(Duration::from_millis(100)); + } + None +} + +/// Make a sealed memfd that `leleka run` inherits (no close-on-exec). +pub(super) fn inheritable_sealed_memfd(bytes: &[u8]) -> fs::File { + use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; + use std::io::Write; + let mut file = fs::File::from(memfd_create("test-archive", MemfdFlags::ALLOW_SEALING).unwrap()); + file.write_all(bytes).unwrap(); + fcntl_add_seals( + &file, + SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL, + ) + .unwrap(); + file +} + +pub(super) fn start_supervisor(fixture: &Fixture, config: &Path, kar_fd: Option) -> Child { + start_supervisor_with_env(fixture, config, kar_fd, &[]) +} + +pub(super) fn start_supervisor_with_env( + fixture: &Fixture, + config: &Path, + kar_fd: Option, + env: &[(&str, &str)], +) -> Child { + let mut command = Process::new(LELEKA); + command.arg("run").arg("--config").arg(config); + command.envs(env.iter().copied()); + if let Some(fd) = kar_fd { + command.arg("--kar-fd").arg(fd.to_string()); + } + // A token in the environment of the supervisor must not reach any child. + command + .env("HF_TOKEN", "hf_test_value_that_must_not_leak") + .stdin(Stdio::null()); + let log = fs::File::create(fixture.root.join("supervisor.out")).unwrap(); + command.stdout(log.try_clone().unwrap()).stderr(log); + command.spawn().unwrap() +} + +// ----------------------------------------------------------------------------------------------------------- +// the `up` flow + +/// `up` options of the 3080 profile with the expert tier switched off on purpose: the flow tests must not download +/// the real table. The tier itself is covered by `up_installs_the_expert_profile_offline_and_reports_it`. +pub(super) fn up_options( + fixture: &Fixture, + bin_src: &Path, + cublas: &Path, + mtp: &Path, + extra: &[&str], +) -> UpOptions { + let mut all = vec!["--no-expert-tier"]; + all.extend_from_slice(extra); + up_options_with(fixture, bin_src, cublas, mtp, "rtx3080-16g", &all) +} + +pub(super) fn up_options_with( + fixture: &Fixture, + bin_src: &Path, + cublas: &Path, + mtp: &Path, + profile: &str, + extra: &[&str], +) -> UpOptions { + let var = |_: &str| None; + let args: Vec = [ + "up", + "--assets", + &fixture.dirs.assets.display().to_string(), + "--state-dir", + &fixture.dirs.state.display().to_string(), + "--prefix", + &fixture.dirs.prefix.display().to_string(), + "--bin-src", + &bin_src.display().to_string(), + "--cublas-dir", + &cublas.display().to_string(), + "--mtp-pack", + &mtp.display().to_string(), + "--api-port", + fixture.ports.api.rsplit(':').next().unwrap(), + "--engine-port", + fixture.ports.engine.rsplit(':').next().unwrap(), + "--daemon-port", + fixture.ports.daemon.rsplit(':').next().unwrap(), + "--profile", + profile, + "--mode", + "none", + ] + .iter() + .map(|s| s.to_string()) + .chain(extra.iter().map(|s| s.to_string())) + .collect(); + match parse( + &args, + &Environment { + root: false, + home: Some(fixture.root.clone()), + var: &var, + }, + ) + .unwrap() + { + Command::Up(options) => options, + _ => unreachable!(), + } +} + +/// A host that passes the preflight, whatever machine runs the test. +pub(super) fn healthy_context(opts: &UpOptions) -> Context { + let mut ctx = gather(opts, &|_| None); + let gpu = Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15500, + sm: Some(86), + }; + ctx.facts.os = "linux".into(); + ctx.facts.arch = "x86_64".into(); + ctx.facts.gpus = vec![gpu]; + ctx.facts.memory = Memory { + total: 39 << 30, + available: 37 << 30, + swap_total: 0, + }; + ctx.facts.proc_fd = true; + ctx.facts.memfd_ok = true; + ctx.facts.busy_ports.clear(); + ctx.facts.libs.insert( + "libcuda.so.1".into(), + Some("/usr/lib/wsl/lib/libcuda.so.1".into()), + ); + for key in ["assets", "state", "prefix"] { + ctx.facts.dirs.insert( + key.into(), + DirFact { + path: PathBuf::from("/x"), + free_bytes: Some(2 << 40), + fs_type: Some("ext4".into()), + }, + ); + } + ctx.needs.binary_has_sm86 = Some(true); + let profile = ctx.profile.as_ref().unwrap().clone(); + ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs)); + assert!( + !ctx.report.as_ref().unwrap().failed(), + "{}", + ctx.report.as_ref().unwrap().render() + ); + ctx +} + +pub(super) fn fake_libraries(dir: &Path) { + fs::create_dir_all(dir).unwrap(); + fs::write(dir.join("libcublas.so.12"), b"x").unwrap(); + fs::write(dir.join("libcublasLt.so.12"), b"x").unwrap(); +} + +pub(super) fn mtp_source(dir: &Path) { + fs::create_dir_all(dir).unwrap(); + for name in MTP_FILES { + fs::write(dir.join(name), b"pack").unwrap(); + } +} + +pub(super) fn count_calls(fixture: &Fixture, needle: &str) -> usize { + fs::read_to_string(fixture.fake_dir().join("calls.log")) + .unwrap_or_default() + .matches(needle) + .count() +} + +/// Rewrite `leleka.json` with `change` applied (the fixture writes the defaults). +pub(super) fn tune(config: &Path, change: impl FnOnce(&mut serde_json::Value)) { + let mut value: serde_json::Value = + serde_json::from_str(&fs::read_to_string(config).unwrap()).unwrap(); + change(&mut value); + fs::write(config, serde_json::to_string_pretty(&value).unwrap()).unwrap(); +} + +pub(super) fn file_profile() -> Profile { + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::File; + profile +} diff --git a/crates/deploy/tests/e2e/main.rs b/crates/deploy/tests/e2e/main.rs new file mode 100644 index 00000000..8c60ce01 --- /dev/null +++ b/crates/deploy/tests/e2e/main.rs @@ -0,0 +1,13 @@ +//! Black-box and flow tests with a test double for the runtime programs (no GPU, no model). +//! Run with `cargo test -p leleka-deploy --features test-fakes`. +#![cfg(all(target_os = "linux", feature = "test-fakes"))] + +mod dry_run_and_usage; +mod engine_supervision; +mod expert_profile_install; +mod harness; +mod reconfigure_flow; +mod sealed_archive; +mod supervisor_lifecycle; +mod up_flow; +mod verify_commands; diff --git a/crates/deploy/tests/e2e/reconfigure_flow.rs b/crates/deploy/tests/e2e/reconfigure_flow.rs new file mode 100644 index 00000000..47666b3b --- /dev/null +++ b/crates/deploy/tests/e2e/reconfigure_flow.rs @@ -0,0 +1,379 @@ +//! Reconfigure flows against the fake runtime: planning, persisting, restart and rollback. + +use crate::harness::*; +use leleka_deploy::profile::{KarSource, Profile}; +use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request}; +use leleka_deploy::resources::Preset; +use serde_json::json; +use std::{ + fs, + process::{Child, Command as Process}, + time::{Duration, Instant}, +}; + +const GIB: u64 = 1 << 30; + +#[test] +fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { + let service = start("reconf-budget"); + let fixture = &service.fixture; + let (engine, gateway, api) = ( + service.first["engine_pid"].as_u64().unwrap(), + service.first["gateway_pid"].as_u64().unwrap(), + service.first["api_pid"].as_u64().unwrap(), + ); + let before = fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(); + let outcome = ask( + fixture, + &request("budget", Some(2), None, json!({}), false), + Duration::from_secs(120), + ); + assert_eq!( + outcome.state, + State::Done, + "{}\n{}", + outcome.message, + fixture.logs() + ); + assert!(!outcome.persisted); + assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0); + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!( + after["engine_pid"].as_u64().unwrap(), + engine, + "the engine process is new" + ); + assert!(!pid_alive(engine), "the old engine is gone"); + assert_eq!( + after["gateway_pid"].as_u64().unwrap(), + gateway, + "the gateway keeps its process" + ); + assert_eq!( + after["api_pid"].as_u64().unwrap(), + api, + "the API keeps its process" + ); + assert_eq!( + after["engine_restarts"], 0, + "a planned restart is not a crash" + ); + assert_eq!(fixture.http_status("/ready"), 200); + let starts = service.starts(); + assert_eq!(starts.len(), 2, "{starts:?}"); + assert!( + starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), + "{}", + starts[0] + ); + assert!( + starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), + "{}", + starts[1] + ); + // the sealed descriptor of the first engine was handed on, and it is the one already verified + assert!( + starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), + "{}", + starts[1] + ); + let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); + assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); + // not persisted: the file still has the old budget + assert_eq!( + fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), + before + ); + // asking for what is in force is answered at once, without another restart + let same = ask( + fixture, + &request("same", Some(2), None, json!({}), false), + Duration::from_secs(20), + ); + assert_eq!( + (same.state, same.message.contains("already")), + (State::Done, true), + "{}", + same.message + ); + assert_eq!(service.starts().len(), 2); + service.stop(); +} + +#[test] +fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { + let service = start("reconf-persist"); + let fixture = &service.fixture; + let gateway = service.first["gateway_pid"].as_u64().unwrap(); + let api = service.first["api_pid"].as_u64().unwrap(); + let outcome = ask( + fixture, + &request( + "persist", + Some(3), + Some(Preset::Workstation), + json!({"context_tokens": 4096, "cpu_workers": 3}), + true, + ), + Duration::from_secs(120), + ); + assert_eq!( + outcome.state, + State::Done, + "{}\n{}", + outcome.message, + fixture.logs() + ); + assert!(outcome.persisted, "{}", outcome.message); + let config = + leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB); + assert_eq!(config.profile.context_tokens, 4096); + assert_eq!(config.preset, Preset::Workstation); + assert!( + config.base_profile.is_some(), + "the unmodified profile is kept to undo the preset" + ); + assert_eq!( + config + .engine_environment() + .get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS") + .map(String::as_str), + Some("3") + ); + // the API advertises the new context: its process was restarted on the same port, the gateway was not + let strata: serde_json::Value = + serde_json::from_str(&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap()) + .unwrap(); + assert_eq!(strata["runtime"]["max_context"], 4096); + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!(after["api_pid"].as_u64().unwrap(), api); + assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway); + assert_eq!(fixture.http_status("/ready"), 200); + // a crash of the new engine restarts it with the new numbers, not the old ones + signal(after["engine_pid"].as_u64().unwrap(), "KILL"); + let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| { + s["phase"] == "ready" && s["engine_restarts"] == 1 + }); + assert_ne!(again["engine_pid"], after["engine_pid"]); + let starts = service.starts(); + let last = starts.last().unwrap(); + assert!( + last.contains(&format!("--gpu-budget {}", 3 * GIB)) + && last.contains("--context-tokens 4096"), + "{last}" + ); + service.stop(); +} + +#[test] +fn settings_alone_are_recorded_and_persisted_without_a_restart() { + let service = start("reconf-record"); + let fixture = &service.fixture; + let engine = service.first["engine_pid"].as_u64().unwrap(); + let outcome = ask( + fixture, + &request( + "record", + None, + None, + json!({"prefix_cache_tail": "prompt", "spec_min_p": 0.25}), + true, + ), + Duration::from_secs(30), + ); + assert_eq!( + (outcome.state, outcome.persisted), + (State::Done, true), + "{}", + outcome.message + ); + let config = + leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!( + config.profile.memory.prefix_cache_tail.as_deref(), + Some("prompt") + ); + assert_eq!(config.profile.spec_min_p, Some(0.25)); + assert_eq!( + fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), + engine, + "no restart" + ); + assert_eq!(service.starts().len(), 1); + // not persisted: in force for this supervisor only + let quiet = ask( + fixture, + &request("quiet", None, None, json!({"context_tokens": 2048}), false), + Duration::from_secs(30), + ); + assert_eq!((quiet.state, quiet.persisted), (State::Done, false)); + let file = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_ne!(file.profile.context_tokens, 2048); + // an invalid document is refused and changes nothing + let bad = ask( + fixture, + &request("bad", None, None, json!({"cpu_workers": 99}), true), + Duration::from_secs(30), + ); + assert_eq!(bad.state, State::Refused); + assert!(bad.message.contains("cpu_workers"), "{}", bad.message); + service.stop(); +} + +#[test] +fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one() { + let service = start("reconf-refuse"); + let fixture = &service.fixture; + let engine = service.first["engine_pid"].as_u64().unwrap(); + // refused before the engine is touched + let bad = ask( + fixture, + &request("bad", Some(2), None, json!({"cpu_workers": 99}), false), + Duration::from_secs(30), + ); + assert_eq!(bad.state, State::Refused); + assert!( + bad.message.contains("nothing was changed"), + "{}", + bad.message + ); + let unknown = ask( + fixture, + &request("unknown", Some(2), None, json!({"nonsense": 1}), false), + Duration::from_secs(30), + ); + assert_eq!(unknown.state, State::Refused); + assert_eq!( + fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), + engine, + "the engine was not stopped" + ); + assert!(pid_alive(engine)); + // a budget the new engine cannot start with: the previous engine is started again with the previous numbers + fs::write( + fixture.fake_dir().join("fail-engine-budget"), + (4 * GIB).to_string(), + ) + .unwrap(); + let outcome = ask( + fixture, + &request("fails", Some(4), None, json!({}), true), + Duration::from_secs(180), + ); + assert_eq!( + outcome.state, + State::Refused, + "{}\n{}", + outcome.message, + fixture.logs() + ); + assert!( + outcome.message.contains("previous settings are back"), + "{}", + outcome.message + ); + let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine); + assert_eq!(fixture.http_status("/ready"), 200); + let starts = service.starts(); + assert_eq!(starts.len(), 3, "{starts:?}"); + assert!( + starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) + && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), + "{starts:?}" + ); + // nothing was persisted from the failed attempt + let config = + leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); + service.stop(); +} + +#[test] +fn the_cli_asks_the_supervisor_and_prints_the_answer() { + let service = start("reconf-cli"); + let dirs = service.fixture.dirs.clone(); + let run = |args: &[&str]| { + Process::new(LELEKA) + .arg("reconfigure") + .args(args) + .arg("--state-dir") + .arg(&dirs.state) + .arg("--assets") + .arg(&dirs.assets) + .arg("--prefix") + .arg(&dirs.prefix) + .output() + .unwrap() + }; + let output = run(&["--gpu-budget-gib", "5", "--persist"]); + let text = String::from_utf8_lossy(&output.stdout).into_owned() + + &String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "{text}\n{}", + service.fixture.logs() + ); + assert!( + text.contains("reconfigured") && text.contains("gpu_budget_gib"), + "{text}" + ); + let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB); + // a refusal is a non-zero exit with the reason + let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]); + assert!(!refused.status.success()); + let text = String::from_utf8_lossy(&refused.stderr); + assert!( + text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"), + "{text}" + ); + service.stop(); + // without a supervisor the restart path says what to do instead of hanging + let stopped = run(&["--preset", "workstation"]); + assert!(!stopped.status.success()); + assert!( + String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"), + "{}", + String::from_utf8_lossy(&stopped.stderr) + ); +} + +#[test] +fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer() { + let mut service = start("reconf-lost"); + let fixture = &service.fixture; + // from now on no engine starts at all: the new one fails, and so does the restored one + fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); + let outcome = ask( + fixture, + &request("lost", Some(4), None, json!({}), false), + Duration::from_secs(120), + ); + assert_eq!( + outcome.state, + State::Failed, + "{}\n{}", + outcome.message, + fixture.logs() + ); + assert!( + outcome.message.contains("could not be restored"), + "{}", + outcome.message + ); + let status = wait_exit(&mut service.supervisor, Duration::from_secs(60)) + .expect("the supervisor must give up"); + assert_eq!(status.code(), Some(1)); + assert_eq!(fixture.status().unwrap()["phase"], "failed"); +} + +mod service; +use service::{ask, request, start}; diff --git a/crates/deploy/tests/e2e/reconfigure_flow/service.rs b/crates/deploy/tests/e2e/reconfigure_flow/service.rs new file mode 100644 index 00000000..6077fefc --- /dev/null +++ b/crates/deploy/tests/e2e/reconfigure_flow/service.rs @@ -0,0 +1,88 @@ +//! A running supervisor with the fake runtime programs and an inherited sealed archive, and the request/answer helpers. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn request( + id: &str, + budget_gib: Option, + preset: Option, + settings: serde_json::Value, + persist: bool, +) -> Request { + Request { + id: id.to_owned(), + gpu_budget_gib: budget_gib, + preset, + settings: settings.as_object().cloned().unwrap_or_default(), + persist, + } +} + +pub(super) fn ask(fixture: &Fixture, request: &Request, limit: Duration) -> Outcome { + write_request(&fixture.dirs.paths(), request).unwrap(); + let started = Instant::now(); + loop { + if let Some(outcome) = read_outcome(&fixture.dirs.paths(), &request.id) + && outcome.state != State::Running + { + return outcome; + } + assert!( + started.elapsed() < limit, + "no answer to {}; logs:\n{}", + request.id, + fixture.logs() + ); + std::thread::sleep(Duration::from_millis(200)); + } +} + +/// A supervisor with the fake runtime programs and an inherited sealed archive, ready. +pub(super) struct Service { + pub(super) fixture: Fixture, + pub(super) supervisor: Child, + pub(super) _memfd: fs::File, + pub(super) first: serde_json::Value, +} + +pub(super) fn start(name: &str) -> Service { + let fixture = Fixture::new(name); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::Memfd; + let config = fixture.write_state(profile); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let supervisor = start_supervisor( + &fixture, + &config, + Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), + ); + let first = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + Service { + fixture, + supervisor, + _memfd: memfd, + first, + } +} + +impl Service { + pub(super) fn starts(&self) -> Vec { + fs::read_to_string(self.fixture.fake_dir().join("calls.log")) + .unwrap() + .lines() + .filter(|line| line.starts_with("leleka-inference ")) + .map(str::to_owned) + .collect() + } + + pub(super) fn stop(mut self) { + signal(u64::from(self.supervisor.id()), "TERM"); + assert!( + wait_exit(&mut self.supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), + "{}", + self.fixture.logs() + ); + } +} diff --git a/crates/deploy/tests/e2e/sealed_archive.rs b/crates/deploy/tests/e2e/sealed_archive.rs new file mode 100644 index 00000000..4ffe1ab2 --- /dev/null +++ b/crates/deploy/tests/e2e/sealed_archive.rs @@ -0,0 +1,192 @@ +//! The sparse memfd profile and `seal-exec`: digests, pins and what is never claimed. + +use crate::harness::*; +use leleka_deploy::profile::{KarSource, Profile}; +use std::{fs, process::Command as Process, time::Duration}; + +/// `memfd_extents: ple_only` profile of the test double (the laptop profile with a sealed memfd and an explicit prefix cap). +pub(super) fn sparse_profile() -> Profile { + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::Memfd; + profile.memfd_extents = leleka_deploy::profile::MemfdExtents::PleOnly; + profile.memory.prefix_cache_mib = Some("4096".into()); + profile.validate().unwrap(); + profile +} + +#[test] +fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims_the_archive_was_verified() + { + let fixture = Fixture::new("sparse"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let config = fixture.write_state(sparse_profile()); + let paths = fixture.dirs.paths(); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let pin = "ab".repeat(32); + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + let expected: String = if compiled == [0u8; 32] { + pin.clone() + } else { + compiled.iter().map(|b| format!("{b:02x}")).collect() + }; + let mut supervisor = start_supervisor_with_env( + &fixture, + &config, + Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), + &[("LELEKA_KAR_EXTENTS_SHA256", &pin)], + ); + let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + assert_eq!(ready["memfd_extents"], "ple_only"); + signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); + fixture.wait_for("engine restart", Duration::from_secs(60), |s| { + s["phase"] == "ready" && s["engine_restarts"] == 1 + }); + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); + let starts: Vec<&str> = calls + .lines() + .filter(|l| l.starts_with("leleka-inference ")) + .collect(); + assert_eq!(starts.len(), 2, "{calls}"); + for (i, line) in starts.iter().enumerate() { + assert!( + line.contains(&format!("--kar-sparse-extents-sha256 {expected}")), + "engine {i}: {line}" + ); + assert!(line.contains("--kar-archive-fd"), "{line}"); + // the memfd is not the archive: no attestation by a stamp of the archive file, not even for the restarted engine + assert!( + !line.contains("--kar-attested-by-stamp"), + "engine {i}: {line}" + ); + } + // and no stamp of the archive was recorded from it + let stamps: Vec = fs::read_dir(paths.stamps()) + .map(|d| { + d.flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default(); + assert!( + !stamps.iter().any(|name| name.starts_with("kar")), + "{stamps:?}" + ); + let log = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap_or_default() + + &fixture.logs(); + // (the sparse memfd was EXPERIMENTAL until it became the rtx5090-32g form; the digest line is the contract) + assert!(log.contains(&expected), "{log}"); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), + "{}", + fixture.logs() + ); +} + +#[test] +fn a_sparse_memfd_profile_starts_on_the_compiled_digest_and_refuses_when_none_is_pinned() { + let fixture = Fixture::new("sparse-nopin"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let config = fixture.write_state(sparse_profile()); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let mut supervisor = start_supervisor_with_env( + &fixture, + &config, + Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), + &[], + ); + if leleka_model_format::kar::PLE_EXTENTS_SHA256 != [0u8; 32] { + // the extents digest is pinned in the binary (the release form): no operator pin is needed and the supervisor starts + fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), + "{}", + fixture.logs() + ); + return; + } + let status = + wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must refuse"); + { + assert_eq!(status.code(), Some(1)); + let message = fixture.status().unwrap()["message"] + .as_str() + .unwrap() + .to_owned(); + assert!( + message.contains("kar_census") && message.contains("--hash-extents"), + "{message}" + ); + // no engine was started + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default(); + assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}"); + } +} + +#[test] +fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_cannot_seal() { + let dir = std::env::temp_dir().join(format!("leleka-seal-exec-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join("archive.bin"); + let bytes: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); + fs::write(&file, &bytes).unwrap(); + let run = |extra: &[&str]| { + Process::new(LELEKA) + .args(["seal-exec", "--file"]) + .arg(&file) + .args(extra) + .output() + .unwrap() + }; + let ok = run(&[ + "--expect-bytes", + "300000", + "--", + "sh", + "-c", + "wc -c < /proc/self/fd/{FD}; readlink /proc/self/fd/{FD}; cksum < /proc/self/fd/{FD}", + ]); + let out = String::from_utf8_lossy(&ok.stdout); + assert!( + ok.status.success(), + "{}{}", + out, + String::from_utf8_lossy(&ok.stderr) + ); + assert!( + out.contains("300000") && out.contains("/memfd:leleka-sealed-archive"), + "{out}" + ); + let want = Process::new("cksum") + .stdin(fs::File::open(&file).unwrap()) + .output() + .unwrap(); + assert!( + out.contains(String::from_utf8_lossy(&want.stdout).trim()), + "the descriptor holds the file byte for byte: {out}" + ); + // a wrong length, a missing command and the sparse form without its length are refused (exit 2), nothing is run + for extra in [ + vec!["--expect-bytes", "1", "--", "true"], + vec!["--expect-bytes", "300000"], + vec!["--sparse-ple", "--", "true"], + ] { + let refused = run(&extra); + assert_eq!( + refused.status.code(), + Some(2), + "{extra:?}: {}", + String::from_utf8_lossy(&refused.stderr) + ); + } + // a file that is not a KAR archive cannot be sealed sparse + let sparse = run(&["--sparse-ple", "--expect-bytes", "300000", "--", "true"]); + assert_eq!(sparse.status.code(), Some(2)); + assert!( + String::from_utf8_lossy(&sparse.stderr).contains("not a valid KAR archive"), + "{}", + String::from_utf8_lossy(&sparse.stderr) + ); + fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/deploy/tests/e2e/supervisor_lifecycle.rs b/crates/deploy/tests/e2e/supervisor_lifecycle.rs new file mode 100644 index 00000000..2c1b0061 --- /dev/null +++ b/crates/deploy/tests/e2e/supervisor_lifecycle.rs @@ -0,0 +1,128 @@ +//! The supervisor from start to ready to a clean stop, with each form of the archive. + +use crate::harness::*; +use leleka_deploy::profile::{KarSource, Profile}; +use std::{fs, os::unix::fs::PermissionsExt, time::Duration}; + +pub(super) fn lifecycle(source: KarSource) { + let fixture = Fixture::new(match source { + KarSource::Memfd => "memfd", + KarSource::File => "file", + KarSource::None => "none", + }); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = source; + let config = fixture.write_state(profile); + let paths = fixture.dirs.paths(); + let memfd = (source == KarSource::Memfd).then(|| inheritable_sealed_memfd(&vec![7u8; 100_000])); + if source == KarSource::File { + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(paths.kar(), b"archive").unwrap(); + } + let fd = memfd.as_ref().map(std::os::fd::AsRawFd::as_raw_fd); + let mut supervisor = start_supervisor(&fixture, &config, fd); + + let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + assert_eq!(ready["engine_restarts"], 0); + assert_eq!(fixture.http_status("/ready"), 200); + let (engine_pid, gateway_pid, api_pid) = ( + ready["engine_pid"].as_u64().unwrap(), + ready["gateway_pid"].as_u64().unwrap(), + ready["api_pid"].as_u64().unwrap(), + ); + let engine_log = fs::read_to_string(paths.logs().join("engine.log")).unwrap(); + match source { + KarSource::Memfd => assert!(engine_log.contains("kar fd "), "{engine_log}"), + KarSource::File => assert!(engine_log.contains("listening"), "{engine_log}"), + KarSource::None => {} + } + // The status file is private and never holds a secret. + let mode = fs::metadata(paths.status_file()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + assert!( + !fs::read_to_string(paths.status_file()) + .unwrap() + .contains(KEY) + ); + + // Kill the engine: the API reports not ready, the supervisor restarts it and loads again. + signal(engine_pid, "KILL"); + let again = fixture.wait_for("engine restart", Duration::from_secs(60), |s| { + s["phase"] == "ready" && s["engine_restarts"] == 1 + }); + assert_ne!(again["engine_pid"].as_u64().unwrap(), engine_pid); + assert_eq!( + again["gateway_pid"].as_u64().unwrap(), + gateway_pid, + "the gateway must survive an engine restart" + ); + assert_eq!( + again["api_pid"].as_u64().unwrap(), + api_pid, + "the API must survive an engine restart" + ); + assert_eq!(fixture.http_status("/ready"), 200); + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); + assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}"); + assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}"); + // The first engine hashed the sealed archive; the restarted one is told the same memfd was verified already + // (stamps are on by default), and both get the stamp directory. + let starts: Vec<&str> = calls + .lines() + .filter(|l| l.starts_with("leleka-inference ")) + .collect(); + assert!( + starts.iter().all(|l| l.contains("--verify-stamps")), + "{calls}" + ); + assert!( + !starts[0].contains("--kar-attested-by-stamp"), + "{}", + starts[0] + ); + assert_eq!( + starts[1].contains("--kar-attested-by-stamp"), + source == KarSource::Memfd, + "{}", + starts[1] + ); + // The sealed descriptor was reused, not copied again (one process held it the whole time). + assert!(!supervisor.try_wait().unwrap().is_some()); + + // SIGTERM drains and stops everything with status 0. + let new_engine = again["engine_pid"].as_u64().unwrap(); + signal(u64::from(supervisor.id()), "TERM"); + let status = wait_exit(&mut supervisor, Duration::from_secs(60)) + .expect("the supervisor must exit after SIGTERM"); + assert!(status.success(), "exit {status:?}\n{}", fixture.logs()); + assert_eq!(fixture.status().unwrap()["phase"], "stopped"); + for pid in [new_engine, gateway_pid, api_pid] { + assert!(!pid_alive(pid), "pid {pid} outlived the supervisor"); + } + assert_eq!( + fixture.http_status("/ready"), + 0, + "the API port must be closed" + ); + // No child ever saw the Hugging Face token (the fake engine exits 3 if it does). + assert!( + !fs::read_to_string(paths.logs().join("engine.log")) + .unwrap() + .contains("leaked") + ); +} + +#[test] +fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() { + lifecycle(KarSource::Memfd); +} + +#[test] +fn supervisor_lifecycle_with_a_read_only_archive_file() { + lifecycle(KarSource::File); +} diff --git a/crates/deploy/tests/e2e/up_flow.rs b/crates/deploy/tests/e2e/up_flow.rs new file mode 100644 index 00000000..829186b2 --- /dev/null +++ b/crates/deploy/tests/e2e/up_flow.rs @@ -0,0 +1,208 @@ +//! `leleka up`: idempotent, resumable, never rotating secrets, and the archive checks. + +use crate::harness::*; +use leleka_deploy::{ + app::run_up, + config::RunConfig, + plan::{FsState, plan_steps}, + steps::gather_fs, +}; +use std::{fs, os::unix::fs::PermissionsExt}; + +#[tokio::test] +async fn up_is_idempotent_resumable_and_never_rotates_secrets() { + let fixture = Fixture::new("up"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + // The fakes find their shared state through the *installed* bin directory. + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); + let paths = fixture.dirs.paths(); + + // First run: everything is a todo, then everything exists. + let ctx = healthy_context(&opts); + let fs0 = gather_fs(&ctx).await; + let steps = plan_steps(&ctx, &fs0); + assert!( + steps + .iter() + .filter(|s| matches!( + s.id, + "binaries" | "secrets" | "model" | "kar" | "tokenizer" | "config" | "mtp-pack" + )) + .all(|s| s.state.tag() == "todo") + ); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + for (what, file) in [ + ("binary", paths.bin("leleka-inference")), + ("run config", paths.run_config()), + ("env", paths.env_file()), + ("api key", paths.api_key()), + ("tokenizer", paths.tokenizer_dir()), + ("mtp", paths.mtp_pack().join("experts.bin")), + ("stamp", paths.stamps().join("model.json")), + ] { + assert!(file.exists(), "{what}: {} missing", file.display()); + } + assert_eq!( + fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + fs::metadata(paths.kar()).unwrap().permissions().mode() & 0o222, + 0, + "the file-mode archive must have no write bits" + ); + let config = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!(config.profile.name, "rtx3080-16g"); + let env_first = fs::read_to_string(paths.env_file()).unwrap(); + assert!( + env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())), + "{env_first}" + ); + assert_eq!( + ( + count_calls(&fixture, "model fetch"), + count_calls(&fixture, "ensure-sharded-streamed"), + count_calls(&fixture, "api-key init") + ), + (0, 1, 1), + "the archive step fetches and verifies the shards itself" + ); + + // Second run: the plan has nothing to do and no tool is invoked again. + let ctx = healthy_context(&opts); + let fs1 = gather_fs(&ctx).await; + let steps = plan_steps(&ctx, &fs1); + for step in &steps { + assert!( + matches!(step.state.tag(), "done" | "skip") || step.id == "preflight", + "{} is {:?} on a re-run", + step.id, + step.state + ); + } + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!( + ( + count_calls(&fixture, "model fetch"), + count_calls(&fixture, "model verify"), + count_calls(&fixture, "ensure-sharded-streamed"), + count_calls(&fixture, "extract-tokenizer") + ), + (0, 0, 1, 1) + ); + assert_eq!( + fs::read_to_string(paths.env_file()).unwrap(), + env_first, + "tokens must never rotate" + ); + + // Resumable: a lost archive is rebuilt, everything else is left alone. + fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap(); + fs::remove_file(paths.kar()).unwrap(); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!( + steps.iter().find(|s| s.id == "kar").unwrap().state.tag(), + "todo" + ); + assert_eq!( + steps.iter().find(|s| s.id == "model").unwrap().state.tag(), + "done" + ); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!( + ( + count_calls(&fixture, "model fetch"), + count_calls(&fixture, "ensure-sharded-streamed") + ), + (0, 2) + ); + + // --reverify forces the verification again. + let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]); + let ctx = healthy_context(&reverify); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!( + steps.iter().find(|s| s.id == "model").unwrap().state.tag(), + "todo" + ); + let _ = FsState::default(); +} + +#[tokio::test] +async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() { + let fixture = Fixture::new("trust"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &["--trust-archive"]); + let paths = fixture.dirs.paths(); + // An archive of the pinned length with its provenance sidecar, as left by an earlier build. + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::File::create(paths.kar()) + .unwrap() + .set_len(55_295_529_472) + .unwrap(); + fs::write(paths.kar_provenance(), "{}").unwrap(); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + let kar = steps.iter().find(|s| s.id == "kar").unwrap(); + assert_eq!(kar.state.tag(), "todo"); + assert!( + kar.state.why().contains("--trust-archive"), + "{:?}", + kar.state + ); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!( + ( + count_calls(&fixture, "model fetch"), + count_calls(&fixture, "model verify"), + count_calls(&fixture, "ensure-sharded-streamed") + ), + (1, 1, 0) + ); + assert!(paths.stamps().join("kar.json").exists() && paths.stamps().join("model.json").exists()); + // Without the flag the same archive would be re-verified by the real tool. + let strict = healthy_context(&up_options( + &fixture, + &bin_src, + &cublas, + &mtp, + &["--reverify"], + )); + let steps = plan_steps(&strict, &gather_fs(&strict).await); + assert!( + !steps + .iter() + .find(|s| s.id == "kar") + .unwrap() + .state + .why() + .contains("--trust-archive") + ); +} + +#[tokio::test] +async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() { + let fixture = Fixture::new("wrongkar"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); + // A pre-existing archive of the wrong length: the fake `ensure` reuses it, the size gate must object. + fs::create_dir_all(&fixture.dirs.assets).unwrap(); + fs::write(fixture.dirs.paths().kar(), b"short").unwrap(); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + let error = run_up(&ctx, &steps).await.unwrap_err(); + assert!(error.contains("engine only admits the pinned"), "{error}"); +} diff --git a/crates/deploy/tests/e2e/verify_commands.rs b/crates/deploy/tests/e2e/verify_commands.rs new file mode 100644 index 00000000..b9c8b408 --- /dev/null +++ b/crates/deploy/tests/e2e/verify_commands.rs @@ -0,0 +1,164 @@ +//! `leleka verify` (quick and full) and the exit code of a broken configuration. + +use crate::harness::*; +use leleka_deploy::{ + config::{GATEWAY_TOKEN_ENV, RUNTIME_TOKEN_ENV}, + profile::{KarSource, Profile}, +}; +use std::{fs, process::Command as Process, time::Duration}; + +#[test] +fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model() { + let fixture = Fixture::new("quick"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + let paths = fixture.dirs.paths(); + fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap(); + for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] { + fs::File::create(paths.shard(index)) + .unwrap() + .set_len(size) + .unwrap(); + } + fs::File::create(paths.kar()) + .unwrap() + .set_len(55_295_529_472) + .unwrap(); + let quick = || { + Process::new(LELEKA) + .args(["verify", "--quick", "--state-dir"]) + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap() + }; + // Not running: the files are there (unstamped, a note), the service is not (a problem). + let before = quick(); + let text = String::from_utf8_lossy(&before.stdout).into_owned(); + assert_eq!(before.status.code(), Some(1), "{text}"); + assert!( + text.contains("not stamped") + && text.contains("PROBLEM: the API does not answer") + && text.contains("health: NOT OK"), + "{text}" + ); + // Running: healthy. + let mut supervisor = start_supervisor(&fixture, &config, None); + fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + let after = quick(); + let text = String::from_utf8_lossy(&after.stdout).into_owned(); + assert_eq!(after.status.code(), Some(0), "{text}"); + assert!( + text.contains("health: OK") + && text.contains("API answers /ready: yes") + && text.contains("engine restarts 0 in total"), + "{text}" + ); + // `leleka status` shows the same supervisor facts. + let status = Process::new(LELEKA) + .args(["status", "--state-dir"]) + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&status.stdout).into_owned(); + assert!( + text.contains("supervisor: phase ready") && text.contains("health: "), + "{text}" + ); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure() { + let fixture = Fixture::new("verify"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::File; + fixture.write_state(profile); + let run = |fixture: &Fixture| { + Process::new(LELEKA) + .arg("verify") + .arg("--state-dir") + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap() + }; + let output = run(&fixture); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); + let line = calls + .lines() + .find(|l| l.starts_with("leleka-inference ")) + .unwrap(); + assert!( + line.contains("--verify-only") + && line.contains("--verify-rehash") + && line.contains("--verify-stamps"), + "{line}" + ); + // The file profile hands the archive to the engine (which stamps it itself) and no serving switches. + assert!( + line.contains("--kar-archive-file") && !line.contains("--backend-mode"), + "{line}" + ); + assert!(fixture.dirs.paths().engine_stamps().is_dir()); + fs::write(fixture.fake_dir().join("fail-verify"), "").unwrap(); + let output = run(&fixture); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("verification FAILED")); +} + +#[test] +fn a_broken_configuration_is_exit_code_two_with_a_clear_message() { + let fixture = Fixture::new("badconfig"); + fs::create_dir_all(&fixture.root).unwrap(); + let missing = fixture.root.join("nope.json"); + let output = Process::new(LELEKA) + .arg("run") + .arg("--config") + .arg(&missing) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2)); + let text = String::from_utf8_lossy(&output.stderr); + assert!(text.contains("run `leleka up` first"), "{text}"); + // Weak tokens are refused before anything starts. + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::File; + let config = fixture.write_state(profile); + fs::write( + fixture.dirs.paths().env_file(), + format!("{RUNTIME_TOKEN_ENV}=short\n{GATEWAY_TOKEN_ENV}=short\n"), + ) + .unwrap(); + let output = Process::new(LELEKA) + .arg("run") + .arg("--config") + .arg(&config) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("32..4096 printable ASCII")); +} diff --git a/limits-allowlist.json b/limits-allowlist.json index 37d52d9c..dc87695a 100644 --- a/limits-allowlist.json +++ b/limits-allowlist.json @@ -1291,6 +1291,1476 @@ "reason": "moved verbatim from the oversize test/source file it was split out of (STRA-338 size-gw); the function itself is legacy and shrinks in later batches", "owner": "STRA-338" }, + { + "path": "crates/deploy/src/app/entry.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/entry.rs", + "name": "main_native", + "fn_lines": 76, + "complexity": 21, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/install_flow.rs", + "name": "powershell_try", + "fn_lines": 5, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/install_flow.rs", + "name": "run_up", + "fn_lines": 67, + "complexity": 22, + "nesting": 4, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/install_flow.rs", + "name": "summary", + "fn_lines": 86, + "complexity": 8, + "nesting": 2, + "width": 3, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/install_flow.rs", + "name": "summary_json", + "fn_lines": 22, + "complexity": 1, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/install_flow.rs", + "name": "up", + "fn_lines": 52, + "complexity": 9, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/machine_tests.rs", + "name": "the_machine_view_names_every_figure_the_operator_asked_for", + "fn_lines": 31, + "complexity": 2, + "nesting": 2, + "width": 4, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/machine_tests.rs", + "name": "the_settings_block_lists_every_member_and_the_prefix_cache_on_one_line", + "fn_lines": 20, + "complexity": 2, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/preflight_report.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/preflight_report.rs", + "name": "seal_probe", + "fn_lines": 60, + "complexity": 7, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/settings_change.rs", + "name": "", + "width": 5, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/settings_change.rs", + "name": "ask_supervisor", + "fn_lines": 32, + "complexity": 10, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/settings_change.rs", + "name": "reconfigure_by_restart", + "fn_lines": 50, + "complexity": 6, + "nesting": 2, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/settings_change.rs", + "name": "render_machine", + "fn_lines": 87, + "complexity": 5, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/settings_change.rs", + "name": "send_reconfigure", + "fn_lines": 64, + "complexity": 10, + "nesting": 3, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/status_report.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/status_report.rs", + "name": "print_status", + "fn_lines": 45, + "complexity": 8, + "nesting": 2, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/status_report.rs", + "name": "render_supervisor", + "fn_lines": 51, + "complexity": 6, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/status_report.rs", + "name": "status", + "fn_lines": 44, + "complexity": 4, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/status_tests.rs", + "name": "the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor", + "fn_lines": 25, + "complexity": 5, + "nesting": 1, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/stop_flow.rs", + "name": "down", + "fn_lines": 38, + "complexity": 6, + "nesting": 3, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/verify_flow.rs", + "name": "", + "width": 3, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/verify_flow.rs", + "name": "verify", + "fn_lines": 124, + "complexity": 20, + "nesting": 3, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/app/verify_flow.rs", + "name": "verify_quick", + "fn_lines": 145, + "complexity": 26, + "nesting": 3, + "width": 3, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/cli_double.rs", + "name": "cli", + "fn_lines": 57, + "complexity": 12, + "nesting": 3, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/engine_double.rs", + "name": "engine", + "fn_lines": 83, + "complexity": 16, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/gateway_double.rs", + "name": "api", + "fn_lines": 33, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/gateway_double.rs", + "name": "respond", + "fn_lines": 74, + "complexity": 20, + "nesting": 3, + "width": 3, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/gateway_double.rs", + "name": "strata", + "fn_lines": 57, + "complexity": 9, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/bin/fake_runtime/main.rs", + "name": "main", + "fn_lines": 31, + "complexity": 5, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/cli/tests/flags.rs", + "name": "flags_accept_both_forms_and_reject_mistakes", + "fn_lines": 47, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/cli/tests/flags.rs", + "name": "logs_and_report_take_their_own_flags_and_the_locating_ones", + "fn_lines": 58, + "complexity": 10, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/cli/tests/flags.rs", + "name": "other_commands", + "fn_lines": 34, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/cli/tests/reconfigure_args.rs", + "name": "reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags", + "fn_lines": 47, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/cli/tests/reconfigure_args.rs", + "name": "reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags", + "fn_lines": 77, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/config/engine_launch.rs", + "name": "", + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/config/engine_launch.rs", + "name": "RunConfig::engine_args", + "fn_lines": 71, + "complexity": 10, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/config/tests.rs", + "name": "generated_configs_are_consistent", + "fn_lines": 35, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/config/tests.rs", + "name": "server_engine_command_matches_the_documented_one", + "fn_lines": 14, + "complexity": 1, + "nesting": 0, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/embedded_table.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/embedded_table.rs", + "name": "an_embedded_table_that_fails_its_digest_falls_back_to_the_download", + "fn_lines": 35, + "complexity": 2, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/embedded_table.rs", + "name": "the_embedded_table_is_installed_offline_before_any_download", + "fn_lines": 42, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/report.rs", + "name": "the_report_says_on_with_the_digest_or_off_with_the_reason", + "fn_lines": 46, + "complexity": 9, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/sources.rs", + "name": "a_download_is_verified_then_installed_and_a_present_file_is_left_alone", + "fn_lines": 37, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/expert_profile/tests/sources.rs", + "name": "a_local_file_is_installed_offline_and_a_wrong_one_is_refused", + "fn_lines": 60, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/facts/linux.rs", + "name": "probe", + "fn_lines": 121, + "complexity": 16, + "nesting": 4, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/facts/windows.rs", + "name": "probe", + "fn_lines": 101, + "complexity": 17, + "nesting": 4, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/gather_state.rs", + "name": "gather", + "fn_lines": 173, + "complexity": 24, + "nesting": 2, + "width": 4, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/render.rs", + "name": "render_plan", + "fn_lines": 48, + "complexity": 8, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests.rs", + "name": "context", + "fn_lines": 94, + "complexity": 7, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/expert_profile_steps.rs", + "name": "only_a_profile_with_another_digest_needs_a_download_or_a_file", + "fn_lines": 29, + "complexity": 4, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/expert_profile_steps.rs", + "name": "the_expert_profile_step_covers_every_state_and_never_stays_silent", + "fn_lines": 47, + "complexity": 10, + "nesting": 1, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/expert_profile_steps.rs", + "name": "the_gathered_environment_names_the_table_unless_the_tier_is_opted_out", + "fn_lines": 39, + "complexity": 3, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/install_steps.rs", + "name": "finished_deployment_is_done_except_nothing_to_do", + "fn_lines": 36, + "complexity": 3, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/install_steps.rs", + "name": "fresh_server_plans_every_step", + "fn_lines": 39, + "complexity": 2, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/install_steps.rs", + "name": "the_archive_step_covers_the_shards_and_trust_archive_does_not", + "fn_lines": 49, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/plan/tests/mode_resolution.rs", + "name": "mode_resolution", + "fn_lines": 32, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/preflight/tests/host_resources.rs", + "name": "an_inherited_sealed_archive_is_not_counted_twice", + "fn_lines": 27, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/preflight/tests/host_resources.rs", + "name": "laptop_under_default_wsl_memory_gets_wslconfig_advice", + "fn_lines": 38, + "complexity": 3, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/preflight/tests/windows_host.rs", + "name": "a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd", + "fn_lines": 48, + "complexity": 3, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/preflight/tests/windows_host.rs", + "name": "windows_laptop", + "fn_lines": 36, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/catalog.rs", + "name": "resolve", + "fn_lines": 38, + "complexity": 9, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/memory_budget.rs", + "name": "", + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/memory_budget.rs", + "name": "MemoryBudget::env", + "fn_lines": 41, + "complexity": 4, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/memory_budget.rs", + "name": "MemoryBudget::validate", + "fn_lines": 34, + "complexity": 15, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/profile_limits.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/profile_limits.rs", + "name": "Profile::validate", + "fn_lines": 80, + "complexity": 38, + "nesting": 2, + "width": 6, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/budget_arguments.rs", + "name": "the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_store", + "fn_lines": 38, + "complexity": 3, + "nesting": 1, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/budget_arguments.rs", + "name": "the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_environment", + "fn_lines": 32, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/builtin_profiles.rs", + "name": "only_the_server_profile_enables_the_mtp_draft_attention_switch", + "fn_lines": 25, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/builtin_profiles.rs", + "name": "only_the_server_profile_turns_the_prompt_routing_seed_off", + "fn_lines": 13, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/builtin_profiles.rs", + "name": "the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_matters", + "fn_lines": 71, + "complexity": 2, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/builtin_profiles.rs", + "name": "the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source", + "fn_lines": 64, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/sparse_memfd.rs", + "name": "only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized", + "fn_lines": 35, + "complexity": 3, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/profile/tests/sparse_memfd.rs", + "name": "the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent", + "fn_lines": 37, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/planning.rs", + "name": "a_budget_change_is_planned_against_the_host_and_keeps_everything_else", + "fn_lines": 44, + "complexity": 1, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/planning.rs", + "name": "an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset", + "fn_lines": 33, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/planning.rs", + "name": "the_resident_archive_is_not_charged_twice_to_the_host", + "fn_lines": 26, + "complexity": 1, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/planning.rs", + "name": "the_workstation_preset_applies_and_dedicated_undoes_it", + "fn_lines": 43, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/recording.rs", + "name": "persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context", + "fn_lines": 44, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/recording.rs", + "name": "recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win", + "fn_lines": 61, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/recording.rs", + "name": "the_effective_summary_names_the_numbers_in_force", + "fn_lines": 11, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/recording.rs", + "name": "the_request_and_answer_files_round_trip_and_a_request_runs_once", + "fn_lines": 45, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/settings_ranges.rs", + "name": "runtime_settings_become_profile_fields_with_the_engines_ranges", + "fn_lines": 84, + "complexity": 5, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/reconfigure/tests/settings_ranges.rs", + "name": "unsafe_values_are_refused_by_the_planner", + "fn_lines": 64, + "complexity": 3, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/sizing.rs", + "name": "", + "width": 7, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/sizing.rs", + "name": "apply", + "fn_lines": 70, + "complexity": 16, + "nesting": 3, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/sizing.rs", + "name": "compute", + "fn_lines": 168, + "complexity": 31, + "nesting": 4, + "width": 9, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/presets_and_workers.rs", + "name": "the_prompt_chunk_follows_what_the_gpu_budget_can_lend", + "fn_lines": 36, + "complexity": 1, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/presets_and_workers.rs", + "name": "workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known", + "fn_lines": 33, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/ram_fit.rs", + "name": "a_resident_sealed_archive_is_not_charged_to_the_footprint_twice", + "fn_lines": 44, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/ram_fit.rs", + "name": "a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credited_by_its_own_size", + "fn_lines": 40, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/ram_fit.rs", + "name": "the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archive", + "fn_lines": 44, + "complexity": 2, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/windows_presets.rs", + "name": "the_windows_file_backed_form_sizes_its_page_locked_experts_from_the_free_ram", + "fn_lines": 42, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/resources/tests/windows_presets.rs", + "name": "the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors", + "fn_lines": 42, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/exec_arguments.rs", + "name": "", + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/linux.rs", + "name": "", + "width": 6, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/linux.rs", + "name": "seal_exec", + "fn_lines": 43, + "complexity": 9, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/linux.rs", + "name": "seal_ranges", + "fn_lines": 143, + "complexity": 25, + "nesting": 5, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/linux/tests.rs", + "name": "a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes", + "fn_lines": 57, + "complexity": 6, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/sealed/linux/tests.rs", + "name": "seal_is_exact_sealed_unlinked_and_cloexec", + "fn_lines": 31, + "complexity": 5, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/api.rs", + "name": "Supervisor::wait_api_ready", + "fn_lines": 41, + "complexity": 10, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/children.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/children.rs", + "name": "Supervisor::child_env", + "fn_lines": 35, + "complexity": 7, + "nesting": 2, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/children.rs", + "name": "Supervisor::spawn", + "fn_lines": 35, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/engine.rs", + "name": "", + "width": 3, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/engine.rs", + "name": "Supervisor::load_model", + "fn_lines": 126, + "complexity": 25, + "nesting": 3, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/engine.rs", + "name": "Supervisor::recover_engine", + "fn_lines": 55, + "complexity": 7, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/engine.rs", + "name": "Supervisor::start_engine", + "fn_lines": 77, + "complexity": 19, + "nesting": 3, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/engine.rs", + "name": "Supervisor::wait_port", + "fn_lines": 38, + "complexity": 7, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/live_reconfigure.rs", + "name": "", + "width": 4, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/live_reconfigure.rs", + "name": "Supervisor::reconfigure", + "fn_lines": 164, + "complexity": 21, + "nesting": 5, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/logfile.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/logfile.rs", + "name": "Log::event", + "fn_lines": 31, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/signals.rs", + "name": "spawn_signal_task", + "fn_lines": 45, + "complexity": 11, + "nesting": 5, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/sparse.rs", + "name": "", + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/sparse.rs", + "name": "Supervisor::sparse_pin", + "fn_lines": 19, + "complexity": 4, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/startup.rs", + "name": "run_inner", + "fn_lines": 141, + "complexity": 20, + "nesting": 2, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/status.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/status.rs", + "name": "Supervisor::write_status", + "fn_lines": 31, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/supervise.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/supervise.rs", + "name": "Supervisor::drive", + "fn_lines": 338, + "complexity": 58, + "nesting": 4, + "width": 11, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/tests.rs", + "name": "operation_records_are_parsed_from_the_cli_output", + "fn_lines": 37, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/src/supervisor/tests.rs", + "name": "status_parsing_matches_the_gateway_document", + "fn_lines": 8, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/dry_run_and_usage.rs", + "name": "a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it", + "fn_lines": 42, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/dry_run_and_usage.rs", + "name": "dry_run_prints_the_plan_and_changes_nothing", + "fn_lines": 76, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/engine_supervision.rs", + "name": "a_hung_engine_is_killed_and_restarted_by_the_health_check", + "fn_lines": 45, + "complexity": 4, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/engine_supervision.rs", + "name": "a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone", + "fn_lines": 43, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/engine_supervision.rs", + "name": "a_refused_load_fails_fast_and_shows_the_engine_log", + "fn_lines": 34, + "complexity": 2, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/engine_supervision.rs", + "name": "engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end", + "fn_lines": 61, + "complexity": 2, + "nesting": 2, + "width": 2, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/engine_supervision.rs", + "name": "logs_past_their_limit_are_rotated_while_the_service_runs", + "fn_lines": 38, + "complexity": 4, + "nesting": 2, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/expert_profile_install.rs", + "name": "first_start_installs_the_embedded_expert_profile_without_a_network", + "fn_lines": 52, + "complexity": 2, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/expert_profile_install.rs", + "name": "up_installs_the_expert_profile_offline_and_reports_it", + "fn_lines": 143, + "complexity": 7, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/harness.rs", + "name": "Fixture::http_status", + "fn_lines": 14, + "complexity": 1, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/harness.rs", + "name": "Fixture::write_state", + "fn_lines": 24, + "complexity": 1, + "nesting": 0, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/harness.rs", + "name": "healthy_context", + "fn_lines": 45, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/harness.rs", + "name": "up_options_with", + "fn_lines": 52, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/reconfigure_flow.rs", + "name": "a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive", + "fn_lines": 87, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/reconfigure_flow.rs", + "name": "persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers", + "fn_lines": 66, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/reconfigure_flow.rs", + "name": "settings_alone_are_recorded_and_persisted_without_a_restart", + "fn_lines": 53, + "complexity": 1, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/reconfigure_flow.rs", + "name": "the_cli_asks_the_supervisor_and_prints_the_answer", + "fn_lines": 48, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/reconfigure_flow.rs", + "name": "what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one", + "fn_lines": 69, + "complexity": 2, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/sealed_archive.rs", + "name": "", + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/sealed_archive.rs", + "name": "a_sparse_memfd_profile_starts_on_the_compiled_digest_and_refuses_when_none_is_pinned", + "fn_lines": 39, + "complexity": 3, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/sealed_archive.rs", + "name": "a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims_the_archive_was_verified", + "fn_lines": 67, + "complexity": 4, + "nesting": 1, + "width": 1, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/sealed_archive.rs", + "name": "seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_cannot_seal", + "fn_lines": 65, + "complexity": 3, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/supervisor_lifecycle.rs", + "name": "lifecycle", + "fn_lines": 112, + "complexity": 8, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/up_flow.rs", + "name": "trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards", + "fn_lines": 54, + "complexity": 2, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/up_flow.rs", + "name": "up_is_idempotent_resumable_and_never_rotates_secrets", + "fn_lines": 122, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/verify_commands.rs", + "name": "a_broken_configuration_is_exit_code_two_with_a_clear_message", + "fn_lines": 32, + "complexity": 1, + "nesting": 0, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/verify_commands.rs", + "name": "verify_quick_reports_the_health_of_the_installation_without_reading_the_model", + "fn_lines": 72, + "complexity": 7, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, + { + "path": "crates/deploy/tests/e2e/verify_commands.rs", + "name": "verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure", + "fn_lines": 46, + "complexity": 4, + "nesting": 1, + "width": 0, + "reason": "moved verbatim from the oversize file it was split out of (STRA-338 size-deploy); the function itself is legacy and shrinks in later batches", + "owner": "STRA-338" + }, { "path": "desktop-core/src/bin/leleka-inference/evaluation_output.rs", "name": "operator_public_evaluation_output", diff --git a/limits-baseline.json b/limits-baseline.json index 9e1df9f9..3805db95 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -39,9 +39,9 @@ "nesting": 32 }, "leleka-deploy": { - "fn_lines": 105, - "width": 387, - "complexity": 53, + "fn_lines": 103, + "width": 339, + "complexity": 50, "nesting": 7 }, "leleka-engine-core": { @@ -257,7 +257,7 @@ }, "leleka-deploy": { "fn_lines": 89, - "width": 67 + "width": 63 }, "leleka-engine-core": { "fn_lines": 11,