diff --git a/.gitignore b/.gitignore index 501e2fd0..a14c6018 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ logs/ *.kar2 *.safetensors *.bin + +# Release tarballs made by scripts/package-release.py +/dist/ diff --git a/Cargo.lock b/Cargo.lock index 5e85acdf..44baf0e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1025,6 +1025,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "leleka-deploy" +version = "0.1.0" +dependencies = [ + "hex", + "rustix", + "serde", + "serde_json", + "sha2", + "tokio", +] + [[package]] name = "leleka-experimental-ref" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 26494d9a..42fbd853 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/deploy", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/crates/deploy/Cargo.toml b/crates/deploy/Cargo.toml new file mode 100644 index 00000000..024c3411 --- /dev/null +++ b/crates/deploy/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "leleka-deploy" +version = "0.1.0" +description = "One-command deployment of the Leleka runtime: preflight, model assets, install, supervision and readiness (no Python)" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lib] +name = "leleka_deploy" +path = "src/lib.rs" + +[[bin]] +name = "leleka" +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" +required-features = ["test-fakes"] + +[features] +test-fakes = [] + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.11" +hex = "0.4" +tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time", "sync", "net", "signal", "fs"] } + +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "=1.1.5", features = ["fs", "process", "stdio"] } + +[lints] +workspace = true diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs new file mode 100644 index 00000000..b704e60e --- /dev/null +++ b/crates/deploy/src/app.rs @@ -0,0 +1,427 @@ +//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`. +use crate::{ + cli::{Command, Environment, USAGE, UpOptions, parse}, + plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan}, + preflight::Report, + profile::{BUILTIN, Profile}, + steps::{self, gather_fs, say}, + supervisor, +}; +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()) +} + +fn is_root() -> bool { + #[cfg(target_os = "linux")] + { + rustix::process::geteuid().is_root() + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +pub async fn main_with(args: Vec) -> i32 { + let var = env_var; + let environment = Environment { + root: is_root(), + home: std::env::var_os("HOME").map(PathBuf::from), + 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!("leleka {}", env!("CARGO_PKG_VERSION")); + 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::Run { config, kar_fd } => { + supervisor::run(supervisor::Options { config, kar_fd }).await + } + Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka exec-inherit: {message}"); + 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); + 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 { + 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(), + "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(crate::profile::ARCHIVE_BYTES) + ), + crate::profile::KarSource::File => "a read-only file (page cache only)".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!(" 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() + )); + 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}"); +} + +/// 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 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, + }; + if opts.json { + println!( + "{}", + serde_json::to_string_pretty( + &json!({"ready": ready, "unit": unit, "supervisor": status}) + ) + .expect("serializable") + ); + } else { + println!("ready: {ready}"); + if let Some(unit) = unit { + println!("systemd unit {}: {unit}", paths.unit_name()); + } + match status { + Some(s) => println!( + "supervisor: phase {} (pid {}), engine restarts {}, updated {} + {}", + s["phase"].as_str().unwrap_or("?"), + s["supervisor_pid"], + s["engine_restarts"], + s["updated_unix"] + .as_u64() + .map(supervisor::format_utc) + .unwrap_or_default(), + s["message"].as_str().unwrap_or("") + ), + None => println!( + "supervisor: no status file in {} (never started?)", + paths.run_dir().display() + ), + } + } + i32::from(!ready) +} + +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 => { + 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 + } + } +} diff --git a/crates/deploy/src/bin/fake_runtime.rs b/crates/deploy/src/bin/fake_runtime.rs new file mode 100644 index 00000000..429d6405 --- /dev/null +++ b/crates/deploy/src/bin/fake_runtime.rs @@ -0,0 +1,361 @@ +//! 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("") + .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 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); + } + 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) { + let mut buffer = [0u8; 4096]; + let count = stream.read(&mut buffer).unwrap_or(0); + let request = String::from_utf8_lossy(&buffer[..count]).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(), + ), + _ => ("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/cli.rs b/crates/deploy/src/cli.rs new file mode 100644 index 00000000..ed6d6a97 --- /dev/null +++ b/crates/deploy/src/cli.rs @@ -0,0 +1,499 @@ +//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`. +use crate::{config::Ports, layout::Dirs}; +use std::{collections::BTreeMap, path::PathBuf}; + +pub const USAGE: &str = "\ +leleka - one-command deployment of the Leleka runtime + +USAGE + leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready + leleka preflight [OPTIONS] only the host checks (exit 1 when one fails) + leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API) + leleka status [OPTIONS] service state and readiness + leleka down [OPTIONS] stop the systemd service + leleka profiles [show NAME] list the memory profiles, or print one as JSON + leleka version + +UP / PREFLIGHT OPTIONS + --dry-run print the plan and the preflight, change nothing + --json machine-readable plan / summary on stdout + --profile auto|NAME|FILE memory profile (default auto: chosen from the GPU) + --gpu N CUDA device ordinal (default 0) + --assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS] + --state-dir DIR configs, tokens, logs, status [$LELEKA_STATE] + --prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX] + --bin-src DIR where to take the six binaries from (default: the directory of this binary) + --mode auto|system|user|foreground|none + --foreground same as --mode foreground (WSL without systemd, containers, terminals) + --api-port N API port (default 8081) + --api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port + is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS) + --engine-port N engine gRPC port (default 18766) + --daemon-port N gateway port (default 18080) + --gpu-budget-gib N override the profile's GPU memory budget + --context-tokens N override the profile's context ceiling + --no-fetch never download or build; require the model files to exist + --reverify ignore the verification stamps and hash everything again + --trust-archive accept an existing archive of the pinned length + its provenance file without the + strict re-derivation (hours-scale); the engine still checks its SHA-256 and every + CRC against the pinned digest at each load + --mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets + --cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading + --no-install-cublas fail instead of downloading cuBLAS 12.9.1.4 + --timeout-s N wait this long for readiness (default 3600) + --kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again, + its RAM is not required (foreground / --mode none only) + --service-user NAME system unit only: account the service runs as (default leleka, created if missing) + +ENVIRONMENT + HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co) +"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ModeChoice { + Auto, + System, + User, + Foreground, + None, +} + +#[derive(Clone, Debug)] +pub struct UpOptions { + pub dry_run: bool, + pub json: bool, + pub profile: Option, + pub gpu: u32, + pub dirs: Dirs, + pub bin_src: Option, + pub mode: ModeChoice, + pub ports: Ports, + pub gpu_budget_gib: Option, + pub context_tokens: Option, + pub fetch: bool, + pub reverify: bool, + /// Accept an existing archive of the pinned length without the strict F32 re-derivation. + pub trust_archive: bool, + pub mtp_pack: Option, + pub cublas_dir: Option, + pub install_cublas: bool, + pub timeout_s: u64, + /// System unit only: the account the service runs as (created when missing). Default `leleka`. + pub service_user: Option, + /// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs). + pub kar_fd: Option, +} + +#[derive(Debug)] +pub enum Command { + Up(UpOptions), + Preflight(UpOptions), + Run { + config: PathBuf, + kar_fd: Option, + }, + ExecInherit(Vec), + Status(UpOptions), + Down(UpOptions), + Profiles(Option), + Version, + Help, +} + +type Flags = BTreeMap>; + +const UP_FLAGS: &[(&str, bool)] = &[ + ("--dry-run", false), + ("--json", false), + ("--profile", true), + ("--gpu", true), + ("--assets", true), + ("--state-dir", true), + ("--prefix", true), + ("--bin-src", true), + ("--mode", true), + ("--foreground", false), + ("--api-port", true), + ("--api-bind", true), + ("--engine-port", true), + ("--daemon-port", true), + ("--gpu-budget-gib", true), + ("--context-tokens", true), + ("--no-fetch", false), + ("--reverify", false), + ("--trust-archive", false), + ("--mtp-pack", true), + ("--cublas-dir", true), + ("--no-install-cublas", false), + ("--timeout-s", true), + ("--service-user", true), + ("--kar-fd", true), +]; + +fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result { + let mut flags = Flags::new(); + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + let (name, inline) = match arg.split_once('=') { + Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), + _ => (arg.as_str(), None), + }; + let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else { + return Err(format!("unknown option {name:?}; see `leleka --help`")); + }; + let value = if *takes_value { + match inline { + Some(value) => Some(value), + None => { + index += 1; + Some( + args.get(index) + .ok_or_else(|| format!("{name} needs a value"))? + .clone(), + ) + } + } + } else if inline.is_some() { + return Err(format!("{name} takes no value")); + } else { + None + }; + if flags.insert(name.to_owned(), value).is_some() { + return Err(format!("{name} given twice")); + } + index += 1; + } + Ok(flags) +} + +fn number(flags: &Flags, name: &str, default: T) -> Result { + match flags.get(name) { + None => Ok(default), + Some(value) => value + .as_deref() + .unwrap_or("") + .parse() + .map_err(|_| format!("{name} needs a number")), + } +} + +/// `--api-bind IP`: where the public API listens. Loopback unless asked; the engine and the gateway always +/// stay on loopback. A non-loopback bind is for containers (publish the port to 127.0.0.1 on the host). +fn api_bind(flags: &Flags) -> Result { + match text(flags, "--api-bind") { + None => Ok("127.0.0.1".into()), + Some(ip) => match ip.parse::() { + Ok(std::net::IpAddr::V4(v4)) => Ok(v4.to_string()), + Ok(std::net::IpAddr::V6(_)) => Err("--api-bind takes an IPv4 address".into()), + Err(_) => Err(format!("--api-bind needs an IP address, not {ip:?}")), + }, + } +} + +fn ranged( + flags: &Flags, + name: &str, + range: std::ops::RangeInclusive, +) -> Result, String> { + if !flags.contains_key(name) { + return Ok(None); + } + let value: T = number(flags, name, *range.start())?; + if !range.contains(&value) { + return Err(format!("{name} must be {}..{}", range.start(), range.end())); + } + Ok(Some(value)) +} + +fn text<'a>(flags: &'a Flags, name: &str) -> Option<&'a str> { + flags.get(name).and_then(|v| v.as_deref()) +} + +fn port(flags: &Flags, name: &str, default: u16) -> Result { + let value: u16 = number(flags, name, default)?; + if value < 1024 { + return Err(format!("{name} must be 1024..65535")); + } + Ok(value) +} + +/// Environment access is injected so that parsing is testable. +pub struct Environment<'a> { + pub root: bool, + pub home: Option, + pub var: &'a dyn Fn(&str) -> Option, +} + +fn up_options(args: &[String], env: &Environment) -> Result { + let flags = parse_flags(args, UP_FLAGS)?; + let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var); + let abs = |name: &str, fallback: PathBuf| -> Result { + let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback); + if !path.is_absolute() { + return Err(format!( + "{name} must be an absolute path (got {})", + path.display() + )); + } + Ok(path) + }; + let dirs = Dirs { + prefix: abs("--prefix", defaults.prefix)?, + state: abs("--state-dir", defaults.state)?, + assets: abs("--assets", defaults.assets)?, + }; + let mode = if flags.contains_key("--foreground") { + if flags.contains_key("--mode") { + return Err("use either --foreground or --mode".into()); + } + ModeChoice::Foreground + } else { + match text(&flags, "--mode").unwrap_or("auto") { + "auto" => ModeChoice::Auto, + "system" => ModeChoice::System, + "user" => ModeChoice::User, + "foreground" => ModeChoice::Foreground, + "none" => ModeChoice::None, + other => { + return Err(format!( + "--mode must be auto, system, user, foreground or none, not {other:?}" + )); + } + } + }; + let kar_fd = match flags.get("--kar-fd") { + None => None, + Some(_) => { + let fd: u32 = number(&flags, "--kar-fd", 0u32)?; + if !(3..=1_048_576).contains(&fd) { + return Err( + "--kar-fd must be an inherited descriptor number of 3 or higher".into(), + ); + } + if matches!(mode, ModeChoice::System | ModeChoice::User) { + return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into()); + } + Some(fd) + } + }; + if mode == ModeChoice::System && !env.root { + return Err("--mode system needs root (use sudo), or --mode user / --foreground".into()); + } + let ports = Ports { + api: format!( + "{}:{}", + api_bind(&flags)?, + port(&flags, "--api-port", 8081)? + ), + engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?), + daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?), + }; + let distinct = [&ports.api, &ports.engine, &ports.daemon]; + if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] { + return Err("the API, engine and gateway ports must differ".into()); + } + let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from); + if let Some(dir) = &cublas_dir + && !dir.is_absolute() + { + return Err("--cublas-dir must be an absolute path".into()); + } + Ok(UpOptions { + dry_run: flags.contains_key("--dry-run"), + json: flags.contains_key("--json"), + profile: text(&flags, "--profile").map(str::to_owned), + gpu: number(&flags, "--gpu", 0u32)?, + dirs, + bin_src: text(&flags, "--bin-src").map(PathBuf::from), + mode, + ports, + gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?, + context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?, + service_user: text(&flags, "--service-user").map(str::to_owned), + kar_fd, + fetch: !flags.contains_key("--no-fetch"), + reverify: flags.contains_key("--reverify"), + trust_archive: flags.contains_key("--trust-archive"), + mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), + cublas_dir, + install_cublas: !flags.contains_key("--no-install-cublas"), + timeout_s: { + let value: u64 = number(&flags, "--timeout-s", 3600)?; + if !(1..=86_400).contains(&value) { + return Err("--timeout-s must be 1..86400".into()); + } + value + }, + }) +} + +pub fn parse(args: &[String], env: &Environment) -> Result { + let Some((command, rest)) = args.split_first() else { + return Ok(Command::Help); + }; + match command.as_str() { + "-h" | "--help" | "help" => Ok(Command::Help), + "version" | "--version" | "-V" => Ok(Command::Version), + "up" => up_options(rest, env).map(Command::Up), + "preflight" => up_options(rest, env).map(Command::Preflight), + "status" => up_options(rest, env).map(Command::Status), + "down" => up_options(rest, env).map(Command::Down), + "profiles" => match rest { + [] => Ok(Command::Profiles(None)), + [show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))), + _ => Err("usage: leleka profiles [show NAME]".into()), + }, + "run" => { + let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?; + let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?; + Ok(Command::Run { + config: PathBuf::from(config), + kar_fd: flags + .get("--kar-fd") + .map(|_| number(&flags, "--kar-fd", 0u32)) + .transpose()?, + }) + } + "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), + other => Err(format!("unknown command {other:?}; see `leleka --help`")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + fn parse_as(root: bool, args: &[&str]) -> Result { + let var = |_: &str| None; + parse( + &strings(args), + &Environment { + root, + home: Some("/home/para".into()), + var: &var, + }, + ) + } + + #[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 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 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()); + } + + #[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(_) + )); + } +} diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs new file mode 100644 index 00000000..698da8a3 --- /dev/null +++ b/crates/deploy/src/config.rs @@ -0,0 +1,463 @@ +//! The run configuration written by `up` and read by `run`, and the generated configs of the child processes. +//! +//! `leleka.json` holds no secret. Tokens live in `runtime.env` (mode 0600) and reach the children only through +//! their environment, never through argv. +use crate::{ + layout::{Dirs, MODEL_DIGEST, MODEL_ID, MTP_PROFILE, Paths}, + profile::{KarSource, Profile}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +pub const SCHEMA_VERSION: u32 = 1; +pub const RUNTIME_TOKEN_ENV: &str = "LELEKA_RUNTIME_TOKEN"; +pub const GATEWAY_TOKEN_ENV: &str = "LELEKA_GATEWAY_TOKEN"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Ports { + pub api: String, + pub engine: String, + pub daemon: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RestartPolicy { + /// Engine restarts the supervisor performs before it gives up (each one re-reads the archive). + pub max_engine_restarts: u32, + /// An engine that stayed ready this long resets the restart counter. + pub stable_after_s: u64, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RunConfig { + pub schema_version: u32, + pub leleka_version: String, + pub model_id: String, + pub model_digest: String, + pub prefix: String, + pub state: String, + pub assets: String, + pub ports: Ports, + pub gpu: u32, + pub profile: Profile, + /// Extra engine environment resolved by `up` (for example the expert-profile path when that file is valid). + #[serde(default)] + pub engine_env: BTreeMap, + pub load_timeout_s: u64, + pub shutdown_grace_s: u64, + pub restart: RestartPolicy, +} + +/// How the engine receives the archive on its command line. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KarArg { + /// `--kar-archive-fd {FD}`: the shim substitutes the descriptor number. + Fd, + /// `--kar-archive-file PATH`. + File, +} + +impl RunConfig { + pub fn new( + dirs: &Dirs, + ports: Ports, + gpu: u32, + profile: Profile, + engine_env: BTreeMap, + ) -> Self { + RunConfig { + schema_version: SCHEMA_VERSION, + leleka_version: env!("CARGO_PKG_VERSION").to_owned(), + model_id: MODEL_ID.to_owned(), + model_digest: MODEL_DIGEST.to_owned(), + prefix: dirs.prefix.display().to_string(), + state: dirs.state.display().to_string(), + assets: dirs.assets.display().to_string(), + ports, + gpu, + profile, + engine_env, + load_timeout_s: 1800, + shutdown_grace_s: 10, + restart: RestartPolicy { + max_engine_restarts: 2, + stable_after_s: 600, + }, + } + } + + pub fn dirs(&self) -> Dirs { + Dirs { + prefix: self.prefix.clone().into(), + state: self.state.clone().into(), + assets: self.assets.clone().into(), + } + } + + pub fn paths(&self) -> Paths { + self.dirs().paths() + } + + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != SCHEMA_VERSION { + return Err(format!( + "leleka.json has schema_version {}, this binary understands {SCHEMA_VERSION}; rerun `leleka up`", + self.schema_version + )); + } + self.profile.validate()?; + for (name, address, must_be_loopback) in [ + ("api", &self.ports.api, false), + ("engine", &self.ports.engine, true), + ("daemon", &self.ports.daemon, true), + ] { + let parsed: std::net::SocketAddr = address + .parse() + .map_err(|_| format!("ports.{name} must be a literal ip:port"))?; + // Only the API may leave the loopback interface (containers); the engine and the gateway never. + if must_be_loopback && !parsed.ip().is_loopback() { + return Err(format!( + "ports.{name} must be a loopback address (use an SSH tunnel for remote access)" + )); + } + } + Ok(()) + } + + pub fn read(path: &std::path::Path) -> Result { + let bytes = std::fs::read(path).map_err(|error| { + format!( + "cannot read {}: {error}; run `leleka up` first", + path.display() + ) + })?; + let config: RunConfig = serde_json::from_slice(&bytes) + .map_err(|error| format!("invalid {}: {error}", path.display()))?; + 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(), + ]), + } + args.extend([ + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + "--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(), + ]); + 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()]); + } + args + } + + pub fn kar_arg(&self) -> KarArg { + match self.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + } + } + + /// 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.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": MTP_PROFILE}, + "max_context": self.profile.context_tokens, + "max_output_tokens": 4096, + } + }) + } +} + +/// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on +/// the loopback interface. +pub fn probe_address(bind: &str) -> Option { + let address: std::net::SocketAddr = bind.parse().ok()?; + Some(if address.ip().is_unspecified() { + std::net::SocketAddr::from(([127, 0, 0, 1], address.port())) + } else { + address + }) +} + +/// Pretty JSON with a trailing newline, the byte form that is written and compared. +pub fn to_file_text(value: &impl Serialize) -> String { + let mut text = serde_json::to_string_pretty(value).expect("serializable"); + text.push('\n'); + text +} + +/// `n` random bytes from the kernel. Linux only (the deployment is). +pub fn random_bytes(n: usize) -> Result, String> { + use std::io::Read; + let mut bytes = vec![0u8; n]; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes)) + .map_err(|error| format!("cannot read /dev/urandom: {error}"))?; + Ok(bytes) +} + +/// A 48-character lower-case hex token (192 bits), inside the 32..4096 printable-ASCII rule of the runtime. +pub fn new_token() -> Result { + Ok(hex::encode(random_bytes(24)?)) +} + +/// Update `KEY=VALUE` lines of a systemd environment file in place, appending missing keys and keeping every +/// other line (including secrets) byte for byte. +pub fn merge_env(existing: &str, updates: &[(&str, String)]) -> String { + let mut lines: Vec = existing.lines().map(str::to_owned).collect(); + for (key, value) in updates { + let prefix = format!("{key}="); + let mut found = false; + for line in lines.iter_mut() { + if line.trim_start().starts_with(&prefix) { + *line = format!("{key}={value}"); + found = true; + break; + } + } + if !found { + lines.push(format!("{key}={value}")); + } + } + let mut text = lines.join("\n"); + text.push('\n'); + text +} + +/// The header comment of a freshly created `runtime.env`. +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::*; + + 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 = args.join(" "); + // 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 25769803776 --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")); + // The engine parser reads the first 14 arguments positionally. + assert_eq!(args[..14].len(), 14); + assert_eq!(args[12], "--context-tokens"); + } + + #[test] + fn laptop_uses_the_file_source_and_a_small_context() { + let config = config("rtx3080-16g"); + assert_eq!(config.kar_arg(), KarArg::File); + let text = config.engine_args(config.kar_arg()).join(" "); + assert!( + text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance") + ); + assert!(text.contains("--gpu-budget 16106127360 --context-tokens 8192")); + assert!(text.contains("--expert-source mapped")); + assert!(!text.contains("{FD}")); + } + + #[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"], + "/data/leleka/tokenizer-assets/tokenizer" + ); + assert_eq!(strata["runtime"]["max_context"], 262144); + // 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 + ); + } + + #[cfg(target_os = "linux")] + #[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 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/facts.rs b/crates/deploy/src/facts.rs new file mode 100644 index 00000000..bbc3ee8e --- /dev/null +++ b/crates/deploy/src/facts.rs @@ -0,0 +1,510 @@ +//! Host facts for the preflight: pure parsers (unit-tested on any OS) and a Linux probe that fills `Facts`. +//! +//! `Facts` is plain data so that `preflight::evaluate` can be tested with synthetic hosts. Nothing here creates +//! a CUDA context; the GPU is read through `nvidia-smi`. +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Gpu { + pub index: u32, + pub name: String, + pub driver: String, + pub vram_total_mib: u64, + pub vram_free_mib: u64, + /// Compute capability times ten (12.0 -> 120, 8.6 -> 86). + pub sm: Option, +} + +impl Gpu { + pub fn driver_major(&self) -> Option { + self.driver.split('.').next()?.parse().ok() + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Memory { + pub total: u64, + pub available: u64, + pub swap_total: u64, +} + +/// What `probe` reads about one directory the deployment will write to. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DirFact { + pub path: PathBuf, + /// Free bytes of the file system that holds (or would hold) the directory. + pub free_bytes: Option, + /// File system type of the mount that holds it (`ext4`, `9p`, `drvfs`, ...). + pub fs_type: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct Facts { + pub os: String, + pub arch: String, + pub root: bool, + pub nvidia_smi_found: bool, + pub nvidia_smi_error: Option, + pub gpus: Vec, + pub memory: Memory, + /// `memory.max` of the cgroup this process runs in, when limited. + pub cgroup_memory_max: Option, + pub wsl: bool, + pub systemd_system: bool, + pub proc_fd: bool, + pub memfd_ok: bool, + pub libs: BTreeMap>, + pub tools: BTreeMap, + pub dirs: BTreeMap, + pub busy_ports: Vec, + pub binaries: BTreeMap, + pub hf_token_set: bool, +} + +impl Facts { + pub fn lib(&self, soname: &str) -> Option<&PathBuf> { + self.libs.get(soname).and_then(Option::as_ref) + } + pub fn tool(&self, name: &str) -> bool { + self.tools.get(name).copied().unwrap_or(false) + } +} + +/// `nvidia-smi --query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap --format=csv,noheader,nounits`. +/// A missing or "[N/A]" compute capability falls back to a name table so older drivers still classify. +pub fn parse_nvidia_smi(csv: &str) -> Vec { + csv.lines() + .filter_map(|line| { + let fields: Vec<&str> = line.split(',').map(str::trim).collect(); + if fields.len() < 5 { + return None; + } + let index = fields[0].parse().ok()?; + let name = fields[1].to_owned(); + let sm = fields + .get(5) + .and_then(|cc| parse_compute_capability(cc)) + .or_else(|| sm_from_name(&name)); + Some(Gpu { + index, + driver: fields[2].to_owned(), + vram_total_mib: fields[3].parse().ok()?, + vram_free_mib: fields[4].parse().ok()?, + name, + sm, + }) + }) + .collect() +} + +pub fn parse_compute_capability(text: &str) -> Option { + let (major, minor) = text.trim().split_once('.')?; + let (major, minor): (u32, u32) = (major.parse().ok()?, minor.parse().ok()?); + (minor < 10).then_some(major * 10 + minor) +} + +fn sm_from_name(name: &str) -> Option { + const TABLE: [(&str, u32); 8] = [ + ("RTX 50", 120), + ("RTX 40", 89), + ("RTX 3090", 86), + ("RTX 30", 86), + ("RTX 20", 75), + ("A100", 80), + ("H100", 90), + ("L40", 89), + ]; + TABLE + .iter() + .find(|(needle, _)| name.contains(needle)) + .map(|(_, sm)| *sm) +} + +/// `/proc/meminfo` in bytes. `MemAvailable` is required; a kernel without it yields zeros (the caller fails closed). +pub fn parse_meminfo(text: &str) -> Memory { + let value = |key: &str| -> u64 { + text.lines() + .find_map(|line| line.strip_prefix(key)?.strip_prefix(':')) + .and_then(|rest| rest.split_whitespace().next()?.parse::().ok()) + .map_or(0, |kib| kib.saturating_mul(1024)) + }; + Memory { + total: value("MemTotal"), + available: value("MemAvailable"), + swap_total: value("SwapTotal"), + } +} + +/// WSL2 identifies itself in the kernel version string (`...-microsoft-standard-WSL2`). +pub fn is_wsl(proc_version: &str) -> bool { + let lower = proc_version.to_ascii_lowercase(); + lower.contains("microsoft") || lower.contains("wsl") +} + +/// `memory.max` content: a byte count, or `max` for unlimited. +pub fn parse_cgroup_max(text: &str) -> Option { + text.trim().parse().ok() +} + +/// File system type of the longest mount point that contains `path` (`/proc/mounts` format). +pub fn fs_type_for(mounts: &str, path: &Path) -> Option { + let mut best: Option<(usize, String)> = None; + for line in mounts.lines() { + let mut fields = line.split_whitespace(); + let (Some(_device), Some(mount), Some(kind)) = + (fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let mount = mount.replace("\\040", " "); + let mount_path = Path::new(&mount); + if path.starts_with(mount_path) && best.as_ref().is_none_or(|(len, _)| mount.len() >= *len) + { + best = Some((mount.len(), kind.to_owned())); + } + } + best.map(|(_, kind)| kind) +} + +/// File system types that are a Windows drive or a network share seen from WSL: far too slow for mapped reads. +pub fn is_slow_foreign_fs(kind: &str) -> bool { + matches!( + kind, + "9p" | "drvfs" | "virtiofs" | "cifs" | "smb3" | "nfs" | "nfs4" | "fuse.sshfs" + ) +} + +/// First directory in `dirs` that holds a file called `soname`, or the `ldconfig -p` entry for it. +pub fn find_library(soname: &str, dirs: &[PathBuf], ldconfig: &str) -> Option { + for dir in dirs { + let candidate = dir.join(soname); + if candidate.exists() { + return Some(candidate); + } + } + ldconfig.lines().find_map(|line| { + let line = line.trim(); + let (name, rest) = line.split_once(" (")?; + if name.trim() != soname { + return None; + } + let path = rest.split_once("=>")?.1.trim(); + Some(PathBuf::from(path)) + }) +} + +/// Parse `KEY=VALUE` lines of an environment file (systemd `EnvironmentFile` subset: no export, `#` comments). +pub fn parse_env_file(text: &str) -> BTreeMap { + text.lines() + .filter_map(|line| { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + let (key, value) = line.split_once('=')?; + let key = key.trim(); + if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + let value = value.trim(); + let value = value + .strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + .unwrap_or(value); + Some((key.to_owned(), value.to_owned())) + }) + .collect() +} + +/// What `probe` must look at beyond the machine itself. +#[derive(Clone, Debug, Default)] +pub struct ProbeRequest { + pub dirs: Vec<(String, PathBuf)>, + pub ports: Vec, + pub binary_dir: Option, + pub binaries: Vec, + pub extra_library_dirs: Vec, +} + +#[cfg(target_os = "linux")] +pub fn probe(request: &ProbeRequest) -> Facts { + linux::probe(request) +} + +#[cfg(not(target_os = "linux"))] +pub fn probe(_request: &ProbeRequest) -> Facts { + Facts { + os: std::env::consts::OS.to_owned(), + arch: std::env::consts::ARCH.to_owned(), + ..Facts::default() + } +} + +#[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()), + ..Facts::default() + }; + facts.wsl = is_wsl(&read("/proc/version")); + facts.memory = parse_meminfo(&read("/proc/meminfo")); + 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) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nvidia_smi_csv_for_server_and_laptop() { + let server = + parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n"); + assert_eq!(server.len(), 1); + assert_eq!(server[0].sm, Some(120)); + assert_eq!(server[0].driver_major(), Some(595)); + assert_eq!(server[0].vram_free_mib, 32105); + let laptop = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n"); + assert_eq!(laptop[0].sm, Some(86)); + assert_eq!(laptop[0].driver_major(), Some(617)); + } + + #[test] + fn missing_compute_capability_falls_back_to_the_name_table() { + let gpus = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n"); + assert_eq!(gpus[0].sm, Some(86)); + let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n"); + assert_eq!(gpus[0].sm, Some(120)); + let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n"); + assert_eq!(gpus[0].sm, None); + assert!(parse_nvidia_smi("garbage\n\n").is_empty()); + } + + #[test] + fn meminfo_bytes() { + let memory = parse_meminfo( + "MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n", + ); + assert_eq!(memory.total, 24_447_308 * 1024); + assert_eq!(memory.available, 22_000_000 * 1024); + assert_eq!(memory.swap_total, 2_097_152 * 1024); + assert_eq!(parse_meminfo("nothing"), Memory::default()); + } + + #[test] + fn wsl_and_cgroup_detection() { + assert!(is_wsl( + "Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)" + )); + assert!(!is_wsl( + "Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)" + )); + assert_eq!(parse_cgroup_max("max\n"), None); + assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736)); + } + + #[test] + fn filesystem_type_uses_the_longest_mount_prefix() { + let mounts = + "/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n"; + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(), + Some("9p") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(), + Some("ext4") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/home/x")).as_deref(), + Some("ext4") + ); + assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4")); + } + + #[test] + fn library_lookup_prefers_directories_then_ldconfig() { + let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n"; + assert_eq!( + find_library("libcublas.so.12", &[], ldconfig), + Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12")) + ); + assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None); + } + + #[test] + fn env_file_parser_handles_comments_and_quotes() { + let env = parse_env_file( + "# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n", + ); + assert_eq!(env.get("A").map(String::as_str), Some("1")); + assert_eq!(env.get("B").map(String::as_str), Some("two words")); + assert_eq!( + env.get("LD_LIBRARY_PATH").map(String::as_str), + Some("/a:/b") + ); + assert!(!env.contains_key("bad key")); + assert!(!env.contains_key("export X")); + } +} diff --git a/crates/deploy/src/http.rs b/crates/deploy/src/http.rs new file mode 100644 index 00000000..ea2dc0c0 --- /dev/null +++ b/crates/deploy/src/http.rs @@ -0,0 +1,195 @@ +//! A minimal HTTP/1.1 GET against a loopback address. The readiness probes need nothing more, and a hand-written +//! client keeps TLS, redirects and proxies out of a path that must only ever talk to 127.0.0.1. +use std::{net::SocketAddr, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, + time::timeout, +}; + +const MAX_RESPONSE: usize = 64 * 1024; + +#[derive(Debug, PartialEq, Eq)] +pub struct Response { + pub status: u16, + pub body: String, +} + +/// `GET path` with an optional bearer token. Errors are plain strings that never contain the token. +pub async fn get( + address: SocketAddr, + path: &str, + bearer: Option<&str>, + limit: Duration, +) -> Result { + if !address.ip().is_loopback() { + return Err("readiness probes talk to loopback addresses only".into()); + } + if !path.starts_with('/') || path.bytes().any(|b| b <= b' ' || b == 0x7f) { + return Err("invalid request path".into()); + } + let exchange = async { + let mut stream = TcpStream::connect(address) + .await + .map_err(|e| e.to_string())?; + let mut request = format!( + "GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\nAccept: application/json\r\n" + ); + if let Some(token) = bearer { + request.push_str(&format!("Authorization: Bearer {token}\r\n")); + } + request.push_str("\r\n"); + stream + .write_all(request.as_bytes()) + .await + .map_err(|e| e.to_string())?; + let mut raw = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let count = stream.read(&mut chunk).await.map_err(|e| e.to_string())?; + if count == 0 { + break; + } + raw.extend_from_slice(&chunk[..count]); + if raw.len() > MAX_RESPONSE { + return Err("response exceeds 64 KiB".to_owned()); + } + } + parse_response(&raw) + }; + timeout(limit, exchange) + .await + .map_err(|_| "request timed out".to_owned())? +} + +pub fn parse_response(raw: &[u8]) -> Result { + let text = String::from_utf8_lossy(raw); + let (head, body) = text + .split_once("\r\n\r\n") + .ok_or("malformed HTTP response")?; + let status_line = head.lines().next().ok_or("empty HTTP response")?; + let mut parts = status_line.split_whitespace(); + let version = parts.next().unwrap_or(""); + if !version.starts_with("HTTP/1.") { + return Err("not an HTTP/1.x response".into()); + } + let status: u16 = parts + .next() + .and_then(|s| s.parse().ok()) + .ok_or("malformed status line")?; + let chunked = head.lines().any(|l| { + l.to_ascii_lowercase().starts_with("transfer-encoding:") + && l.to_ascii_lowercase().contains("chunked") + }); + let body = if chunked { + dechunk(body) + } else { + body.to_owned() + }; + Ok(Response { status, body }) +} + +fn dechunk(body: &str) -> String { + let mut out = String::new(); + let mut rest = body; + while let Some((size_line, after)) = rest.split_once("\r\n") { + let Ok(size) = usize::from_str_radix(size_line.split(';').next().unwrap_or("").trim(), 16) + else { + break; + }; + if size == 0 || after.len() < size { + break; + } + out.push_str(&after[..size]); + rest = after[size..].trim_start_matches("\r\n"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::net::TcpListener; + + #[test] + fn parses_plain_and_chunked_bodies() { + let plain = parse_response(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").unwrap(); + assert_eq!( + plain, + Response { + status: 200, + body: "{}".into() + } + ); + let chunked = parse_response(b"HTTP/1.1 503 Service Unavailable\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n4\r\n abc\r\n0\r\n\r\n").unwrap(); + assert_eq!((chunked.status, chunked.body.as_str()), (503, "hello abc")); + assert!(parse_response(b"garbage").is_err()); + assert!(parse_response(b"SMTP/1.0 200\r\n\r\n").is_err()); + } + + #[tokio::test] + async fn gets_json_from_a_local_listener_and_sends_the_bearer_header() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut buffer = vec![0u8; 2048]; + let count = stream.read(&mut buffer).await.unwrap(); + let request = String::from_utf8_lossy(&buffer[..count]).into_owned(); + let body = r#"{"ready":true}"#; + stream + .write_all( + format!( + "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ) + .await + .unwrap(); + request + }); + let response = get(address, "/ready", Some("tok-123"), Duration::from_secs(5)) + .await + .unwrap(); + assert_eq!( + (response.status, response.body.as_str()), + (200, r#"{"ready":true}"#) + ); + let request = server.await.unwrap(); + assert!( + request.starts_with("GET /ready HTTP/1.1\r\n") + && request.contains("Authorization: Bearer tok-123\r\n") + ); + } + + #[tokio::test] + async fn refuses_remote_addresses_bad_paths_and_reports_refused_connections() { + let remote: SocketAddr = "10.0.0.1:80".parse().unwrap(); + assert!( + get(remote, "/", None, Duration::from_secs(1)) + .await + .unwrap_err() + .contains("loopback") + ); + let local: SocketAddr = "127.0.0.1:9".parse().unwrap(); + assert!( + get(local, "/a b", None, Duration::from_secs(1)) + .await + .is_err() + ); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed = listener.local_addr().unwrap(); + drop(listener); + assert!( + get( + closed, + "/", + Some("secret-token-value"), + Duration::from_secs(2) + ) + .await + .is_err() + ); + } +} diff --git a/crates/deploy/src/layout.rs b/crates/deploy/src/layout.rs new file mode 100644 index 00000000..b0771155 --- /dev/null +++ b/crates/deploy/src/layout.rs @@ -0,0 +1,233 @@ +//! Where everything lives: install prefix, private state, model volume. +//! +//! ```text +//! PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} +//! PREFIX/lib/cublas/ CUDA 12 cuBLAS (only when the host has none) +//! STATE/leleka.json run configuration (no secrets) 0600 +//! STATE/runtime.env tokens + LD_LIBRARY_PATH 0600 +//! STATE/api-key bearer key of the public API 0600 +//! STATE/daemon.json strata.json profile.json generated configs +//! STATE/logs/*.log STATE/run/status.json STATE/stamps/*.json STATE/mtp-staging/ +//! ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(+.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/ +//! ``` +use crate::profile::{ARCHIVE_BYTES, SHARD_BYTES}; +use std::path::{Path, PathBuf}; + +pub const BINARIES: [&str; 6] = [ + "leleka", + "strata-next", + "leleka-inference", + "leleka-daemon", + "leleka-cli", + "leleka-seal-exec", +]; +pub const SHARD_NAMES: [&str; 2] = [ + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", +]; +pub const KAR_NAME: &str = "qwen-iq3-s-l2-v4.kar"; +pub const MTP_FILES: [&str; 4] = ["dense.bin", "dense.txt", "draft_vocab.bin", "experts.bin"]; +pub const MANIFEST: &str = "qwen-iq3-s"; +pub const MODEL_ID: &str = "qwen-iq3"; +pub const MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1"; +/// Digest of the pinned IQ3_S shard pair (`crates/leleka-runtime/src/backend.rs` `MODEL_DIGEST`). +pub const MODEL_DIGEST: &str = + "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Dirs { + pub prefix: PathBuf, + pub state: PathBuf, + pub assets: PathBuf, +} + +impl Dirs { + /// Defaults: root gets `/opt/leleka`, `/var/lib/leleka`; a user gets XDG-style directories under `$HOME`. + /// Environment overrides: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`. + pub fn defaults(root: bool, home: Option<&Path>, env: &dyn Fn(&str) -> Option) -> Dirs { + let pick = |name: &str, fallback: PathBuf| env(name).map(PathBuf::from).unwrap_or(fallback); + if root { + Dirs { + prefix: pick("LELEKA_PREFIX", "/opt/leleka".into()), + state: pick("LELEKA_STATE", "/var/lib/leleka/state".into()), + assets: pick("LELEKA_ASSETS", "/var/lib/leleka/assets".into()), + } + } else { + let home = home.map(Path::to_path_buf).unwrap_or_else(|| "/tmp".into()); + Dirs { + prefix: pick("LELEKA_PREFIX", home.join(".local/share/leleka")), + state: pick("LELEKA_STATE", home.join(".local/state/leleka")), + assets: pick("LELEKA_ASSETS", home.join(".local/share/leleka/assets")), + } + } + } + + pub fn paths(&self) -> Paths { + Paths { dirs: self.clone() } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Paths { + pub dirs: Dirs, +} + +impl Paths { + pub fn bin_dir(&self) -> PathBuf { + self.dirs.prefix.join("bin") + } + pub fn bin(&self, name: &str) -> PathBuf { + self.bin_dir().join(name) + } + pub fn cublas_dir(&self) -> PathBuf { + self.dirs.prefix.join("lib/cublas") + } + pub fn run_config(&self) -> PathBuf { + self.dirs.state.join("leleka.json") + } + pub fn env_file(&self) -> PathBuf { + self.dirs.state.join("runtime.env") + } + pub fn api_key(&self) -> PathBuf { + self.dirs.state.join("api-key") + } + pub fn daemon_config(&self) -> PathBuf { + self.dirs.state.join("daemon.json") + } + pub fn strata_config(&self) -> PathBuf { + self.dirs.state.join("strata.json") + } + pub fn profile_file(&self) -> PathBuf { + self.dirs.state.join("profile.json") + } + pub fn logs(&self) -> PathBuf { + self.dirs.state.join("logs") + } + pub fn run_dir(&self) -> PathBuf { + self.dirs.state.join("run") + } + pub fn status_file(&self) -> PathBuf { + self.run_dir().join("status.json") + } + pub fn stamps(&self) -> PathBuf { + self.dirs.state.join("stamps") + } + pub fn mtp_staging(&self) -> PathBuf { + self.dirs.state.join("mtp-staging") + } + pub fn shard(&self, index: usize) -> PathBuf { + self.dirs.assets.join("model").join(SHARD_NAMES[index]) + } + pub fn model_dir(&self) -> PathBuf { + self.dirs.assets.join("model") + } + pub fn kar(&self) -> PathBuf { + self.dirs.assets.join(KAR_NAME) + } + pub fn kar_provenance(&self) -> PathBuf { + self.dirs.assets.join(format!("{KAR_NAME}.provenance.json")) + } + pub fn mtp_pack(&self) -> PathBuf { + self.dirs.assets.join("data/mtp-rt") + } + pub fn tokenizer_root(&self) -> PathBuf { + self.dirs.assets.join("tokenizer-assets") + } + pub fn tokenizer_dir(&self) -> PathBuf { + self.tokenizer_root().join("tokenizer") + } + pub fn unit_name(&self) -> &'static str { + "leleka.service" + } +} + +/// Bytes still missing on the model volume, from the current sizes of the pinned files. A file with the wrong size +/// counts as missing (fetch resumes or restarts it; the archive step refuses a wrong archive). +pub fn missing_asset_bytes(paths: &Paths) -> (u64, u64) { + let size = |path: PathBuf| { + std::fs::metadata(path) + .ok() + .filter(|m| m.is_file()) + .map(|m| m.len()) + }; + let mut shards = 0u64; + for (index, expected) in SHARD_BYTES.iter().enumerate() { + let have = size(paths.shard(index)).unwrap_or(0); + let part = size( + paths + .model_dir() + .join(format!("{}.part", SHARD_NAMES[index])), + ) + .unwrap_or(0); + if have != *expected { + shards += expected.saturating_sub(part.max(have.min(*expected))); + } + } + let kar = if size(paths.kar()) == Some(ARCHIVE_BYTES) { + 0 + } else { + // Sections, the final archive and slack: the guard in `ensure-sharded-streamed` is the exact bound. + ARCHIVE_BYTES + ARCHIVE_BYTES / 5 + }; + (shards, kar) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_follow_the_user() { + let none = |_: &str| None; + let root = Dirs::defaults(true, None, &none); + assert_eq!(root.prefix, PathBuf::from("/opt/leleka")); + let user = Dirs::defaults(false, Some(Path::new("/home/para")), &none); + assert_eq!(user.state, PathBuf::from("/home/para/.local/state/leleka")); + let overridden = Dirs::defaults(false, Some(Path::new("/home/para")), &|name| { + (name == "LELEKA_ASSETS").then(|| "/data/leleka".to_owned()) + }); + assert_eq!(overridden.assets, PathBuf::from("/data/leleka")); + assert_eq!( + overridden.prefix, + PathBuf::from("/home/para/.local/share/leleka") + ); + } + + #[test] + fn paths_are_derived_from_the_three_roots() { + let dirs = Dirs { + prefix: "/opt/leleka".into(), + state: "/var/lib/leleka/state".into(), + assets: "/data".into(), + }; + let paths = dirs.paths(); + assert_eq!( + paths.bin("leleka-inference"), + PathBuf::from("/opt/leleka/bin/leleka-inference") + ); + assert_eq!( + paths.kar_provenance(), + PathBuf::from("/data/qwen-iq3-s-l2-v4.kar.provenance.json") + ); + assert_eq!( + paths.tokenizer_dir(), + PathBuf::from("/data/tokenizer-assets/tokenizer") + ); + } + + #[test] + fn missing_bytes_of_an_empty_volume_are_the_whole_model() { + let dir = std::env::temp_dir().join(format!("leleka-layout-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths = Dirs { + prefix: dir.clone(), + state: dir.clone(), + assets: dir.join("assets"), + } + .paths(); + let (shards, kar) = missing_asset_bytes(&paths); + assert_eq!(shards, SHARD_BYTES[0] + SHARD_BYTES[1]); + assert!(kar > ARCHIVE_BYTES); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/deploy/src/lib.rs b/crates/deploy/src/lib.rs new file mode 100644 index 00000000..0f924566 --- /dev/null +++ b/crates/deploy/src/lib.rs @@ -0,0 +1,19 @@ +//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command. +//! +//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the +//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness; +//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`. +pub mod app; +pub mod cli; +pub mod config; +pub mod facts; +pub mod http; +pub mod layout; +pub mod manifest; +pub mod plan; +pub mod preflight; +pub mod profile; +pub mod sealed; +pub mod steps; +pub mod supervisor; +pub mod units; diff --git a/crates/deploy/src/main.rs b/crates/deploy/src/main.rs new file mode 100644 index 00000000..13040534 --- /dev/null +++ b/crates/deploy/src/main.rs @@ -0,0 +1,6 @@ +#[tokio::main(flavor = "current_thread")] +async fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let code = leleka_deploy::app::main_with(args).await; + std::process::exit(code); +} diff --git a/crates/deploy/src/manifest.rs b/crates/deploy/src/manifest.rs new file mode 100644 index 00000000..3afed0b1 --- /dev/null +++ b/crates/deploy/src/manifest.rs @@ -0,0 +1,90 @@ +//! `MANIFEST.json` of a release tarball (written by `scripts/package-release.sh`): what was built, from which +//! commit, with which features, and the SHA-256 of every binary. `up` uses it to verify the binaries it installs +//! and to know whether the sm_86 companion PTX are inside. +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::Path}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + pub schema_version: u32, + pub version: String, + pub git_commit: String, + /// Cargo features the runtime binaries were built with (`sm86` among them for a two-architecture build). + #[serde(default)] + pub features: Vec, + /// Binary name -> lower-case hex SHA-256. + #[serde(default)] + pub binaries: BTreeMap, +} + +impl Manifest { + pub fn has_sm86(&self) -> bool { + self.features.iter().any(|f| f == "sm86") + } + + pub fn parse(text: &str) -> Result { + let manifest: Manifest = + serde_json::from_str(text).map_err(|e| format!("invalid MANIFEST.json: {e}"))?; + if manifest.schema_version != 1 { + return Err(format!( + "MANIFEST.json schema_version {} is not supported", + manifest.schema_version + )); + } + for (name, digest) in &manifest.binaries { + if name.contains('/') + || digest.len() != 64 + || !digest.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err(format!( + "MANIFEST.json entry {name:?} is not a name and a SHA-256" + )); + } + } + Ok(manifest) + } + + /// Look for `MANIFEST.json` next to `bin_dir` (`PREFIX/MANIFEST.json`) or inside it. + pub fn find(bin_dir: &Path) -> Option> { + [ + bin_dir.parent().map(|p| p.join("MANIFEST.json")), + Some(bin_dir.join("MANIFEST.json")), + ] + .into_iter() + .flatten() + .find(|path| path.is_file()) + .map(|path| { + let text = std::fs::read_to_string(&path) + .map_err(|e| format!("cannot read {}: {e}", path.display()))?; + Manifest::parse(&text) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_features_and_digests() { + let digest = "a".repeat(64); + let text = format!( + r#"{{"schema_version":1,"version":"0.1.0","git_commit":"abc","features":["sm86"],"binaries":{{"leleka":"{digest}"}},"extra":1}}"# + ); + let manifest = Manifest::parse(&text).unwrap(); + assert!(manifest.has_sm86()); + assert_eq!(manifest.binaries["leleka"], digest); + assert!(Manifest::parse(r#"{"schema_version":2,"version":"","git_commit":""}"#).is_err()); + assert!( + Manifest::parse( + r#"{"schema_version":1,"version":"","git_commit":"","binaries":{"a/b":"00"}}"# + ) + .is_err() + ); + assert!( + !Manifest::parse(r#"{"schema_version":1,"version":"","git_commit":""}"#) + .unwrap() + .has_sm86() + ); + } +} diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs new file mode 100644 index 00000000..6a601313 --- /dev/null +++ b/crates/deploy/src/plan.rs @@ -0,0 +1,1134 @@ +//! The deployment plan: what `up` would do, derived from what is already on the machine. +//! +//! `gather` reads the host (no writes, no hashing of model files, no network). `plan_steps` is pure over the +//! gathered state, so a fresh machine, a half-finished run and a finished deployment are all unit-tested. +//! `--dry-run` prints this plan; execution (`steps.rs`) walks the same list and runs only the `Todo` entries, +//! which is what makes a re-run idempotent and a crashed run resumable. +use crate::{ + cli::{ModeChoice, UpOptions}, + config::{KarArg, RunConfig}, + facts::{Facts, ProbeRequest, probe}, + layout::{BINARIES, MANIFEST, MTP_FILES, Paths, missing_asset_bytes}, + manifest::Manifest, + preflight::{ExpertProfileState, Needs, Report, evaluate}, + profile::{ARCHIVE_BYTES, KarSource, Profile, resolve}, + units::UnitScope, +}; +use serde::Serialize; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +pub const CUBLAS_VERSION: &str = "12.9.1.4"; +pub const CUBLAS_URL: &str = "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz"; +pub const CUBLAS_SHA256: &str = "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"; +pub const CUBLAS_BYTES: u64 = 933_611_504; +pub const EXPERT_PROFILE_SHA256: &str = + "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Mode { + Systemd(UnitScopeTag), + Foreground, + /// Prepare everything, start nothing. + None, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum UnitScopeTag { + System, + 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, + pub facts: Facts, + pub paths: Paths, + pub bin_src: PathBuf, + pub manifest: Option>, + pub profile: Result, + pub mode: Mode, + pub service_user: String, + pub config: Option, + pub report: Option, + 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 { + let relative = profile.expert_profile.as_ref()?; + let path = assets.join(relative); + let Ok(bytes) = std::fs::read(&path) else { + return Some(ExpertProfileState::Absent); + }; + if bytes.len() > 16 << 20 { + return Some(ExpertProfileState::WrongDigest); + } + let expected = profile + .expert_profile_sha256 + .as_deref() + .unwrap_or(EXPERT_PROFILE_SHA256); + Some(if sha256_hex(&bytes) == expected { + ExpertProfileState::Valid + } else { + 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 Path::new(&format!("/proc/{pid}")).exists()) + && !matches!(phase, "stopped" | "failed") +} + +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(), + shard_bytes_missing: if opts.fetch { shards } else { 0 }, + kar_bytes_missing: if opts.fetch { kar } else { 0 }, + install_binaries: !installed_same_dir, + may_install_cublas: opts.install_cublas && opts.cublas_dir.is_none(), + 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, + }; + let (config, report) = match &profile { + Ok(p) => { + needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); + let mut engine_env = BTreeMap::new(); + if needs.expert_profile == Some(ExpertProfileState::Valid) + && let Some(relative) = &p.expert_profile + { + engine_env.insert( + "LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".to_owned(), + "auto".to_owned(), + ); + engine_env.insert( + "LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE".to_owned(), + opts.dirs.assets.join(relative).display().to_string(), + ); + } + let config = RunConfig::new( + &opts.dirs, + opts.ports.clone(), + opts.gpu, + p.clone(), + engine_env, + ); + 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 { + pub dirs_exist: bool, + pub binaries_current: bool, + pub binaries_source_ok: bool, + pub cublas_ready: bool, + pub secrets_present: bool, + pub shards_stamp_ok: bool, + pub kar_stamp_ok: bool, + /// The archive file has the pinned length and its provenance sidecar exists. + pub kar_present: bool, + pub mtp_present: bool, + pub tokenizer_present: bool, + pub configs_current: bool, + pub unit_current: bool, + pub service_ready: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "state", content = "why", rename_all = "lowercase")] +pub enum StepState { + Done(String), + Todo(String), + Skip(String), + 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, + pub title: String, + #[serde(flatten)] + pub state: StepState, + 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 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!["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() + )], + )); + + 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("libcublas.so.12 and libcublasLt.so.12 found".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()) + }, + 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_state = 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 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) + )) + }, + 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, + 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 +} + +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, + }; + 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, + }; + + 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)); + let needs = Needs { + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + ..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 + } + + #[test] + fn fresh_server_plans_every_step() { + let ctx = context( + options(&[]), + Mode::Systemd(UnitScopeTag::System), + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + mtp_present: true, + ..FsState::default() + }, + ); + for id in [ + "layout", + "binaries", + "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); + 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); + assert!( + text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar") + && text.contains("--context-tokens 8192"), + "{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) + ); + assert_eq!( + expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir), + None + ); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs new file mode 100644 index 00000000..b4e92c40 --- /dev/null +++ b/crates/deploy/src/preflight.rs @@ -0,0 +1,1029 @@ +//! Preflight: turn `Facts` + `Profile` + what the plan needs into pass / warn / fail checks with a fix for each. +//! +//! Pure logic over data, so it is unit-tested with synthetic hosts (server, laptop under WSL2, driver too old, +//! no cuBLAS, full disk). `leleka up` refuses to start a step that changes anything while a check fails. +use crate::{ + facts::{Facts, Gpu, is_slow_foreign_fs}, + profile::{ARCHIVE_BYTES, KarSource, Profile}, +}; +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Level { + Pass, + Warn, + Fail, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Check { + pub id: &'static str, + pub level: Level, + pub title: String, + pub detail: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub fix: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Report { + pub profile: String, + pub checks: Vec, +} + +impl Report { + pub fn failed(&self) -> bool { + self.checks.iter().any(|c| c.level == Level::Fail) + } + pub fn count(&self, level: Level) -> usize { + self.checks.iter().filter(|c| c.level == level).count() + } + pub fn render(&self) -> String { + let mut out = format!("preflight (profile {}):\n", self.profile); + for check in &self.checks { + let tag = match check.level { + Level::Pass => "ok ", + Level::Warn => "WARN", + Level::Fail => "FAIL", + }; + out.push_str(&format!(" [{tag}] {}: {}\n", check.title, check.detail)); + if check.level != Level::Pass + && let Some(fix) = &check.fix + { + for line in fix.lines() { + out.push_str(&format!(" fix: {line}\n")); + } + } + } + out.push_str(&format!( + " {} failed, {} warnings, {} ok\n", + self.count(Level::Fail), + self.count(Level::Warn), + self.count(Level::Pass) + )); + out + } +} + +/// What the plan will do, as far as it matters for the checks. +#[derive(Clone, Debug, Default)] +pub struct Needs { + pub gpu_index: u32, + pub assets_dir: PathBuf, + pub state_dir: PathBuf, + pub prefix_dir: PathBuf, + /// Bytes of GGUF shards still to download / of KAR archive still to build (0 when present). + pub shard_bytes_missing: u64, + pub kar_bytes_missing: u64, + /// Install the binaries from `bin_src` into the prefix. + pub install_binaries: bool, + /// cuBLAS 12 will be downloaded when the host has none. + pub may_install_cublas: bool, + pub cublas_download_bytes: u64, + pub wants_systemd: bool, + pub service_ports: Vec<(String, u16)>, + pub require_binaries: bool, + /// The release manifest lists the `sm86` feature (companion PTX for cc 8.6 <= cc < 12.0), when known. + pub binary_has_sm86: Option, + /// Ports already owned by this deployment's own running service are not conflicts. + pub service_running: bool, + /// The public API is bound beyond the loopback interface (`--api-bind`). + pub api_bind_open: bool, + /// The sealed archive comes from the parent process (`--kar-fd`): the service does not copy it. + pub kar_fd_inherited: bool, + /// Expert profile present, and its digest is the pinned one (only meaningful for profiles that name one). + pub expert_profile: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExpertProfileState { + Absent, + Valid, + WrongDigest, +} + +const GIB: u64 = 1 << 30; + +fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / GIB as f64) +} + +fn check( + id: &'static str, + level: Level, + title: &str, + detail: String, + fix: Option, +) -> Check { + Check { + id, + level, + title: title.to_owned(), + detail, + fix, + } +} + +fn pass(id: &'static str, title: &str, detail: String) -> Check { + check(id, Level::Pass, title, detail, None) +} + +pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { + let mut checks = Vec::new(); + + // 1. platform + if facts.os == "linux" && facts.arch == "x86_64" { + checks.push(pass("platform", "platform", "linux x86_64".into())); + } else { + checks.push(check( + "platform", + Level::Fail, + "platform", + format!( + "{}/{} is not supported; the CUDA runtime is Linux x86_64 only", + facts.os, facts.arch + ), + Some("run on a Linux x86_64 host, or inside WSL2 on Windows".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("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), + )); + } + } + } + } + + // 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_bytes + .saturating_sub(ARCHIVE_BYTES) + .max(4 * GIB) + } else { + profile.min_ram_available_bytes + }; + 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 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"); + match (blas, blas_lt) { + (Some(path), Some(_)) => checks.push(pass( + "cublas", + "cuBLAS 12", + format!("libcublas.so.12 and libcublasLt.so.12 found ({})", path.display()), + )), + _ if needs.may_install_cublas => { + let mut missing = Vec::new(); + if blas.is_none() { + missing.push("libcublas.so.12"); + } + if blas_lt.is_none() { + missing.push("libcublasLt.so.12"); + } + 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", + "libcublas.so.12 / libcublasLt.so.12 not found; leleka-inference loads them by name".into(), + Some("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", + "libcuda.so.1 was not found by the library search (the engine dlopens it)".into(), + Some(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()), + )); + } + match &needs.expert_profile { + Some(ExpertProfileState::Absent) if profile.expert_profile.is_some() => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + format!("{} is not in the assets directory; the engine runs without the ranked VRAM expert tier (slower)", profile.expert_profile.as_deref().unwrap_or("")), + Some("copy the upstream data/expert-profile.bin (sha256 8f59b4aa...388975baf) there, then rerun".into()), + )), + Some(ExpertProfileState::WrongDigest) => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + "the expert profile does not have the pinned SHA-256; it will not be used".into(), + None, + )), + _ => {} + } + + Report { + profile: profile.name.clone(), + checks, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::facts::{DirFact, Memory}; + + fn server_facts() -> Facts { + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + nvidia_smi_found: true, + gpus: vec![Gpu { + index: 0, + name: "NVIDIA GeForce RTX 5090".into(), + driver: "595.99.02".into(), + vram_total_mib: 32607, + vram_free_mib: 32105, + sm: Some(120), + }], + memory: Memory { + total: 121 * GIB, + available: 118 * GIB, + swap_total: 0, + }, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + facts.libs.insert( + "libcublas.so.12".into(), + Some("/opt/c/libcublas.so.12".into()), + ); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/opt/c/libcublasLt.so.12".into()), + ); + facts.libs.insert( + "libcuda.so.1".into(), + Some("/usr/lib/x86_64-linux-gnu/libcuda.so.1".into()), + ); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + DirFact { + path: format!("/data/{key}").into(), + free_bytes: Some(900 * GIB), + fs_type: Some("ext4".into()), + }, + ); + } + facts + } + + fn needs() -> Needs { + Needs { + assets_dir: "/data/assets".into(), + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + install_binaries: true, + may_install_cublas: true, + cublas_download_bytes: 500 << 20, + wants_systemd: true, + service_ports: vec![("api".into(), 8081), ("engine".into(), 18766)], + ..Needs::default() + } + } + + fn level_of(report: &Report, id: &str) -> Level { + report + .checks + .iter() + .find(|c| c.id == id) + .unwrap_or_else(|| panic!("no check {id}")) + .level + } + + #[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 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 profile = Profile::builtin("rtx5090-32g").unwrap(); + 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: "windows".into(), + arch: "x86_64".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/profile.rs b/crates/deploy/src/profile.rs new file mode 100644 index 00000000..7573363d --- /dev/null +++ b/crates/deploy/src/profile.rs @@ -0,0 +1,344 @@ +//! Memory profiles: which GPU class gets which budget, context ceiling, KAR source and RAM floor. +//! +//! The built-in profiles are the JSON files in `deploy/rust-runtime/profiles/`, embedded at build time so the binary +//! needs no data directory. `--profile FILE` replaces them with an operator file of the same shape. A profile only +//! selects documented switches of `leleka-inference`; it never changes the model, the quantization or the backend +//! mode, so choosing one is not a quality decision. +use crate::facts::Gpu; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::Path}; + +/// Bytes of the pinned level-2 KAR archive (`InheritedKarArchive` admits exactly this length). +pub const ARCHIVE_BYTES: u64 = 55_295_529_472; +/// Bytes of the two pinned IQ3_S GGUF shards. +pub const SHARD_BYTES: [u64; 2] = [54_817_524_224, 28_800_138_432]; + +pub const BUILTIN: [(&str, &str); 2] = [ + ( + "rtx5090-32g", + include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g.json"), + ), + ( + "rtx3080-16g", + include_str!("../../../deploy/rust-runtime/profiles/rtx3080-16g.json"), + ), +]; + +const PREFILL_CAPACITIES: [u32; 8] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192]; + +/// How the engine receives the KAR archive. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum KarSource { + /// A sealed memfd made by the supervisor: the whole archive lives in RAM (shmem) while the service runs. + Memfd, + /// An ordinary read-only file (`--kar-archive-file`): only the pages that are read pass through the file cache. + File, +} + +impl KarSource { + pub fn as_str(self) -> &'static str { + match self { + KarSource::Memfd => "memfd", + KarSource::File => "file", + } + } +} + +/// How the routed experts are admitted (`leleka-inference --expert-source`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ExpertSource { + /// A page-locked RAM copy of the routed experts (about 50 GB): the server form. + Resident, + /// Read-only mappings of shard 0, nothing copied: the low-RAM form. + Mapped, +} + +impl ExpertSource { + pub fn as_str(self) -> &'static str { + match self { + ExpertSource::Resident => "resident", + ExpertSource::Mapped => "mapped", + } + } +} + +/// 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)] +pub struct Selector { + pub sm_min: u32, + pub sm_max: u32, + pub vram_mib_min: u64, + pub vram_mib_max: u64, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Profile { + pub name: String, + pub description: String, + #[serde(default)] + pub select: Selector, + pub gpu_budget_bytes: u64, + pub context_tokens: u32, + #[serde(default)] + pub prefill_capacity: Option, + #[serde(default)] + pub kv: Option, + #[serde(default)] + pub kv_resident: Option, + #[serde(default)] + pub prompt_cache: Option, + pub kar_source: KarSource, + pub expert_source: ExpertSource, + pub min_driver_major: u32, + pub min_vram_total_mib: u64, + /// Free VRAM required at start. Defaults to the budget; a profile whose budget is an upper bound that the + /// engine does not fully reach (the laptop: 15 GiB budget, 14.2 GiB measured peak) names the measured need. + #[serde(default)] + pub min_vram_free_mib: Option, + pub min_ram_total_bytes: u64, + pub min_ram_available_bytes: u64, + /// Advice only: the `memory=` value for `.wslconfig` when WSL2 gives the VM too little. + #[serde(default)] + pub wsl_memory_gib: Option, + /// Path relative to the assets directory of an optional ranked expert profile (VRAM expert tier). + #[serde(default)] + pub expert_profile: Option, + #[serde(default)] + pub expert_profile_sha256: Option, + /// Extra `LELEKA_ORIGINAL_SERVE_*` switches for the engine process. + #[serde(default)] + pub engine_env: BTreeMap, +} + +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) + } + + pub fn validate(&self) -> Result<(), String> { + 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(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(), + ); + } + for (key, value) in &self.engine_env { + if !key.starts_with("LELEKA_ORIGINAL_SERVE_") + || !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_* name" + )); + } + 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::*; + + 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(), 2); + } + + #[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, 8192); + } + + #[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 unknown_fields_in_a_profile_file_are_refused() { + let text = BUILTIN[0] + .1 + .replace("\"engine_env\": {}", "\"engine_env\": {}, \"typo\": 1"); + assert!(serde_json::from_str::(&text).is_err()); + } +} diff --git a/crates/deploy/src/sealed.rs b/crates/deploy/src/sealed.rs new file mode 100644 index 00000000..635aeba1 --- /dev/null +++ b/crates/deploy/src/sealed.rs @@ -0,0 +1,252 @@ +//! The sealed KAR archive, made by the service itself (no helper process, no Python). +//! +//! `leleka run` copies the archive once into an irrevocably sealed `memfd` and keeps it for its whole life, so an +//! engine restart does not copy 55 GB again. The engine refuses anything but a regular, unlinked file of the +//! pinned length with `WRITE | GROW | SHRINK | SEAL` seals (`InheritedKarArchive::open`). The descriptor is +//! `CLOEXEC` in the supervisor and reaches only the engine: the supervisor hands a duplicate to `leleka +//! exec-inherit` as standard input, and that shim moves it to a descriptor number >= 3 without close-on-exec and +//! `exec`s the engine, which reopens it through `/proc/self/fd/N`. +#[cfg(target_os = "linux")] +pub use linux::*; + +#[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 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()) +} + +pub const PLACEHOLDER: &str = "{FD}"; + +/// Replace every `{FD}` in `args`. +pub fn substitute(args: &[String], number: i32) -> Vec { + args.iter() + .map(|arg| arg.replace(PLACEHOLDER, &number.to_string())) + .collect() +} + +#[cfg(target_os = "linux")] +mod linux { + use super::substitute; + use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; + use std::{ + convert::Infallible, + fs::File, + io::{Read, Write}, + os::{ + fd::{AsFd, IntoRawFd}, + unix::process::CommandExt, + }, + path::Path, + process::Command, + }; + + pub const SEALS: SealFlags = SealFlags::from_bits_truncate( + SealFlags::WRITE.bits() + | SealFlags::GROW.bits() + | SealFlags::SHRINK.bits() + | SealFlags::SEAL.bits(), + ); + const CHUNK: usize = 16 << 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 { + let mut 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 fd = memfd_create( + "leleka-sealed-archive", + MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, + ) + .map_err(|e| format!("memfd_create failed: {e}"))?; + let mut memory = File::from(fd); + let mut buffer = vec![0u8; CHUNK]; + let total = metadata.len(); + let (mut copied, mut reported) = (0u64, 0u64); + loop { + let count = source + .read(&mut buffer) + .map_err(|e| format!("read failed: {e}"))?; + if count == 0 { + break; + } + memory + .write_all(&buffer[..count]) + .map_err(|e| format!("write to memfd failed (out of memory?): {e}"))?; + copied += count as u64; + if copied - reported >= 4 << 30 { + reported = copied; + progress(copied, total); + } + } + if copied != total { + 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(total, total); + Ok(memory) + } + + /// 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])) + } + + #[cfg(test)] + mod tests { + use super::*; + 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 exec_inherit_needs_a_command() { + assert!(exec_inherit(&[]).is_err()); + assert!(exec_inherit(&["--".into()]).is_err()); + assert!(exec_inherit(&["cmd".into()]).is_err()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn placeholder_substitution() { + let args = vec![ + "--kar-archive-fd".to_owned(), + "{FD}".to_owned(), + "x{FD}y".to_owned(), + ]; + assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]); + } +} diff --git a/crates/deploy/src/steps.rs b/crates/deploy/src/steps.rs new file mode 100644 index 00000000..02662d88 --- /dev/null +++ b/crates/deploy/src/steps.rs @@ -0,0 +1,1143 @@ +//! Execution of the plan. Every step is idempotent and can be repeated after a crash: downloads resume +//! (`.part` files), verified assets carry a stamp (path, size, mtime) so a re-run does not hash 140 GB again, +//! generated files are rewritten only when their content changes, and secrets are never rotated. +use crate::{ + config::{ + ENV_HEADER, GATEWAY_TOKEN_ENV, RUNTIME_TOKEN_ENV, RunConfig, merge_env, new_token, + to_file_text, + }, + facts::parse_env_file, + http, + layout::{BINARIES, MANIFEST, MTP_FILES, Paths}, + plan::{ + CUBLAS_SHA256, CUBLAS_URL, CUBLAS_VERSION, Context, FsState, Mode, Step, StepState, + UnitScopeTag, plan_steps, + }, + profile::ARCHIVE_BYTES, + supervisor::{valid_token, write_private}, + units, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + io::Read, + path::{Path, PathBuf}, + process::Stdio, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use tokio::{io::AsyncReadExt, io::AsyncWriteExt, process::Command}; + +pub fn say(message: &str) { + eprintln!("leleka: {message}"); +} + +// --------------------------------------------------------------------------------------------------------------- +// stamps + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FileStamp { + pub path: String, + pub size: u64, + pub mtime_ns: u128, +} + +#[derive(Debug, Serialize, Deserialize)] +struct StampFile { + leleka_version: String, + what: String, + files: Vec, + verified_unix: u64, +} + +pub fn file_stamp(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?; + let mtime = meta + .modified() + .ok()? + .duration_since(UNIX_EPOCH) + .ok()? + .as_nanos(); + Some(FileStamp { + path: path.display().to_string(), + size: meta.len(), + mtime_ns: mtime, + }) +} + +pub fn stamp_path(paths: &Paths, name: &str) -> PathBuf { + paths.stamps().join(format!("{name}.json")) +} + +/// True when `stamp` exists and every listed file still has the stamped size and mtime. +pub fn stamp_current(stamp: &Path, files: &[PathBuf]) -> bool { + let Ok(text) = std::fs::read_to_string(stamp) else { + return false; + }; + let Ok(stored) = serde_json::from_str::(&text) else { + return false; + }; + let now: Option> = files.iter().map(|p| file_stamp(p)).collect(); + now.is_some_and(|now| now == stored.files) +} + +fn write_stamp(stamp: &Path, what: &str, files: &[PathBuf]) -> Result<(), String> { + let stamps: Option> = files.iter().map(|p| file_stamp(p)).collect(); + let files = stamps.ok_or("a verified file disappeared before it could be stamped")?; + let doc = StampFile { + leleka_version: env!("CARGO_PKG_VERSION").to_owned(), + what: what.to_owned(), + files, + verified_unix: SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()), + }; + write_private(stamp, &to_file_text(&doc)) + .map_err(|e| format!("cannot write {}: {e}", stamp.display())) +} + +// --------------------------------------------------------------------------------------------------------------- +// facts about the file system, for the plan + +pub fn sha256_file(path: &Path) -> std::io::Result { + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 1 << 20]; + loop { + let count = file.read(&mut buffer)?; + if count == 0 { + break; + } + hasher.update(&buffer[..count]); + } + Ok(hex::encode(hasher.finalize())) +} + +fn mtp_complete(paths: &Paths) -> bool { + MTP_FILES.iter().all(|name| { + std::fs::metadata(paths.mtp_pack().join(name)).is_ok_and(|m| m.is_file() && m.len() > 0) + }) +} + +fn binary_digest( + manifest: Option<&crate::manifest::Manifest>, + src: &Path, + name: &str, +) -> Option { + manifest + .and_then(|m| m.binaries.get(name).cloned()) + .or_else(|| sha256_file(&src.join(name)).ok()) +} + +pub fn binaries_state(ctx: &Context) -> (bool, bool) { + let installed = ctx.paths.bin_dir(); + let manifest = ctx.manifest.as_ref().and_then(|m| m.as_ref().ok()); + let src_has_all = BINARIES.iter().all(|b| ctx.bin_src.join(b).is_file()); + let installed_has_all = BINARIES.iter().all(|b| installed.join(b).is_file()); + if !src_has_all && !installed_has_all { + return (false, false); + } + if !src_has_all { + return (true, true); + } + let current = BINARIES.iter().all(|name| { + let (src, dst) = (ctx.bin_src.join(name), installed.join(name)); + if !dst.is_file() { + return false; + } + match ( + binary_digest(manifest, &ctx.bin_src, name), + sha256_file(&dst).ok(), + ) { + (Some(a), Some(b)) => a == b, + _ => src == dst, + } + }); + (true, current) +} + +pub fn render_configs(ctx: &Context) -> Vec<(PathBuf, String)> { + let Some(config) = &ctx.config else { + return Vec::new(); + }; + vec![ + (ctx.paths.run_config(), to_file_text(config)), + ( + ctx.paths.daemon_config(), + to_file_text(&config.daemon_json()), + ), + ( + ctx.paths.strata_config(), + to_file_text(&config.strata_json()), + ), + (ctx.paths.profile_file(), to_file_text(&config.profile)), + ] +} + +pub fn cublas_lib_dirs(ctx: &Context) -> Vec { + let mut dirs: Vec = Vec::new(); + for soname in ["libcublas.so.12", "libcublasLt.so.12"] { + let candidates = [ + ctx.opts.cublas_dir.clone().map(|d| d.join(soname)), + Some(ctx.paths.cublas_dir().join(soname)), + ctx.facts.lib(soname).cloned(), + ]; + if let Some(found) = candidates.into_iter().flatten().find(|p| p.exists()) + && let Some(parent) = found.parent() + && !dirs.iter().any(|d| d == parent) + { + dirs.push(parent.to_path_buf()); + } + } + dirs +} + +pub fn desired_ld_library_path(ctx: &Context) -> String { + cublas_lib_dirs(ctx) + .iter() + .map(|d| d.display().to_string()) + .collect::>() + .join(":") +} + +fn secrets_ok(paths: &Paths) -> bool { + let env = std::fs::read_to_string(paths.env_file()) + .map(|t| parse_env_file(&t)) + .unwrap_or_default(); + let good = |key: &str| env.get(key).is_some_and(|v| valid_token(v)); + good(RUNTIME_TOKEN_ENV) && good(GATEWAY_TOKEN_ENV) && paths.api_key().is_file() +} + +pub async fn gather_fs(ctx: &Context) -> FsState { + let paths = &ctx.paths; + let (binaries_source_ok, binaries_current) = binaries_state(ctx); + let model_files: Vec = vec![paths.shard(0), paths.shard(1)]; + let kar_files: Vec = vec![paths.kar(), paths.kar_provenance()]; + let kar_size_ok = std::fs::metadata(paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES); + let configs = render_configs(ctx); + let configs_current = !configs.is_empty() + && configs + .iter() + .all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| &t == text)) + && std::fs::read_to_string(paths.env_file()) + .ok() + .map(|t| parse_env_file(&t)) + .is_some_and(|env| { + env.get("LD_LIBRARY_PATH").map(String::as_str).unwrap_or("") + == desired_ld_library_path(ctx) + }); + let unit_current = match ctx.mode { + Mode::Systemd(scope) => unit_text(ctx, scope) + .ok() + .is_some_and(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| t == text)), + _ => false, + }; + let service_ready = probe_ready(ctx).await; + FsState { + dirs_exist: [ + paths.dirs.state.clone(), + paths.logs(), + paths.stamps(), + paths.bin_dir(), + paths.dirs.assets.clone(), + ] + .iter() + .all(|d| d.is_dir()), + binaries_current, + binaries_source_ok, + cublas_ready: ctx.facts.lib("libcublas.so.12").is_some() + && ctx.facts.lib("libcublasLt.so.12").is_some(), + secrets_present: secrets_ok(paths), + shards_stamp_ok: stamp_current(&stamp_path(paths, "model"), &model_files), + kar_present: kar_size_ok && paths.kar_provenance().is_file(), + kar_stamp_ok: kar_size_ok && stamp_current(&stamp_path(paths, "kar"), &kar_files), + mtp_present: mtp_complete(paths), + tokenizer_present: paths.tokenizer_dir().is_dir(), + configs_current, + unit_current, + service_ready, + } +} + +pub async fn probe_ready(ctx: &Context) -> bool { + probe_ready_at(&ctx.paths, &ctx.opts.ports.api).await +} + +/// `GET /ready` with the key of `paths`. False on any failure (no key, nothing listening, 503). +pub async fn probe_ready_at(paths: &Paths, api: &str) -> bool { + let Ok(key) = std::fs::read_to_string(paths.api_key()) else { + return false; + }; + let Some(address) = crate::config::probe_address(api) else { + return false; + }; + matches!(http::get(address, "/ready", Some(key.trim_end()), Duration::from_secs(3)).await, Ok(r) if r.status == 200) +} + +pub fn unit_text(ctx: &Context, scope: UnitScopeTag) -> Result<(PathBuf, String), String> { + let home = std::env::var_os("HOME").map(PathBuf::from); + let text = units::render( + scope.scope(), + &ctx.opts.dirs.prefix, + &ctx.opts.dirs.state, + Some(&ctx.service_user), + )?; + let path = units::unit_path(scope.scope(), home.as_deref(), ctx.paths.unit_name())?; + Ok((path, text)) +} + +// --------------------------------------------------------------------------------------------------------------- +// running tools + +/// Run `program` with its output forwarded to stderr and appended to `log`. The environment is inherited (so +/// `HF_TOKEN` reaches `model fetch`); the command line printed here never contains a secret. +pub async fn run_tool( + label: &str, + program: &Path, + args: &[String], + log: &Path, +) -> Result<(), String> { + say(&format!("$ {} {}", program.display(), args.join(" "))); + let mut log_file = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(log) + .await + .map_err(|e| format!("cannot open {}: {e}", log.display()))?; + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|e| format!("cannot start {}: {e}", program.display()))?; + let mut stdout = child.stdout.take().expect("piped"); + let mut stderr = child.stderr.take().expect("piped"); + let (mut out_buf, mut err_buf) = (vec![0u8; 8192], vec![0u8; 8192]); + let (mut out_open, mut err_open) = (true, true); + while out_open || err_open { + tokio::select! { + read = stdout.read(&mut out_buf), if out_open => match read { + Ok(0) | Err(_) => out_open = false, + Ok(n) => { forward(&mut log_file, &out_buf[..n]).await; } + }, + read = stderr.read(&mut err_buf), if err_open => match read { + Ok(0) | Err(_) => err_open = false, + Ok(n) => { forward(&mut log_file, &err_buf[..n]).await; } + }, + } + } + let status = child + .wait() + .await + .map_err(|e| format!("{label}: wait failed: {e}"))?; + if status.success() { + Ok(()) + } else { + Err(format!("{label} failed ({status}); see {}", log.display())) + } +} + +async fn forward(log: &mut tokio::fs::File, bytes: &[u8]) { + use std::io::Write; + let _ = std::io::stderr().write_all(bytes); + let _ = log.write_all(bytes).await; +} + +// --------------------------------------------------------------------------------------------------------------- +// the steps + +pub fn make_dirs(ctx: &Context) -> Result<(), String> { + let paths = &ctx.paths; + let private = [ + paths.dirs.state.clone(), + paths.logs(), + paths.run_dir(), + paths.stamps(), + paths.mtp_staging(), + ]; + for dir in private.iter().chain( + [ + paths.bin_dir(), + paths.dirs.assets.clone(), + paths.model_dir(), + paths.dirs.assets.join("data"), + ] + .iter(), + ) { + std::fs::create_dir_all(dir) + .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for dir in &private { + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) + .map_err(|e| format!("cannot restrict {}: {e}", dir.display()))?; + } + } + Ok(()) +} + +pub fn install_binaries(ctx: &Context) -> Result { + let (src_dir, dst_dir) = (&ctx.bin_src, ctx.paths.bin_dir()); + let manifest = ctx.manifest.as_ref().and_then(|m| m.as_ref().ok()); + let mut installed = 0; + for name in BINARIES { + let (src, dst) = (src_dir.join(name), dst_dir.join(name)); + if !src.is_file() { + if dst.is_file() { + continue; + } + return Err(format!( + "{} is missing (looked in {} and {})", + name, + src_dir.display(), + dst_dir.display() + )); + } + let digest = + sha256_file(&src).map_err(|e| format!("cannot read {}: {e}", src.display()))?; + if let Some(expected) = manifest.and_then(|m| m.binaries.get(name)) + && *expected != digest + { + return Err(format!( + "{} does not match MANIFEST.json (corrupt download?)", + src.display() + )); + } + if dst.is_file() && sha256_file(&dst).ok().as_deref() == Some(digest.as_str()) { + continue; + } + let tmp = dst_dir.join(format!(".{name}.new")); + std::fs::copy(&src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| e.to_string())?; + } + // rename over a running binary is safe (a new inode); a plain overwrite would fail with ETXTBSY. + std::fs::rename(&tmp, &dst).map_err(|e| format!("cannot install {name}: {e}"))?; + installed += 1; + } + Ok(installed) +} + +pub async fn install_cublas(ctx: &Context) -> Result<(), String> { + let paths = &ctx.paths; + let lib_dir = paths.dirs.prefix.join("lib"); + std::fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?; + let tar_path = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz")); + let part = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz.part")); + let log = paths.logs().join("install.log"); + let have = sha256_file(&tar_path) + .ok() + .is_some_and(|d| d == CUBLAS_SHA256); + if !have { + let downloader = if ctx.facts.tool("curl") { + "curl" + } else { + "wget" + }; + let args: Vec = if downloader == "curl" { + ["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"] + .iter() + .map(|s| s.to_string()) + .chain([part.display().to_string(), CUBLAS_URL.to_owned()]) + .collect() + } else { + ["-c", "-O"] + .iter() + .map(|s| s.to_string()) + .chain([part.display().to_string(), CUBLAS_URL.to_owned()]) + .collect() + }; + run_tool("cuBLAS download", Path::new(downloader), &args, &log).await?; + let digest = sha256_file(&part).map_err(|e| format!("cannot hash the download: {e}"))?; + if digest != CUBLAS_SHA256 { + let _ = std::fs::remove_file(&part); + return Err(format!( + "the cuBLAS download has SHA-256 {digest}, expected {CUBLAS_SHA256}; it was deleted, rerun to download again" + )); + } + std::fs::rename(&part, &tar_path).map_err(|e| e.to_string())?; + } + let staging = lib_dir.join(".cublas-extract"); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; + let args: Vec = [ + "-xJf", + &tar_path.display().to_string(), + "-C", + &staging.display().to_string(), + "--strip-components=1", + "--wildcards", + "*/lib/libcublas.so.12*", + "*/lib/libcublasLt.so.12*", + "*/LICENSE", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + run_tool("cuBLAS unpack", Path::new("tar"), &args, &log).await?; + let target = paths.cublas_dir(); + let _ = std::fs::remove_dir_all(&target); + std::fs::rename(staging.join("lib"), &target) + .map_err(|e| format!("cannot move the unpacked libraries: {e}"))?; + if staging.join("LICENSE").is_file() { + let _ = std::fs::rename(staging.join("LICENSE"), target.join("LICENSE-cublas.txt")); + } + let _ = std::fs::remove_dir_all(&staging); + let _ = std::fs::remove_file(&tar_path); + for soname in ["libcublas.so.12", "libcublasLt.so.12"] { + if !target.join(soname).exists() { + return Err(format!( + "{soname} is missing after unpacking the cuBLAS archive" + )); + } + } + Ok(()) +} + +pub fn write_secrets_and_env(ctx: &Context) -> Result<(), String> { + let path = ctx.paths.env_file(); + let existing = std::fs::read_to_string(&path).unwrap_or_default(); + let parsed = parse_env_file(&existing); + let mut updates: Vec<(&str, String)> = Vec::new(); + let mut seen: Vec = Vec::new(); + for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] { + match parsed.get(key) { + Some(value) if valid_token(value) && !seen.contains(value) => seen.push(value.clone()), + _ => { + // Missing or malformed: create a fresh one. A valid existing token is never rotated. + let token = new_token()?; + seen.push(token.clone()); + updates.push((key, token)); + } + } + } + updates.push(("LD_LIBRARY_PATH", desired_ld_library_path(ctx))); + let base = if existing.is_empty() { + format!("{ENV_HEADER}\n") + } else { + existing + }; + let text = merge_env(&base, &updates); + if text != std::fs::read_to_string(&path).unwrap_or_default() { + write_private(&path, &text).map_err(|e| format!("cannot write {}: {e}", path.display()))?; + } + Ok(()) +} + +pub async fn init_api_key(ctx: &Context) -> Result<(), String> { + let args = vec![ + "api-key".to_owned(), + "init".to_owned(), + "--file".to_owned(), + ctx.paths.api_key().display().to_string(), + ]; + run_tool( + "api-key init", + &ctx.paths.bin("strata-next"), + &args, + &ctx.paths.logs().join("install.log"), + ) + .await +} + +pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> { + let strata = ctx.paths.bin("strata-next"); + let log = ctx.paths.logs().join("install.log"); + let model_dir = ctx.paths.model_dir().display().to_string(); + if ctx.opts.fetch { + run_tool( + "model fetch", + &strata, + &[ + "model".into(), + "fetch".into(), + MANIFEST.into(), + "--output".into(), + model_dir.clone(), + ], + &log, + ) + .await?; + } + run_tool( + "model verify", + &strata, + &[ + "model".into(), + "verify".into(), + MANIFEST.into(), + "--output".into(), + model_dir, + ], + &log, + ) + .await?; + write_stamp( + &stamp_path(&ctx.paths, "model"), + "gguf shards verified by `model verify`", + &[ctx.paths.shard(0), ctx.paths.shard(1)], + ) +} + +pub async fn ensure_kar(ctx: &Context) -> Result<(), String> { + let strata = ctx.paths.bin("strata-next"); + let log = ctx.paths.logs().join("install.log"); + let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES) + && ctx.paths.kar_provenance().is_file(); + if ctx.opts.trust_archive && present { + say("--trust-archive: the existing archive is accepted without the strict re-derivation"); + } else { + let args: Vec = [ + "model", + "ensure-sharded-streamed", + MANIFEST, + "--source-dir", + &ctx.paths.model_dir().display().to_string(), + "--output", + &ctx.paths.kar().display().to_string(), + "--levels", + "2", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + run_tool("KAR archive", &strata, &args, &log).await?; + // The tool fetched and verified the shards before it touched the archive. + write_stamp( + &stamp_path(&ctx.paths, "model"), + "gguf shards verified by `ensure-sharded-streamed`", + &[ctx.paths.shard(0), ctx.paths.shard(1)], + )?; + } + let size = std::fs::metadata(ctx.paths.kar()) + .map_err(|e| format!("the archive is missing after the build: {e}"))? + .len(); + if size != ARCHIVE_BYTES { + return Err(format!( + "{} has {size} bytes but the engine only admits the pinned {ARCHIVE_BYTES}-byte level-2 archive; the engine would refuse it (do not use another --levels or an overlay here)", + ctx.paths.kar().display() + )); + } + if !ctx.paths.kar_provenance().is_file() { + return Err(format!( + "{} is missing next to the archive", + ctx.paths.kar_provenance().display() + )); + } + #[cfg(unix)] + if ctx + .config + .as_ref() + .is_some_and(|c| c.profile.kar_source == crate::profile::KarSource::File) + { + use std::os::unix::fs::PermissionsExt; + // `--kar-archive-file` admits only a regular, single-link file without write bits that this user owns. + std::fs::set_permissions(ctx.paths.kar(), std::fs::Permissions::from_mode(0o400)) + .map_err(|e| format!("cannot make the archive read-only: {e}"))?; + } + write_stamp( + &stamp_path(&ctx.paths, "kar"), + "level-2 KAR archive verified by `ensure-sharded-streamed`", + &[ctx.paths.kar(), ctx.paths.kar_provenance()], + ) +} + +pub async fn import_mtp_pack(ctx: &Context) -> Result<(), String> { + let source = ctx.opts.mtp_pack.clone().ok_or("no --mtp-pack given")?; + let target = ctx.paths.mtp_pack(); + let staging = ctx.paths.dirs.assets.join("data/.mtp-import"); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; + let name = source + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_owned(); + if source.is_dir() { + copy_dir(&source, &staging)?; + } else if name.ends_with(".tar") + || name.ends_with(".tar.gz") + || name.ends_with(".tgz") + || name.ends_with(".tar.xz") + { + let flag = if name.ends_with(".tar") { + "-xf" + } else if name.ends_with(".tar.xz") { + "-xJf" + } else { + "-xzf" + }; + run_tool( + "unpack the MTP pack", + Path::new("tar"), + &[ + flag.into(), + source.display().to_string(), + "-C".into(), + staging.display().to_string(), + ], + &ctx.paths.logs().join("install.log"), + ) + .await?; + } else { + return Err(format!( + "--mtp-pack {} must be a directory or a .tar/.tar.gz/.tgz/.tar.xz archive", + source.display() + )); + } + // The pack may sit in a sub-directory (data/mtp-rt/ inside the tarball). + let root = find_pack_root(&staging).ok_or_else(|| { + format!( + "none of the unpacked directories contains {}", + MTP_FILES.join(", ") + ) + })?; + let _ = std::fs::remove_dir_all(&target); + std::fs::rename(&root, &target).map_err(|e| format!("cannot move the pack into place: {e}"))?; + let _ = std::fs::remove_dir_all(&staging); + if !mtp_complete(&ctx.paths) { + return Err("the imported MTP pack is incomplete".into()); + } + Ok(()) +} + +fn find_pack_root(dir: &Path) -> Option { + if MTP_FILES.iter().all(|f| dir.join(f).is_file()) { + return Some(dir.to_path_buf()); + } + for entry in std::fs::read_dir(dir).ok()?.flatten() { + if entry.path().is_dir() + && let Some(found) = find_pack_root(&entry.path()) + { + return Some(found); + } + } + None +} + +fn copy_dir(from: &Path, to: &Path) -> Result<(), String> { + for entry in std::fs::read_dir(from) + .map_err(|e| format!("cannot read {}: {e}", from.display()))? + .flatten() + { + let (src, dst) = (entry.path(), to.join(entry.file_name())); + if src.is_dir() { + std::fs::create_dir_all(&dst).map_err(|e| e.to_string())?; + copy_dir(&src, &dst)?; + } else if src.is_file() { + std::fs::copy(&src, &dst).map_err(|e| format!("cannot copy {}: {e}", src.display()))?; + } + } + Ok(()) +} + +pub async fn extract_tokenizer(ctx: &Context) -> Result<(), String> { + let args: Vec = [ + "model", + "extract-tokenizer", + &ctx.paths.shard(0).display().to_string(), + "--output", + &ctx.paths.tokenizer_root().display().to_string(), + ] + .iter() + .map(|s| s.to_string()) + .collect(); + run_tool( + "tokenizer extraction", + &ctx.paths.bin("strata-next"), + &args, + &ctx.paths.logs().join("install.log"), + ) + .await +} + +pub fn write_configs(ctx: &Context) -> Result { + let mut written = 0; + for (path, text) in render_configs(ctx) { + if std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) { + write_private(&path, &text) + .map_err(|e| format!("cannot write {}: {e}", path.display()))?; + written += 1; + } + } + write_secrets_and_env(ctx)?; + Ok(written) +} + +// --------------------------------------------------------------------------------------------------------------- +// system user and ownership (system unit only) + +#[cfg(unix)] +pub fn lookup_user(name: &str) -> Option<(u32, u32)> { + let passwd = std::fs::read_to_string("/etc/passwd").ok()?; + passwd.lines().find_map(|line| { + let fields: Vec<&str> = line.split(':').collect(); + (fields.first() == Some(&name)) + .then(|| Some((fields.get(2)?.parse().ok()?, fields.get(3)?.parse().ok()?)))? + }) +} + +#[cfg(unix)] +pub async fn ensure_service_user(ctx: &Context) -> Result<(), String> { + let name = &ctx.service_user; + if name == "root" || lookup_user(name).is_some() { + return Ok(()); + } + say(&format!( + "creating the system account {name} (no login shell, home {})", + ctx.opts.dirs.state.display() + )); + let args: Vec = [ + "--system", + "--no-create-home", + "--home-dir", + &ctx.opts.dirs.state.display().to_string(), + "--shell", + "/usr/sbin/nologin", + name, + ] + .iter() + .map(|s| s.to_string()) + .collect(); + run_tool( + "useradd", + Path::new("useradd"), + &args, + &ctx.paths.logs().join("install.log"), + ) + .await +} + +#[cfg(unix)] +pub fn chown_tree(root: &Path, uid: u32, gid: u32) -> Result<(), String> { + use std::os::unix::fs::chown; + if let Ok(meta) = std::fs::symlink_metadata(root) { + if meta.file_type().is_symlink() { + return Ok(()); + } + chown(root, Some(uid), Some(gid)).map_err(|e| format!("chown {}: {e}", root.display()))?; + if meta.is_dir() { + for entry in std::fs::read_dir(root) + .map_err(|e| e.to_string())? + .flatten() + { + chown_tree(&entry.path(), uid, gid)?; + } + } + } + Ok(()) +} + +#[cfg(unix)] +pub fn hand_over_to_service_user(ctx: &Context) -> Result<(), String> { + if !matches!(ctx.mode, Mode::Systemd(UnitScopeTag::System)) || ctx.service_user == "root" { + return Ok(()); + } + let (uid, gid) = lookup_user(&ctx.service_user) + .ok_or_else(|| format!("service user {} does not exist", ctx.service_user))?; + chown_tree(&ctx.paths.dirs.state, uid, gid)?; + chown_tree(&ctx.paths.dirs.assets, uid, gid) +} + +// --------------------------------------------------------------------------------------------------------------- +// systemd + +async fn systemctl(scope: UnitScopeTag, args: &[&str], log: &Path) -> Result<(), String> { + let mut all: Vec = Vec::new(); + if scope == UnitScopeTag::User { + all.push("--user".into()); + } + all.extend(args.iter().map(|s| s.to_string())); + run_tool("systemctl", Path::new("systemctl"), &all, log).await +} + +async fn systemctl_query(scope: UnitScopeTag, args: &[&str]) -> String { + let mut command = Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + match command + .args(args) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .await + { + Ok(output) => String::from_utf8_lossy(&output.stdout).trim().to_owned(), + Err(_) => String::new(), + } +} + +pub async fn install_unit(ctx: &Context, scope: UnitScopeTag) -> Result { + let (path, text) = unit_text(ctx, scope)?; + let changed = std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()); + if changed { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + std::fs::write(&path, &text) + .map_err(|e| format!("cannot write {}: {e}", path.display()))?; + } + let log = ctx.paths.logs().join("install.log"); + if changed { + systemctl(scope, &["daemon-reload"], &log).await?; + } + systemctl(scope, &["enable", ctx.paths.unit_name()], &log).await?; + Ok(changed) +} + +pub async fn start_unit( + ctx: &Context, + scope: UnitScopeTag, + unit_changed: bool, +) -> Result<(), String> { + let log = ctx.paths.logs().join("install.log"); + let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await; + if active == "active" && unit_changed { + say("the unit changed while the service runs: restarting it"); + systemctl(scope, &["restart", ctx.paths.unit_name()], &log).await + } else if active == "active" || active == "activating" { + say("the service is already running; waiting for it to become ready"); + Ok(()) + } else { + systemctl(scope, &["start", ctx.paths.unit_name()], &log).await + } +} + +/// Poll `/ready`, printing the supervisor's phase every 15 s. Fails fast when the unit or supervisor failed. +pub async fn wait_ready(ctx: &Context, scope: Option) -> Result<(), String> { + let started = Instant::now(); + let limit = Duration::from_secs(ctx.opts.timeout_s); + let mut last_phase = String::new(); + let mut last_print = Instant::now() - Duration::from_secs(60); + loop { + if probe_ready(ctx).await { + return Ok(()); + } + let status: Option = std::fs::read_to_string(ctx.paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let phase = status + .as_ref() + .and_then(|s| s.get("phase")) + .and_then(|v| v.as_str()) + .unwrap_or("not started") + .to_owned(); + if phase == "failed" { + let message = status + .as_ref() + .and_then(|s| s.get("message")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + return Err(format!("the service failed: {message}\n{}", log_tail(ctx))); + } + if let Some(scope) = scope { + let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await; + if active == "failed" { + return Err(format!( + "{} failed\n{}", + ctx.paths.unit_name(), + log_tail(ctx) + )); + } + } + if phase != last_phase || last_print.elapsed() >= Duration::from_secs(30) { + say(&format!( + "waiting for ready: {phase} ({:.0}s)", + started.elapsed().as_secs_f32() + )); + last_phase = phase; + last_print = Instant::now(); + } + if started.elapsed() > limit { + return Err(format!( + "not ready after {} s (phase {last_phase}); the service keeps running; logs in {}", + limit.as_secs(), + ctx.paths.logs().display() + )); + } + tokio::time::sleep(Duration::from_secs(3)).await; + } +} + +fn log_tail(ctx: &Context) -> String { + let mut out = String::new(); + for name in ["leleka.log", "engine.log"] { + if let Ok(text) = std::fs::read_to_string(ctx.paths.logs().join(name)) { + let lines: Vec<&str> = text.lines().collect(); + let tail = &lines[lines.len().saturating_sub(12)..]; + out.push_str(&format!( + "--- last lines of {} ---\n{}\n", + ctx.paths.logs().join(name).display(), + tail.join("\n") + )); + } + } + out +} + +// --------------------------------------------------------------------------------------------------------------- +// the whole plan + +/// Will the `kar` step run `ensure-sharded-streamed`? That tool fetches and verifies the shards itself. +fn kar_runs_tool(ctx: &Context, steps: &[Step]) -> bool { + let kar_todo = steps + .iter() + .any(|s| s.id == "kar" && matches!(s.state, StepState::Todo(_))); + let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES) + && ctx.paths.kar_provenance().is_file(); + kar_todo && !(ctx.opts.trust_archive && present) +} + +/// Run every `Todo` step of the plan up to (not including) the start of the service. Returns the steps as +/// re-planned after the work, which the caller prints in `--json` mode. +/// What the preparation changed that a running service does not see until it restarts. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Changes { + pub binaries: usize, + pub configs: usize, +} + +impl Changes { + pub fn needs_restart(&self) -> bool { + self.binaries > 0 || self.configs > 0 + } +} + +pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result { + let mut changes = Changes::default(); + let total = steps.len(); + for (index, step) in steps.iter().enumerate() { + match &step.state { + StepState::Blocked(why) => { + return Err(format!( + "step {} ({}) is blocked: {why}", + step.id, step.title + )); + } + StepState::Done(_) | StepState::Skip(_) => continue, + StepState::Todo(_) => {} + } + if matches!(step.id, "preflight" | "service" | "start" | "ready") { + continue; + } + if step.id == "model" && kar_runs_tool(ctx, steps) { + say("the shards are fetched and verified by the archive step below"); + continue; + } + say(&format!("[{}/{}] {}", index + 1, total, step.title)); + let started = Instant::now(); + let result: Result<(), String> = match step.id { + "layout" => make_dirs(ctx), + "binaries" => install_binaries(ctx).map(|n| { + changes.binaries += n; + say(&format!( + "installed {n} binaries into {}", + ctx.paths.bin_dir().display() + )) + }), + "cublas" => install_cublas(ctx).await, + "secrets" => { + write_secrets_and_env(ctx)?; + init_api_key(ctx).await + } + "model" => fetch_and_verify_model(ctx).await, + "kar" => ensure_kar(ctx).await, + "mtp-pack" => import_mtp_pack(ctx).await, + "tokenizer" => extract_tokenizer(ctx).await, + "config" => write_configs(ctx).map(|n| { + changes.configs += n; + say(&format!( + "wrote {n} configuration file(s) in {}", + ctx.paths.dirs.state.display() + )) + }), + other => Err(format!("internal error: no executor for step {other}")), + }; + result.map_err(|e| format!("step {} failed: {e}", step.id))?; + say(&format!( + "[{}/{}] done in {:.1}s", + index + 1, + total, + started.elapsed().as_secs_f32() + )); + } + Ok(changes) +} + +/// Re-plan with the current state of the disk (after `prepare`), used to decide what `start` has to do. +pub async fn replan(ctx: &Context) -> Vec { + let fs = gather_fs(ctx).await; + plan_steps(ctx, &fs) +} + +pub fn config_of(ctx: &Context) -> Result<&RunConfig, String> { + ctx.config + .as_ref() + .ok_or_else(|| "no profile could be selected".to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("leleka-steps-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn stamps_track_size_and_mtime() { + let dir = temp("stamp"); + let (a, b) = (dir.join("a.gguf"), dir.join("b.gguf")); + std::fs::write(&a, b"aaaa").unwrap(); + std::fs::write(&b, b"bb").unwrap(); + let stamp = dir.join("model.json"); + assert!(!stamp_current(&stamp, &[a.clone(), b.clone()])); + write_stamp(&stamp, "test", &[a.clone(), b.clone()]).unwrap(); + assert!(stamp_current(&stamp, &[a.clone(), b.clone()])); + std::fs::write(&b, b"bbb").unwrap(); + assert!( + !stamp_current(&stamp, &[a.clone(), b.clone()]), + "a changed size must invalidate the stamp" + ); + assert!(!stamp_current(&stamp, std::slice::from_ref(&a))); + std::fs::remove_file(&a).unwrap(); + assert!(!stamp_current(&stamp, &[a, b])); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn mtp_pack_root_is_found_in_a_subdirectory() { + let dir = temp("mtp"); + let nested = dir.join("data/mtp-rt"); + std::fs::create_dir_all(&nested).unwrap(); + assert_eq!(find_pack_root(&dir), None); + for name in MTP_FILES { + std::fs::write(nested.join(name), b"x").unwrap(); + } + assert_eq!(find_pack_root(&dir), Some(nested)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn sha256_of_a_file() { + let dir = temp("sha"); + let file = dir.join("f"); + std::fs::write(&file, b"abc").unwrap(); + assert_eq!( + sha256_file(&file).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs new file mode 100644 index 00000000..f07f2c13 --- /dev/null +++ b/crates/deploy/src/supervisor.rs @@ -0,0 +1,1067 @@ +//! `leleka run`: the foreground supervisor that systemd (or a terminal) starts. +//! +//! Order: seal the archive (once) -> gateway -> engine -> wait for the engine port -> typed `load-mtp` through +//! `leleka-cli` -> wait for `model_ready` -> public API -> wait for `/ready` -> supervise. An engine that dies is +//! restarted with the same sealed descriptor (no second 55 GB copy) and loaded again, up to a bound; the API +//! process stays up and reports not-ready meanwhile. SIGTERM/SIGINT drain the API first, then stop the gateway +//! and the engine (both handle SIGINT only), and escalate to SIGKILL after the grace period. +use crate::{ + config::{GATEWAY_TOKEN_ENV, KarArg, RUNTIME_TOKEN_ENV, RunConfig}, + facts::parse_env_file, + http, + layout::{MTP_PROFILE, Paths}, + profile::{ARCHIVE_BYTES, KarSource}, + sealed, +}; +use serde::Serialize; +use std::{ + collections::BTreeMap, + fs::File, + io::Write, + net::SocketAddr, + path::{Path, PathBuf}, + process::Stdio, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use tokio::{ + process::{Child, Command}, + sync::watch, + time::{sleep, timeout}, +}; + +const LOG_ROTATE_BYTES: u64 = 64 << 20; + +#[derive(Clone, Debug)] +pub struct Options { + pub config: PathBuf, + /// A sealed archive descriptor inherited from a holder process (tests, operator tooling). The supervisor + /// reopens it and does not copy the archive itself. + pub kar_fd: Option, +} + +#[derive(Debug)] +pub struct Failure { + pub code: i32, + pub message: String, +} + +fn fail(code: i32, message: impl Into) -> Result { + Err(Flow::Fatal(Failure { + code, + message: message.into(), + })) +} + +#[derive(Debug)] +enum Flow { + /// A stop signal arrived while waiting. + Stopped, + Fatal(Failure), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Starting, + Sealing, + StartingGateway, + StartingEngine, + Loading, + StartingApi, + Ready, + EngineRestarting, + Draining, + Stopped, + Failed, +} + +#[derive(Serialize)] +struct StatusDoc<'a> { + schema_version: u32, + phase: Phase, + ready: bool, + message: &'a str, + updated_unix: u64, + supervisor_pid: u32, + engine_pid: Option, + gateway_pid: Option, + api_pid: Option, + engine_restarts: u32, + endpoint: &'a str, + model: &'a str, + model_digest: &'a str, + profile: &'a str, + kar_source: &'a str, +} + +/// 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 { + fn line(&self, message: &str) { + let line = format!("{} leleka: {message}\n", format_utc(unix_now())); + let _ = std::io::stderr().write_all(line.as_bytes()); + if let Ok(mut file) = self.file.lock() { + let _ = file.write_all(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). +pub fn tail_of(path: &Path, lines: usize) -> String { + let text = std::fs::read_to_string(path).unwrap_or_default(); + let all: Vec<&str> = text.lines().collect(); + all[all.len().saturating_sub(lines)..] + .iter() + .map(|l| l.chars().take(240).collect::()) + .collect::>() + .join( + " +", + ) +} + +/// 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, + env: BTreeMap, + api_key: String, + log: Log, + status_path: PathBuf, + shutdown: watch::Receiver, + archive: Option, + api_addr: SocketAddr, + engine_addr: SocketAddr, + daemon_addr: SocketAddr, + engine_restarts: u32, + pids: [Option; 3], + phase: Phase, +} + +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(); + for dir in [paths.logs(), paths.run_dir(), paths.mtp_staging()] { + 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; + let _ = + std::fs::set_permissions(paths.mtp_staging(), 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)?, + ); + 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); + 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, + api_addr, + engine_addr, + daemon_addr, + engine_restarts: 0, + pids: [None; 3], + phase: Phase::Starting, + }; + 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.line(&format!("fatal: {}", failure.message)); + supervisor.set_phase(Phase::Failed, &failure.message); + Err(failure) + } + }; + if result.is_ok() { + supervisor.set_phase(Phase::Stopped, "stopped"); + } + result +} + +fn spawn_signal_task(stop: watch::Sender) { + #[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(unix))] + drop(stop); +} + +impl Supervisor { + fn set_phase(&mut self, phase: Phase, message: &str) { + self.phase = phase; + 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(), + }; + 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"); + for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] { + if let Some(value) = self.env.get(key) { + command.env(key, value); + } + } + 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); + 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()), + ), + } + } + + 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), _) => { + self.log.line(&format!( + "using the sealed archive descriptor {fd} inherited from the parent" + )); + Some( + sealed::open_inherited(fd) + .map_err(|message| Flow::Fatal(Failure { code: 2, message }))?, + ) + } + (None, KarSource::Memfd) => { + self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); + let kar = self.paths.kar(); + self.log.line(&format!( + "sealing {} into RAM (once per service life)", + kar.display() + )); + let started = Instant::now(); + let log = &self.log; + let sealed = sealed::seal_file(&kar, Some(ARCHIVE_BYTES), &mut |done, total| { + log.line(&format!( + "sealing archive: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + )); + }); + match sealed { + Ok(file) => { + self.log.line(&format!( + "sealed memfd ready in {:.1}s", + started.elapsed().as_secs_f32() + )); + 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(); + let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32); + + // 4. supervise + let result: Result<(), Flow> = loop { + tokio::select! { + _ = self.shutdown.changed() => break Ok(()), + status = engine.wait() => { + let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); + self.log.line(&format!("engine exited ({text}); the API reports not-ready until it is back")); + self.pids[0] = None; + if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) { + self.engine_restarts = 0; + } + if self.engine_restarts >= self.config.restart.max_engine_restarts { + break fail(1, format!("the engine died {} times; see {}", self.engine_restarts + 1, self.paths.logs().join("engine.log").display())); + } + self.engine_restarts += 1; + self.set_phase(Phase::EngineRestarting, "restarting the engine"); + if !self.pause(Duration::from_secs(5)).await { + break Ok(()); + } + match self.start_engine(&mut gateway).await { + Ok(child) => { + engine = child; + self.set_phase(Phase::Ready, "ready (engine restarted)"); + ready_since = Instant::now(); + } + 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()); + gateway_restarts += 1; + self.log.line(&format!("gateway exited ({text}); restart {gateway_restarts}/3")); + 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(); + } + status = api.wait() => { + let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); + api_restarts += 1; + self.log.line(&format!("API exited ({text}); restart {api_restarts}/5")); + 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(); + } + } + }; + + // 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"); + let env = self.config.engine_environment(); + 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 => (KarArg::File, None), + }; + let engine_args = self.config.engine_args(kar_arg); + 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); + } + 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, 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); + } + } + } + + /// 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(not(target_os = "linux"))] +fn interrupt(_child: &Child) {} + +#[cfg(test)] +mod tests { + 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/src/units.rs b/crates/deploy/src/units.rs new file mode 100644 index 00000000..b7b0d095 --- /dev/null +++ b/crates/deploy/src/units.rs @@ -0,0 +1,199 @@ +//! systemd unit for the supervisor (`leleka run`). One unit runs the whole service; the supervisor owns the +//! engine, gateway and API children, restarts the engine without copying the archive again, and drains on +//! SIGTERM/SIGINT. +use std::path::Path; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnitScope { + /// `/etc/systemd/system`, started at boot, `User=` the owner of the state directory. + System, + /// `~/.config/systemd/user`; needs `loginctl enable-linger USER` to start without a login session. + User, +} + +fn quote(path: &Path) -> Result { + let text = path.to_str().ok_or("path is not UTF-8")?; + if !text.starts_with('/') + || text + .chars() + .any(|c| c.is_control() || c == '"' || c == '\\' || c == '%' || c == '$') + { + return Err(format!( + "path {text:?} cannot be used in a unit file (must be absolute without quotes, %, $ or control characters)" + )); + } + Ok(if text.contains(' ') { + format!("\"{text}\"") + } else { + text.to_owned() + }) +} + +/// Render the unit. `user` is only used for the system scope. +pub fn render( + scope: UnitScope, + prefix: &Path, + state: &Path, + user: Option<&str>, +) -> Result { + let bin = quote(&prefix.join("bin/leleka"))?; + let config = quote(&state.join("leleka.json"))?; + let env_file = quote(&state.join("runtime.env"))?; + let mut unit = String::new(); + unit.push_str("# Generated by `leleka up`; edit the run configuration, not this file.\n"); + unit.push_str("[Unit]\n"); + unit.push_str("Description=Leleka runtime (engine, gateway and API on loopback)\n"); + unit.push_str("Documentation=https://github.com/paveldhq/strata-next (docs/deploy.md)\n"); + unit.push_str("After=network.target\n"); + unit.push_str("StartLimitIntervalSec=1800\nStartLimitBurst=3\n\n"); + unit.push_str("[Service]\n"); + unit.push_str("Type=exec\n"); + if scope == UnitScope::System { + let user = user.ok_or("a system unit needs a service user")?; + if user.is_empty() + || !user + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + { + return Err("service user must be [A-Za-z0-9_.-]+".into()); + } + unit.push_str(&format!("User={user}\n")); + } + unit.push_str(&format!("EnvironmentFile={env_file}\n")); + unit.push_str("UMask=0077\nNoNewPrivileges=yes\n"); + // Pinned host memory (cudaHostAlloc/Register) is counted against RLIMIT_MEMLOCK on some drivers. + unit.push_str("LimitMEMLOCK=infinity\n"); + unit.push_str(&format!("ExecStart={bin} run --config {config}\n")); + // A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error. + unit.push_str("Restart=on-failure\nRestartSec=30\nRestartPreventExitStatus=2\n"); + // The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine. + unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=120\nKillMode=mixed\n\n"); + unit.push_str("[Install]\n"); + unit.push_str(match scope { + UnitScope::System => "WantedBy=multi-user.target\n", + UnitScope::User => "WantedBy=default.target\n", + }); + Ok(unit) +} + +pub fn unit_path( + scope: UnitScope, + home: Option<&Path>, + name: &str, +) -> Result { + match scope { + UnitScope::System => Ok(Path::new("/etc/systemd/system").join(name)), + UnitScope::User => { + let home = home.ok_or("HOME is not set")?; + Ok(home.join(".config/systemd/user").join(name)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn system_unit_is_complete_and_bounded() { + let unit = render( + UnitScope::System, + Path::new("/opt/leleka"), + Path::new("/var/lib/leleka/state"), + Some("leleka"), + ) + .unwrap(); + for needle in [ + "User=leleka", + "EnvironmentFile=/var/lib/leleka/state/runtime.env", + "ExecStart=/opt/leleka/bin/leleka run --config /var/lib/leleka/state/leleka.json", + "Restart=on-failure", + "RestartPreventExitStatus=2", + "StartLimitBurst=3", + "LimitMEMLOCK=infinity", + "KillSignal=SIGTERM", + "WantedBy=multi-user.target", + ] { + assert!(unit.contains(needle), "missing {needle}\n{unit}"); + } + assert!(!unit.contains("Password") && !unit.contains("TOKEN")); + } + + #[test] + fn user_unit_has_no_user_line_and_targets_default() { + let unit = render( + UnitScope::User, + Path::new("/home/p/.local/share/leleka"), + Path::new("/home/p/.local/state/leleka"), + None, + ) + .unwrap(); + assert!(!unit.contains("User=") && unit.contains("WantedBy=default.target")); + } + + #[test] + fn dangerous_paths_and_users_are_refused() { + assert!( + render( + UnitScope::System, + Path::new("/opt/le%leka"), + Path::new("/s"), + Some("u") + ) + .is_err() + ); + assert!( + render( + UnitScope::System, + Path::new("/opt/leleka"), + Path::new("relative"), + Some("u") + ) + .is_err() + ); + assert!( + render( + UnitScope::System, + Path::new("/opt/leleka"), + Path::new("/s"), + Some("a b") + ) + .is_err() + ); + assert!( + render( + UnitScope::System, + Path::new("/opt/leleka"), + Path::new("/s"), + None + ) + .is_err() + ); + let spaced = render( + UnitScope::User, + Path::new("/opt/my leleka"), + Path::new("/s"), + None, + ) + .unwrap(); + assert!(spaced.contains("\"/opt/my leleka/bin/leleka\"")); + } + + #[test] + fn unit_locations() { + assert_eq!( + unit_path(UnitScope::System, None, "leleka.service").unwrap(), + Path::new("/etc/systemd/system/leleka.service") + ); + assert_eq!( + unit_path( + UnitScope::User, + Some(Path::new("/home/p")), + "leleka.service" + ) + .unwrap(), + Path::new("/home/p/.config/systemd/user/leleka.service") + ); + assert!(unit_path(UnitScope::User, None, "x").is_err()); + } +} diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs new file mode 100644 index 00000000..51ab6a77 --- /dev/null +++ b/crates/deploy/tests/e2e.rs @@ -0,0 +1,889 @@ +//! 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; + 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 { + let mut command = Process::new(LELEKA); + command.arg("run").arg("--config").arg(config); + 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", + }); + 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}"), + } + // 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 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); +} + +#[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 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 + +fn up_options( + fixture: &Fixture, + bin_src: &Path, + cublas: &Path, + mtp: &Path, + 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", + "rtx3080-16g", + "--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 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, 8192); + 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/recipe.rs b/crates/deploy/tests/recipe.rs new file mode 100644 index 00000000..d3e1b097 --- /dev/null +++ b/crates/deploy/tests/recipe.rs @@ -0,0 +1,154 @@ +//! Static checks of the packaging recipes (no container engine needed): the OCI recipe keeps the model and +//! secrets out of the image, runs non-root with a health check, and the install script is valid POSIX sh. +use std::path::{Path, PathBuf}; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(relative: &str) -> String { + std::fs::read_to_string(repo().join(relative)).unwrap_or_else(|e| panic!("{relative}: {e}")) +} + +/// The instruction lines of a Containerfile (comments and blank lines removed, continuations joined). +fn instructions(text: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + for line in text.lines() { + let line = line.trim_end(); + if line.trim_start().starts_with('#') || line.trim().is_empty() { + continue; + } + if let Some(stripped) = line.strip_suffix('\\') { + current.push_str(stripped.trim_start()); + current.push(' '); + } else { + current.push_str(line.trim_start()); + out.push(std::mem::take(&mut current)); + } + } + out +} + +#[test] +fn the_oci_recipe_is_non_root_checked_and_model_free() { + let text = read("deploy/Containerfile.rust-runtime"); + let lines = instructions(&text); + let find = |prefix: &str| { + lines + .iter() + .filter(|l| l.starts_with(prefix)) + .cloned() + .collect::>() + }; + // Non-root, and the last USER wins. + assert_eq!( + find("USER ").last().map(String::as_str), + Some("USER 10001:10001") + ); + // A health check that does not need a GPU probe. + let health = find("HEALTHCHECK").join(" "); + assert!( + health.contains("/opt/leleka/bin/leleka") && health.contains("status"), + "{health}" + ); + // The model volume is external: declared, never copied. + assert!(find("VOLUME").join(" ").contains("/models")); + for copy in find("COPY").iter().chain(find("ADD").iter()) { + let lower = copy.to_ascii_lowercase(); + for forbidden in [ + ".gguf", + ".kar", + "mtp-rt", + "api-key", + "runtime.env", + "token", + "secret", + ] { + assert!( + !lower.contains(forbidden), + "{copy} would bake {forbidden} into the image" + ); + } + } + // Only the binaries, the cuBLAS libraries and the manifests are copied in. + let copies: Vec = find("COPY"); + assert!(copies.iter().any(|c| c.contains("bin/ /opt/leleka/bin/"))); + assert!(copies.iter().any(|c| c.contains("--from=cublas"))); + // The cuBLAS download is checksum-pinned. + assert!( + find("ADD") + .iter() + .any(|a| a.contains("--checksum=sha256:${CUBLAS_SHA256}")) + ); + assert!(text.contains("546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057")); + // No secret-looking environment, no ssh keys, no package-manager network step in the runtime stage. + for env in find("ENV") { + assert!( + !env.to_ascii_uppercase().contains("TOKEN") + && !env.to_ascii_uppercase().contains("KEY="), + "{env}" + ); + } + assert_eq!( + find("ENTRYPOINT"), + vec![r#"ENTRYPOINT ["/opt/leleka/bin/leleka"]"#.to_string()] + ); + assert!(find("CMD").join(" ").contains("--foreground")); +} + +#[test] +fn the_cublas_pin_matches_the_tool_and_the_documentation() { + let recipe = read("deploy/Containerfile.rust-runtime"); + let plan = read("crates/deploy/src/plan.rs"); + for pinned in [ + "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057", + "libcublas-linux-x86_64-12.9.1.4-archive.tar.xz", + ] { + assert!( + recipe.contains(pinned) && plan.contains(pinned), + "{pinned} differs between the recipe and plan.rs" + ); + assert!(read("docs/rust-runtime-run.md").contains(pinned)); + } +} + +#[cfg(unix)] +#[test] +fn install_script_is_valid_sh_and_verifies_before_it_runs() { + let script = repo().join("deploy/rust-runtime/install.sh"); + let status = std::process::Command::new("sh") + .arg("-n") + .arg(&script) + .status() + .unwrap(); + assert!(status.success()); + let text = read("deploy/rust-runtime/install.sh"); + let verify = text + .find("sha256sum --quiet -c SHA256SUMS") + .expect("verifies the release"); + let run = text + .find("exec ./bin/leleka up") + .expect("hands over to leleka up"); + assert!( + verify < run, + "the checksum check must come before the hand-over" + ); +} + +#[test] +fn systemd_unit_templates_do_not_carry_secrets() { + for template in [ + "leleka-daemon.service", + "leleka-inference.service", + "runtime.env.example", + ] { + let text = read(&format!("deploy/rust-runtime/{template}")); + assert!( + !text + .lines() + .any(|l| l.trim_start().starts_with("Environment=") && l.contains("TOKEN")), + "{template}" + ); + } +} diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index b8585ad3..19bcd1ee 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -4,7 +4,7 @@ pub(crate) mod original_prompt; #[path = "backend_original_serve.rs"] mod original_serve; -pub use original_serve::{OriginalServeChoice, OriginalServeMode, OriginalServeOptions}; +pub use original_serve::{ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions}; use crate::experimental::{self as experimental_modes, ExperimentalConfig}; use crate::model_binding::kar_expert_source::KarExpertSource; pub use crate::model_binding::kar_expert_source::{ @@ -1268,11 +1268,15 @@ fn serve_load( }; // Only this fresh unpublished selected binding can gain the raw RAM bank. // Complete GGUF/KAR/MTP admission already finished; no sessions or Ready exist. - if optimized.is_some() { + // The Original serve stack reads the same bank (CPU window tier, prompt arena); without it the stack's + // arena fails with InputRead at Load. The operator picks the RAM copy (server) or the mappings (laptop). + if optimized.is_some() || original.is_some() { (if streamed_spill { binding.adopt_resident_expert_capture(expert_capture.ok_or_else(|| { load_failure(LoadPhase::SelectedBinding, invalid("streamed expert capture absent")) })?) + } else if original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped) { + binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() }).map_err(|error| { diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index aa4282ee..3d139e58 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -39,6 +39,32 @@ impl OriginalServeMode { } } +/// Where the routed experts come from for the Original path. The window CPU tier and the prompt arena read the +/// bank of the selected binding, so exactly one form must be admitted before the stack opens. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum ExpertSource { + /// A RAM copy of the routed experts of shard 0 (about 50 GB, page-locked): the server form, as the serve smoke does. + #[default] + Resident, + /// Read-only shared mappings of shard 0, nothing copied: the low-RAM (laptop) form, `docs/laptop-profile.md`. + Mapped, +} +impl ExpertSource { + pub fn parse(text: &str) -> Option { + match text { + "resident" => Some(Self::Resident), + "mapped" => Some(Self::Mapped), + _ => None, + } + } + pub fn as_str(self) -> &'static str { + match self { + Self::Resident => "resident", + Self::Mapped => "mapped", + } + } +} + /// Operator choices of the Original path. Nothing here enters an RPC. #[derive(Clone, Debug)] pub struct OriginalServeOptions { @@ -63,6 +89,8 @@ pub struct OriginalServeOptions { pub prompt_cache_root: usize, /// `--turn-token ID`: the token that opens a chat turn (`<|im_start|>`); `None` = no turn checkpoints. pub turn_token: Option, + /// `--expert-source resident|mapped`: how the routed-expert bank is admitted before the stack opens. + pub expert_source: ExpertSource, } impl Default for OriginalServeOptions { fn default() -> Self { @@ -77,6 +105,7 @@ impl Default for OriginalServeOptions { prompt_cache_every: 16_384, prompt_cache_root: 2048, turn_token: Some(crate::qwen_forward::original_serve_stack::TURN_TOKEN), + expert_source: ExpertSource::default(), } } } diff --git a/deploy/Containerfile.rust-runtime b/deploy/Containerfile.rust-runtime new file mode 100644 index 00000000..01b28458 --- /dev/null +++ b/deploy/Containerfile.rust-runtime @@ -0,0 +1,67 @@ +# OCI image of the Rust runtime (engine + gateway + API + `leleka`): binaries and CUDA 12 cuBLAS only. +# +# NOT in the image, by design: +# * the model (shards, KAR archive, MTP pack, tokenizer) - mount a volume at /models; never baked, never in Git; +# * the NVIDIA driver and libcuda.so.1 - injected by the NVIDIA Container Toolkit (docker run --gpus all); +# * secrets - the tokens and the API key are generated into the /state volume on the first start; +# * the sealed PTX is embedded in the binaries (sm_120, and the sm_86 companions when built with `sm86`). +# +# Build context = an unpacked release tarball (it holds bin/ and MANIFEST.json), see docs/deploy.md: +# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64 +# docker build -f /path/to/deploy/Containerfile.rust-runtime -t leleka-runtime:VERSION . +# +# Base: Ubuntu 24.04 (glibc 2.39), the oldest glibc the release is built against. Pin the digest for a release: +# docker buildx imagetools inspect ubuntu:24.04 -> --build-arg BASE=ubuntu:24.04@sha256:... +ARG BASE=ubuntu:24.04 + +# --- stage 1: the pinned NVIDIA cuBLAS 12.9.1.4 redistributable, checksum-verified by BuildKit --------------- +FROM ${BASE} AS cublas +ARG CUBLAS_URL=https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz +ARG CUBLAS_SHA256=546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057 +ADD --checksum=sha256:${CUBLAS_SHA256} ${CUBLAS_URL} /cublas.tar.xz +RUN mkdir /out \ + && tar -xJf /cublas.tar.xz -C /out --strip-components=1 --wildcards '*/lib/libcublas.so.12*' '*/lib/libcublasLt.so.12*' '*/LICENSE' \ + && mv /out/LICENSE /out/lib/LICENSE-cublas.txt + +# --- stage 2: the runtime --------------------------------------------------------------------------------------- +FROM ${BASE} +ARG VERSION=dev +LABEL org.opencontainers.image.title="leleka-runtime" \ + org.opencontainers.image.description="Leleka runtime: Rust CUDA engine, gateway and API. Model volume mounted externally." \ + org.opencontainers.image.version="${VERSION}" + +RUN groupadd --gid 10001 leleka \ + && useradd --uid 10001 --gid 10001 --no-create-home --home-dir /state --shell /usr/sbin/nologin leleka \ + && install -d -m 0755 /opt/leleka/bin /opt/leleka/lib/cublas /usr/share/leleka \ + && install -d -m 0700 -o leleka -g leleka /state \ + && install -d -m 0755 -o leleka -g leleka /models + +COPY --chmod=0755 bin/ /opt/leleka/bin/ +COPY --from=cublas --chmod=0644 /out/lib/ /opt/leleka/lib/cublas/ +# MANIFEST.json sits next to bin/ so that `leleka` sees the build features (sm86) and the binary digests. +COPY --chmod=0644 MANIFEST.json PROVENANCE.json SHA256SUMS /opt/leleka/ +COPY --chmod=0755 install.sh /usr/share/leleka/install.sh + +# `leleka up` finds libcublas.so.12 in PREFIX/lib/cublas on its own and records it in the service environment. +# The paths below are the defaults of `leleka` (--prefix / --state-dir / --assets). +ENV LELEKA_PREFIX=/opt/leleka \ + LELEKA_STATE=/state \ + LELEKA_ASSETS=/models \ + HOME=/state \ + NVIDIA_VISIBLE_DEVICES=all \ + NVIDIA_DRIVER_CAPABILITIES=compute,utility + +USER 10001:10001 +WORKDIR /state +VOLUME ["/models", "/state"] +EXPOSE 8081 + +# Ready = the API answers /ready with the key kept in /state. The first start downloads, verifies and converts +# the model (hours), so the start period is long; a restart with a populated volume is minutes. +HEALTHCHECK --interval=30s --timeout=10s --start-period=4h --retries=3 \ + CMD ["/opt/leleka/bin/leleka", "status"] + +# SIGTERM -> `leleka` drains the API, then stops the gateway and the engine. +STOPSIGNAL SIGTERM +ENTRYPOINT ["/opt/leleka/bin/leleka"] +CMD ["up", "--foreground", "--no-install-cublas", "--api-bind", "0.0.0.0", "--timeout-s", "86400"] diff --git a/deploy/rust-runtime/install.sh b/deploy/rust-runtime/install.sh new file mode 100755 index 00000000..196756e0 --- /dev/null +++ b/deploy/rust-runtime/install.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# One command on a fresh Linux CUDA machine (or WSL2): verify this release, then hand over to `leleka up`. +# +# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64 +# sudo ./install.sh --assets /data/leleka # systemd service, starts at boot +# ./install.sh --assets ~/leleka --foreground # WSL2 without systemd, or a terminal +# ./install.sh --dry-run # print the plan, change nothing +# +# Every option is passed to `leleka up` (see `./bin/leleka --help`). Nothing here needs Python. +set -eu + +here=$(cd "$(dirname "$0")" && pwd) +cd "$here" + +case "$(uname -s)/$(uname -m)" in + Linux/x86_64) ;; + *) echo "install.sh: this release is for Linux x86_64 (WSL2 included), not $(uname -s)/$(uname -m)" >&2; exit 1 ;; +esac + +[ -x ./bin/leleka ] || { echo "install.sh: ./bin/leleka is missing; run this script from the unpacked release directory" >&2; exit 1; } + +if [ -f SHA256SUMS ]; then + if command -v sha256sum >/dev/null 2>&1; then + echo "install.sh: verifying the release files against SHA256SUMS ..." >&2 + sha256sum --quiet -c SHA256SUMS || { + echo "install.sh: a file does not match SHA256SUMS; download the release again" >&2 + exit 1 + } + else + echo "install.sh: sha256sum not found, skipping the integrity check" >&2 + fi +fi + +exec ./bin/leleka up "$@" diff --git a/deploy/rust-runtime/profiles/rtx3080-16g.json b/deploy/rust-runtime/profiles/rtx3080-16g.json new file mode 100644 index 00000000..0e4b1cd2 --- /dev/null +++ b/deploy/rust-runtime/profiles/rtx3080-16g.json @@ -0,0 +1,18 @@ +{ + "name": "rtx3080-16g", + "description": "RTX 3080 Laptop class (sm_86, 16 GB VRAM, 24-48 GB RAM, typically WSL2). The KAR archive stays an ordinary read-only file (no 55 GB memfd), routed experts are served from the memory-mapped shards, context is capped at 8192. Experimental (docs/laptop-profile.md): measured on one laptop, slower than the server profile, no quality claim.", + "select": {"sm_min": 80, "sm_max": 120, "vram_mib_min": 14000, "vram_mib_max": 24000}, + "gpu_budget_bytes": 16106127360, + "context_tokens": 8192, + "kar_source": "file", + "expert_source": "mapped", + "min_driver_major": 595, + "min_vram_total_mib": 14000, + "min_vram_free_mib": 14500, + "min_ram_total_bytes": 23622320128, + "min_ram_available_bytes": 10737418240, + "wsl_memory_gib": 32, + "expert_profile": "data/expert-profile.bin", + "expert_profile_sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", + "engine_env": {} +} diff --git a/deploy/rust-runtime/profiles/rtx5090-32g.json b/deploy/rust-runtime/profiles/rtx5090-32g.json new file mode 100644 index 00000000..1c746a8f --- /dev/null +++ b/deploy/rust-runtime/profiles/rtx5090-32g.json @@ -0,0 +1,14 @@ +{ + "name": "rtx5090-32g", + "description": "RTX 5090 class server (sm_120, 32 GB VRAM, >= 100 GiB RAM). The 55 GB level-2 KAR archive is copied once into a sealed memfd and the 50 GB routed-expert bank is a page-locked RAM copy (the bring-up smoke form). Values are the documented bring-up configuration (docs/rust-runtime-run.md), not a tuned or quality-gated profile.", + "select": {"sm_min": 120, "sm_max": 130, "vram_mib_min": 30000, "vram_mib_max": 1000000}, + "gpu_budget_bytes": 25769803776, + "context_tokens": 262144, + "kar_source": "memfd", + "expert_source": "resident", + "min_driver_major": 595, + "min_vram_total_mib": 30000, + "min_ram_total_bytes": 107374182400, + "min_ram_available_bytes": 113000000000, + "engine_env": {} +} diff --git a/desktop-core/src/bin/leleka-inference.rs b/desktop-core/src/bin/leleka-inference.rs index 2fc75ed3..239378c7 100644 --- a/desktop-core/src/bin/leleka-inference.rs +++ b/desktop-core/src/bin/leleka-inference.rs @@ -35,6 +35,7 @@ const PROMPT_CACHE_FLAG: &str = "--prompt-cache"; const PROMPT_CACHE_EVERY_FLAG: &str = "--prompt-cache-every"; const PROMPT_CACHE_ROOT_FLAG: &str = "--prompt-cache-root"; const TURN_TOKEN_FLAG: &str = "--turn-token"; +const EXPERT_SOURCE_FLAG: &str = "--expert-source"; const EXECUTION_FLAGS: [&str; 7] = [ ADAPTIVE_SLOTS_FLAG, RESIDENT_OWNERS_FLAG, @@ -50,7 +51,7 @@ async fn main() -> Result<(), Box> { let args: Vec = std::env::args().skip(1).collect(); if args.as_slice() == ["--help"] { println!( - "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)]" + "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" ); return Ok(()); } @@ -126,10 +127,12 @@ async fn main() -> Result<(), Box> { gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?, context_tokens: context.parse().map_err(|_| "invalid_context_bound")?, kar_ple_source: sources.kar, - kar_ple_inherited: sources - .inherited - .map(|(fd, provenance)| InheritedKarArchive::open(fd, provenance)) - .transpose()?, + kar_ple_inherited: match (sources.inherited, sources.kar_file) { + (Some((fd, provenance)), None) => Some(InheritedKarArchive::open(fd, provenance)?), + // Low-RAM form (docs/laptop-profile.md): an ordinary read-only file instead of a 55 GB sealed memfd. + (None, Some((file, provenance))) => Some(InheritedKarArchive::open_read_only_file(&file, provenance)?), + _ => None, + }, mtp_source: sources.mtp, // The routed-expert KAR source has no operator flag in this binary yet. kar_expert_source: None, @@ -348,6 +351,8 @@ struct OperatorSources { kar: OperatorSource, mtp: OperatorSource, inherited: Option<(u32, PathBuf)>, + /// `--kar-archive-file PATH --kar-provenance PATH`: the archive as a read-only regular file. + kar_file: Option<(PathBuf, PathBuf)>, } fn operator_sources_with_inherited(args: &[String]) -> Result { @@ -355,9 +360,19 @@ fn operator_sources_with_inherited(args: &[String]) -> Result().0 { - if pair[0] == "--kar-archive-fd" { + if pair[0] == "--kar-archive-file" { + if kar_file.is_some() + || pair[2] != "--kar-provenance" + || pair[1].is_empty() + || pair[3].is_empty() + { + return Err("invalid_kar_archive_file_arguments"); + } + kar_file = Some((PathBuf::from(&pair[1]), PathBuf::from(&pair[3]))); + } else if pair[0] == "--kar-archive-fd" { if inherited.is_some() || pair[2] != "--kar-provenance" || pair[1].is_empty() @@ -378,13 +393,14 @@ fn operator_sources_with_inherited(args: &[String]) -> Result 1 { return Err("conflicting_kar_sources"); } Ok(OperatorSources { kar, mtp, inherited, + kar_file, }) } @@ -498,6 +514,26 @@ mod queued_owner_operator_tests { mod inherited_source_tests { use super::*; + #[test] + fn read_only_file_form_is_exclusive_with_the_fd_and_the_staged_forms() { + let file = ["--kar-archive-file", "/assets/a.kar", "--kar-provenance", "/assets/a.json"].map(String::from); + let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from); + let parsed = operator_sources_with_inherited(&file.iter().chain(&mtp).cloned().collect::>()).unwrap(); + assert_eq!(parsed.kar_file, Some(("/assets/a.kar".into(), "/assets/a.json".into()))); + assert_eq!((parsed.inherited, parsed.kar), (None, None)); + let fd = ["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from); + let staged = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from); + for other in [&fd, &staged, &file] { + assert!(operator_sources_with_inherited(&file.iter().chain(other).cloned().collect::>()).is_err()); + } + let mut invalid = file.clone(); + invalid[2] = "--kar-staging".into(); + assert!(operator_sources_with_inherited(&invalid).is_err()); + let mut invalid = file.clone(); + invalid[1].clear(); + assert!(operator_sources_with_inherited(&invalid).is_err()); + } + #[test] fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() { let inherited = @@ -507,6 +543,7 @@ mod inherited_source_tests { kar: None, mtp: Some(("pack".into(), "private".into())), inherited: Some((9, "proof.json".into())), + kar_file: None, }; for args in [ inherited.iter().chain(&mtp).cloned().collect::>(), @@ -551,6 +588,7 @@ mod inherited_source_tests { kar: None, mtp: None, inherited: None, + kar_file: None, } ); } @@ -951,6 +989,7 @@ fn operator_original_serve( let (mut capacity, mut directory, mut floor) = (false, false, false); let (mut kv, mut kv_resident) = (false, false); let (mut cache, mut every, mut root, mut turn) = (false, false, false, false); + let mut expert_source = false; let mut ordinary = Vec::with_capacity(args.len()); let mut offset = 0usize; while offset < args.len() { @@ -1035,6 +1074,13 @@ fn operator_original_serve( Some(u32::try_from(id).map_err(|_| "invalid_turn_token")?) }; offset += 2; + } else if flag == EXPERT_SOURCE_FLAG { + if std::mem::replace(&mut expert_source, true) { + return Err("duplicate_expert_source"); + } + options.expert_source = + leleka_runtime::backend::ExpertSource::parse(value()?).ok_or("invalid_expert_source")?; + offset += 2; } else if flag == PUBLIC_EVALUATION_OUTPUT_FLAG { let end = offset .checked_add(2) @@ -1070,6 +1116,31 @@ mod original_serve_operator_tests { items.iter().map(|s| s.to_string()).collect() } + #[test] + fn expert_source_is_resident_by_default_and_mapped_on_request() { + let (_, options, rest) = operator_original_serve(&args(&[])).unwrap(); + assert_eq!(options.expert_source, leleka_runtime::backend::ExpertSource::Resident); + assert!(rest.is_empty()); + let (_, options, rest) = operator_original_serve(&args(&[ + "--expert-source", + "mapped", + "--kar-archive-file", + "/a.kar", + "--kar-provenance", + "/a.json", + ])) + .unwrap(); + assert_eq!(options.expert_source, leleka_runtime::backend::ExpertSource::Mapped); + assert_eq!(rest, args(&["--kar-archive-file", "/a.kar", "--kar-provenance", "/a.json"])); + for bad in [ + args(&["--expert-source"]), + args(&["--expert-source", "copy"]), + args(&["--expert-source", "mapped", "--expert-source", "resident"]), + ] { + assert!(operator_original_serve(&bad).is_err(), "{bad:?}"); + } + } + #[test] fn the_four_options_are_consumed_and_everything_else_passes_through_unchanged() { let input = args(&[ diff --git a/docs/delivery-gap-audit.md b/docs/delivery-gap-audit.md index 8197a4b4..3bd68994 100644 --- a/docs/delivery-gap-audit.md +++ b/docs/delivery-gap-audit.md @@ -12,6 +12,11 @@ to this branch. The run recipe is [`rust-runtime-run.md`](rust-runtime-run.md). > artefact (a `flock` kept alive past `drop` by a child another test forked meanwhile); the reopen in those tests now waits, and 12 of 12 > parallel runs of the `strata-desktop-core` lib suite passed afterwards (the mechanism itself was not isolated). +> Update 2026-10-17, branch `claude/deploy`: the packaging half of finding 4 and tasks 3-4 of section 7 are addressed in software by +> [`deploy.md`](deploy.md) (`leleka up`: preflight incl. driver/cuBLAS/`/proc`/RAM/disk, asset fetch+verify+archive with stamps, native sealed-memfd supervisor, +> auto-load and readiness, systemd unit, OCI recipe, release tarball with provenance). Still open there: the MTP pack has no automated producer, no clean-VM run on +> Ubuntu 24.04/26.04, the image was not built here (see `deploy.md` section 10), and SIGTERM handling of the daemon/engine is worked around by the supervisor (it sends SIGINT). + 1. **Two serving stacks exist and the full API is wired to the wrong one.** `strata-next` (`control-plane/`) has the Responses / Chat / Messages surface, text.format, custom tools, reasoning, drain, history, MCP hub, but it drives an *engine process over the Original stdio wire protocol* (`READY`/`GEN `/`T `/`DONE`, `control-plane/src/wire.rs`). The Rust engine diff --git a/docs/deploy.md b/docs/deploy.md new file mode 100644 index 00000000..ba75eccb --- /dev/null +++ b/docs/deploy.md @@ -0,0 +1,282 @@ +# One-command deployment: `leleka up` + +Status 2026-10-17, branch `claude/deploy` (base `claude/port-gpu-bringup` @ `5e0bd84`). This page describes the deployment +tool `leleka` (crate `crates/deploy`, no Python at run time), what it does, every flag, and what was and was not run to +check it. Results are in [section 10](#10-what-was-run-and-what-was-not); nothing here is a performance or model-quality +claim. Background: [`rust-runtime-run.md`](rust-runtime-run.md) (the processes), [`model-assets.md`](model-assets.md) (the model +commands `leleka` drives), [`laptop-profile.md`](laptop-profile.md), [`sm86-assets.md`](sm86-assets.md), +[`delivery-gap-audit.md`](delivery-gap-audit.md) section 5 (the packaging gaps this closes in part). + +## 1. Quickstart + +Server (Linux x86_64, NVIDIA driver >= 595, systemd), as root, from the unpacked release: + +```sh +tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64 +sudo ./install.sh --assets /data/leleka # preflight, fetch+verify, KAR archive, install, start, wait for ready +``` + +WSL2 laptop (RTX 3080 16 GB), as your user, in a terminal (WSL2 usually has no systemd): + +```sh +./install.sh --assets ~/leleka --foreground # keep the terminal open; Ctrl-C drains and stops +``` + +Both do the same thing, idempotently, and print the endpoint, model digest, GPU, the VRAM/RAM budget that was chosen, and the +log directory when the service answers `/ready`. Look first with `--dry-run`: it prints the preflight and the plan and changes nothing. + +```sh +./bin/leleka up --dry-run --assets /data/leleka +``` + +This is charter goal G2 (`PROJECT_CHARTER.md` section 6): one command, GPU and memory plan chosen automatically, external model volume, readiness only after the model is loaded, orderly stop and restart of the worker, no Python at run time. +Its acceptance test (a clean Linux GPU node, driver installed, one command, no re-download after a restart) has **not** been run; section 10 lists what was. + +Container: [section 7](#7-container-image). Build your own release: [section 8](#8-build-a-release-tarball). + +## 2. What `up` does + +| # | step | what happens | idempotency | +| --- | --- | --- | --- | +| 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed | +| 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` | +| 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) | +| 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found | +| 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `strata-next api-key init` | never rotated; only missing/invalid ones are created | +| 6 | model | `strata-next model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` | +| 7 | KAR archive | `strata-next model ensure-sharded-streamed qwen-iq3-s --levels 2` (level 2, the pinned 55,295,529,472-byte archive + provenance) | stamped; also checks the length the engine admits | +| 8 | MTP pack | `ASSETS/data/mtp-rt` must exist; `--mtp-pack` imports it from a directory or tarball | skipped when present | +| 9 | tokenizer | `model extract-tokenizer` from shard 1 | skipped when present | +| 10 | config | `leleka.json`, `daemon.json`, `strata.json`, `profile.json`, `runtime.env` | rewritten only when the content changes | +| 11 | service | systemd unit (system or user), `daemon-reload`, `enable`; none in foreground mode | rewritten only when the content changes; a changed unit restarts a running service | +| 12 | start / ready | start the unit (or run the supervisor in this terminal), poll `/ready` with the key, print the summary | an already ready service is left alone | + +The archive step runs `ensure-sharded-streamed`, which fetches and verifies the shards itself, so on a first run step 6 is folded into +step 7 (the plan says so). The strict verification of an *existing* archive re-derives the 708 GB virtual F32 stream and is slow; a +machine that already holds the archive can pass `--trust-archive`: the archive is accepted when it has the pinned length and a +provenance file, and the engine checks its SHA-256 and every CRC against the pinned digest at each load anyway. + +A failed run is resumable: fix the cause and run the same command; finished steps are skipped (downloads continue from `.part`). + +## 3. The processes and files + +```text +leleka run (supervisor, the systemd ExecStart or your terminal) + |- seals the KAR archive into a memfd ONCE (memfd profile) -- or hands the engine a read-only file (file profile) + |- leleka-daemon gateway for the typed lifecycle, 127.0.0.1:18080 + |- leleka-inference engine, gRPC 127.0.0.1:18766 (started through `leleka exec-inherit`, which passes the sealed fd) + |- leleka-cli load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 -> wait for model_ready (the engine verifies shards + archive here) + `- strata-next serve public API (Responses, Chat, Messages, tools, ...), 127.0.0.1:8081, bearer key +``` + +```text +PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} PREFIX/lib/cublas/ +STATE/{leleka.json,daemon.json,strata.json,profile.json,runtime.env,api-key} STATE/{logs,run/status.json,stamps,mtp-staging} +ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/ +``` + +Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/assets`; a user gets `~/.local/share/leleka`, +`~/.local/state/leleka`, `~/.local/share/leleka/assets`. Environment: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`. +**Put `--assets` on the big volume**: about 140 GB (shards 83.6 GB + archive 55.3 GB); the first run needs that plus slack. + +### The sealed KAR archive is made by the service + +The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator +tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a +sealed memfd once (about 10 s for 55 GB from a warm cache, minutes cold), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate +to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does +**not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs. +`--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded. + +The **file profile** (laptop) cannot afford 55 GB of shmem. `leleka-inference` gained `--kar-archive-file PATH --kar-provenance PATH` +(`InheritedKarArchive::open_read_only_file`, the form `docs/laptop-profile.md` measured in a bench): the archive stays an ordinary file; +it must be regular, single-link, owned by the service user and without write bits (`up` sets mode 0400). It is weaker than the seal (immutability rests on +the file system) and is selected only by that profile. The full SHA-256 and all CRCs are still checked at load. + +## 4. Memory profiles + +`--profile auto` (default) picks by the GPU `nvidia-smi` reports; `--profile NAME` or `--profile FILE.json` overrides it, and +`--gpu-budget-gib` / `--context-tokens` override single values. `leleka profiles` lists them, `leleka profiles show NAME` prints one to copy and edit. +The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profiles/) and are embedded in the binary. + +| profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 24 GiB | 262,144 | sealed memfd (55.3 GB of RAM) | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 113 GB (58 GB when `--kar-fd` supplies the archive) | the documented bring-up configuration | +| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | optional VRAM expert tier when `ASSETS/data/expert-profile.bin` has the pinned SHA-256 `8f59b4aa...388975baf` | + +Both profiles run `--backend-mode original` and the level-2 archive; the routed-expert bank must be admitted before the Original stack opens, which `leleka-inference` now does from `--expert-source resident|mapped` (see section 10, finding 1). They select documented switches only (budget, context, archive form, the +`LELEKA_ORIGINAL_SERVE_*` environment); they are **not** tuned, not quality-gated and carry no speed claim. A GPU that fits neither +(a 24 GB 4090, say) gets an error that names the way out: write a profile file. Fields: see `crates/deploy/src/profile.rs` +(`gpu_budget_bytes`, `context_tokens`, `prefill_capacity`, `kv`, `kv_resident`, `prompt_cache`, `kar_source`, `min_*`, `engine_env` +restricted to `LELEKA_ORIGINAL_SERVE_*`); unknown fields are refused. + +One binary serves both architectures: the sealed sm_120 PTX is used as is on Blackwell, and the build with `--features sm86` +(every release) swaps in the sm_86 companion PTX on 8.6 <= cc < 12.0 cards ([`sm86-assets.md`](sm86-assets.md)). Preflight reads `MANIFEST.json` and refuses a +binary built without `sm86` on such a card. All PTX is embedded in the binaries (the release also ships the files and a `SHA256SUMS` for audit). + +## 5. Flags + +`leleka up [OPTIONS]` (also accepted by `preflight`, `status`, `down`): + +| flag | meaning | +| --- | --- | +| `--dry-run` | print preflight and plan (and the exact engine command); change nothing; exit 1 if a check fails or a step is blocked | +| `--json` | machine-readable plan / summary on stdout (logs stay on stderr) | +| `--profile auto\|NAME\|FILE` | memory profile | +| `--gpu N` | CUDA device ordinal (default 0) | +| `--assets DIR` `--state-dir DIR` `--prefix DIR` | the three roots (section 3) | +| `--bin-src DIR` | where the six binaries come from (default: the directory of `leleka`, i.e. the release `bin/`) | +| `--mode auto\|system\|user\|foreground\|none`, `--foreground` | `auto`: root with systemd -> system unit; a user with a systemd user session -> user unit; otherwise foreground. `none` prepares and starts nothing | +| `--service-user NAME` | system unit only: the account the service runs as (default `leleka`, created with `useradd --system`; state and assets are chowned to it) | +| `--api-port` `--engine-port` `--daemon-port` | ports (defaults 8081, 18766, 18080) | +| `--api-bind IP` | API listen address, default `127.0.0.1`; `0.0.0.0` only inside a container whose port is published to the host's loopback or tunnelled (the bearer key is the only protection, no TLS). The engine and gateway are always loopback | +| `--gpu-budget-gib N` `--context-tokens N` | override one profile value | +| `--no-fetch` | never download or build; require verified files to exist | +| `--reverify` | ignore the stamps and hash everything again | +| `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) | +| `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) | +| `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it | +| `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) | +| `--timeout-s N` | wait this long for `/ready` (default 3600) | + +Other commands: `leleka preflight` (checks only, exit 1 on FAIL), `leleka status` (cheap: no GPU probe; exit 0 only when ready; this is the container health check), +`leleka down` (stop the systemd unit), `leleka run --config STATE/leleka.json [--kar-fd N]` (the supervisor), `leleka profiles [show NAME]`. +`HF_TOKEN` in the environment is used only by `model fetch`, is sent only to `https://huggingface.co`, is removed from every child the supervisor starts, and is never printed or written. + +## 6. Operating it + +* systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has + `Restart=on-failure` with `RestartSec=30`, at most 3 starts in 30 minutes, and no restart after exit code 2 (configuration), because every start re-reads 55 GB. +* The supervisor restarts a dead engine up to twice (counter reset after 10 ready minutes) with the same sealed descriptor and loads the model again; the API process stays up and + answers not-ready meanwhile. A dead gateway (3) or API (5) is restarted too. Then it exits 1 and systemd decides. +* `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace. +* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log` (rotated once past 64 MiB at start). Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed). +* Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`. + Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md). + +## 7. Container image + +[`deploy/Containerfile.rust-runtime`](../deploy/Containerfile.rust-runtime): Ubuntu 24.04 (glibc 2.39, the floor of the binaries) + the six binaries + cuBLAS 12.9.1.4 +(downloaded by BuildKit with `ADD --checksum`, only `libcublas.so.12*` and `libcublasLt.so.12*` kept) + the manifest/provenance. The sealed PTX is inside the binaries; `ldd` shows only libc, libm +and libgcc_s, and the engine `dlopen`s `libcuda.so.1` (injected by the NVIDIA Container Toolkit) and `libcublas.so.12`. Not in the image, by design: the model, the driver, any secret. Non-root (uid 10001), volumes `/models` and `/state`, +`HEALTHCHECK` = `leleka status`. + +```sh +tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64 +docker build -f /path/to/repo/deploy/Containerfile.rust-runtime --build-arg VERSION=VERSION -t leleka-runtime:VERSION . +# pin the base for a release: docker buildx imagetools inspect ubuntu:24.04 then --build-arg BASE=ubuntu:24.04@sha256:... + +docker run -d --name leleka --gpus all --restart unless-stopped \ + -v /data/leleka-models:/models -v leleka-state:/state -p 127.0.0.1:8081:8081 \ + leleka-runtime:VERSION # default command: up --foreground --no-install-cublas --api-bind 0.0.0.0 +docker logs -f leleka # first start: hours (download, verification, archive build); later starts: minutes +docker exec leleka cat /state/api-key +``` + +The memfd profile needs the host to give the container ~60 GB of RAM (no `--memory` below that; memfd is shmem charged to the container, not limited by `--shm-size`). Docker's default seccomp +profile allows `memfd_create`. Build is not run in CI; see section 10 for what was checked. + +## 8. Build a release tarball + +On Linux/WSL, from a tree with the toolchain pinned by `rust-toolchain.toml` (no CUDA toolkit is needed; the PTX is checked in): + +```sh +cargo build --release --locked -p strata-desktop-core --features sm86 \ + --bin leleka-inference --bin leleka-daemon --bin leleka-cli --bin leleka-seal-exec +cargo build --release --locked -p strata-control --bin strata-next +cargo build --release --locked -p leleka-deploy --bin leleka + +# provenance is made where git exists (an exported tree has no .git); the tree must be clean or --allow-dirty marks it +python3 scripts/package-release.py provenance --repo . --out provenance.json +python3 scripts/package-release.py package --repo . --target-dir target --provenance provenance.json --out dist +``` + +`dist/leleka-VERSION-COMMIT12-linux-x86_64.tar.xz` (+ `.sha256`) contains `bin/` (six binaries), `share/leleka/ptx/{sm_120,sm_86}` (the sealed PTX and `SHA256SUMS`), `share/leleka/{profiles,templates,docs}`, +`MANIFEST.json` (version, commit, `features`, SHA-256 of every binary, rustc/glibc of the builder), `PROVENANCE.json`, `SHA256SUMS` for every file, and `install.sh`. `--no-ptx` omits the PTX files (they are embedded anyway); +`--with-cublas DIR` bundles cuBLAS (NVIDIA's redistribution terms apply). +`PROVENANCE.json` records the git commit, whether the tree was dirty (and a digest of the diff), the `Cargo.lock` digest, and for `engine/strata`: the upstream URL and commit from [`upstream.md`](upstream.md), +the subtree tree id, the import commit, every later commit touching the subtree, and the diff since import (shortstat + digest). The diff against the upstream tree itself is computed only when the upstream commit is present +in the repository (`git fetch strata-upstream`); otherwise the record says so. `engine/strata` is not modified by this work. + +## 9. Troubleshooting + +| message (preflight / run) | cause and fix | +| --- | --- | +| `NVIDIA GPU: nvidia-smi was not found` | no driver. Linux: install the NVIDIA driver >= 595. WSL2: install the Windows driver (never a Linux driver inside WSL), `wsl --shutdown`, retry | +| `driver version: 580.x is older than 595` | the sealed PTX needs ISA 9.2 (CUDA 13.2): update the driver | +| `GPU memory: N MiB free but the engine needs M MiB` | another process holds VRAM (`nvidia-smi`); stop it or lower `--gpu-budget-gib` | +| `architecture: ... built WITHOUT the sm86 feature` | an RTX 30-series card needs a release made with `--features sm86` | +| `memory: ... available is below ...` | the sealed archive copy needs the whole 55 GB in RAM. Free memory, or use the file profile if the GPU fits it. On WSL2 put `[wsl2] memory=32GB swap=8GB` in `%UserProfile%\.wslconfig` and `wsl --shutdown` | +| `WSL2 file system: ... is on a Windows/network mount` | `/mnt/c` is 9p: far too slow for mapped reads. Use a path on the WSL ext4 disk | +| `cuBLAS 12: libcublas.so.12 ... not found` | let `up` download the pinned 12.9.1.4 (needs curl or wget, tar, xz), or `--cublas-dir DIR`, or `apt install libcublas12` | +| `disk space: assets ...: N GiB free, M needed` | nothing was downloaded yet; point `--assets` at a larger volume | +| `loopback ports: already in use` | another listener; `--api-port` / `--engine-port` / `--daemon-port` | +| `permission denied` on `/dev/nvidia*` in the system unit | the device nodes are not world-accessible: add the service user to the `video` (or `render`) group and restart the unit | +| `systemd: not running` | WSL2 without systemd or a container: `--foreground`, or enable systemd in `/etc/wsl.conf` | +| `step mtp-pack is blocked` | the MTP pack has no automated producer yet; copy `data/mtp-rt` from a machine that has it (`--mtp-pack` takes a directory or tarball) | +| `... has N bytes but the engine only admits the pinned 55295529472-byte level-2 archive` | the archive was built with another level or policy; the engine would refuse it. Rebuild with `--levels 2` | +| `step model failed: ... 401/403` | the repository needs a token: `export HF_TOKEN=...` (sent only to huggingface.co) | +| `load-mtp was refused` | read `STATE/logs/engine.log` (the engine prints a fixed code, never a path or a secret) | +| `the model was not ready within 1800 s` | the engine verifies 84 GB of shards and 55 GB of archive at load; a cold disk can need longer: raise `load_timeout_s` in `STATE/leleka.json` | +| a stale `Another supervisor is running for ...` | `leleka down` (systemd) or stop the other process; `STATE/run/status.json` names its pid | + +## 10. What was run and what was not + +All of this is bring-up evidence, not a performance or quality result: no paired A/B, one request, no token statistics beyond what is quoted. + +### Findings that the real run produced + +1. **The production `Load` of the Original path could not succeed.** `leleka-inference ... --backend-mode original` never admitted a routed-expert bank + (the serve smokes call `load_resident_expert_source()` themselves; `backend.rs` did that only for the `--experimental-optimized-*` modes), so the first real `load-mtp` + through the daemon failed in `OriginalServeStack::open` with `MoeWeightCache::new_original_prompt_arena: InputRead` (`leleka-load phase=OriginalStack class=BackendUnavailable` in + `engine.log`) and the engine process stayed up. Fixed here: `OriginalServeOptions.expert_source` and `--expert-source resident|mapped` (default `resident`, the smoke form); + `backend.rs` admits the chosen bank before the driver, as it does for the optimized modes. The profile files select `resident` (server) and `mapped` (laptop). +2. **The supervisor waited out the load timeout for a refused load.** The engine does not exit on a failed load; `leleka` now reads the operation record + (`leleka-cli operation`, state FAILED/INDETERMINATE) and stops with the last lines of `engine.log`. +3. `leleka-inference` had no way to take the archive as a read-only file (only the 55 GB sealed memfd); `--kar-archive-file` is new and was exercised on the laptop. + +### Real runs + +| where | what | result | +| --- | --- | --- | +| WSL2 laptop, RTX 3080 Laptop 16 GB, driver 617.42, Ubuntu 24.04 with systemd, RAM 40 GB (`.wslconfig`) | `leleka up` from the unpacked release (commit `e03d97d`, 30.7 MB tarball, sm86 build), user unit, real shards and archive (copied to the WSL ext4 disk), profile `rtx3080-16g` chosen by `auto` | preflight 13 ok / 1 warning (cuBLAS missing); cuBLAS 12.9.1.4 unpacked from the pinned archive (SHA-256 checked; **the download itself was not exercised**: the archive was placed in `PREFIX/lib` beforehand); fetch + verify of the real shards about 3 min (hash reuse, no download); tokens, configs, tokenizer, `systemctl --user enable/start`; **model loaded in 198 s, `/ready` 200**; one `POST /v1/responses` (59 input tokens, 16 output tokens, 21.4 s wall, stopped by `max_output_tokens`, text is the model's reasoning preamble) | +| same | peak during that request | VRAM 13,971 MiB; engine RSS 26.4 GB (anon 2.6, file-backed 19.9, shmem 4.0); the engine log shows 3,133 VRAM expert slots (the expert tier was on because `expert-profile.bin` had the pinned digest) | +| same | idempotence | a second `up` against the running service: 0.27 s, same systemd `MainPID`, every step `done`; `leleka down`: 1.9 s, no process left, VRAM back to 0 | +| same | engine killed with `kill -9` | phase `engine_restarting`, `/ready` false, the engine restarted and reloaded: ready again 293 s after the kill (load 286 s), restart counter 1, gateway and API processes unchanged, one request served afterwards | +| RTX 5090 server (Ubuntu 26.04, driver 595.99.02, 121 GB RAM) | `leleka up --dry-run` with the real assets and the real preflight | 12 checks ok; the plan names the exact engine command; nothing created. The real-model jobs `930-deploy-prepare.sh` and `931-deploy-serve.sh` are in the holder queue (they inherit the holder's sealed descriptor with `--kar-fd`); see "Server job" below for their state | + +### Tests (no GPU, no model) + +* `cargo test -p leleka-deploy --features test-fakes` (71 unit, 11 end-to-end, 4 recipe tests, all passing in WSL): unit tests (profiles, facts parsers, preflight on synthetic hosts - server, laptop under default WSL2 memory, old driver, busy GPU, + no cuBLAS, full disk, `/mnt/c`, no systemd -, plan, units, CLI, sealed memfd, stamps, HTTP), `tests/e2e.rs` against a test double of the five programs + (supervisor lifecycle with an inherited sealed descriptor and with a read-only file: ready, SIGKILL of the engine -> restart with API/gateway unchanged -> SIGTERM drain with every child gone; + an engine that cannot start; a refused load fails fast; weak tokens are exit code 2; `up` is idempotent, resumable after a deleted archive, never rotates secrets, `--trust-archive`, wrong-size archive refused; + `--dry-run` creates nothing; a failing preflight changes nothing), `tests/recipe.rs` (the Containerfile is non-root, has a health check, copies no model or secret; the cuBLAS pin agrees in three places; `install.sh` verifies before it runs). + `cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` are clean. +* `cargo test -p strata-desktop-core --bin leleka-inference` (14 argument-parsing tests, including `--kar-archive-file` and `--expert-source`). +* Linux only for the process tests; the portable parts also run on Windows (`cargo test -p leleka-deploy`), where the POSIX-path tests are not meaningful. + +### Not done / open + +* **No container image was built.** Docker Desktop on this laptop does not start: its backend aborts on stale `AF_UNIX` socket files (`%LOCALAPPDATA%\Docker un\dockerInference`, + `userAnalyticsOtlpHttp.sock`, dated 2025-06) that Windows refuses to delete without elevation (`Error 1920`). The recipe is checked statically (`tests/recipe.rs`) and by simulation: the `COPY` layout + rebuilt under `/opt/leleka` in WSL, `env -i`, the container's environment variables: `ldd` resolves every library from the base alone (libc, libm, libgcc_s), `libcublas.so.12` is found in + `PREFIX/lib/cublas`, `leleka status` answers in 2 ms; the content is 167 MB of binaries + 815 MB of cuBLAS = 982 MB before the Ubuntu base layer (no image digest exists). + Build it on a machine with a working engine (section 7) and record the digest and size. +* The **system-scope** unit (`useradd`, chown of state and assets, `/etc/systemd/system`) and the `curl` branch of the cuBLAS download have unit tests / renders but were not run for real. +* No clean Ubuntu 24.04 / 26.04 VM was installed from nothing; the first-ever archive build (`ensure-sharded-streamed` creating 55 GB) was not repeated. +* The MTP pack has no producer in the repository (`mtp_pack`); `up` needs it in `ASSETS/data/mtp-rt` or via `--mtp-pack`. +* Not measured: the load time of the server profile under the supervisor, the RAM peak of 55 GB memfd + 50 GB bank, anything about throughput. +* Native Windows is not a target. TLS and remote access are not part of this: use an SSH tunnel. + +### Server job (RTX 5090) + +Two holder jobs are queued on `rnr5090` (`~/work/gpu-runs/holder2/jobs/`), written to run after each other and to inherit the holder's sealed descriptor, so nothing is copied or downloaded: + +* `930-deploy-prepare.sh`: `up --dry-run`, then `up --mode none --kar-fd $LELEKA_STRA169_KAR_FD --trust-archive` against `~/leleka-gates/assets` (real `model fetch`/`verify` of the existing shards by hash reuse, + tokens, configs, tokenizer extraction into `assets/tokenizer-assets`), then a second dry-run and a second `up` to show that nothing is redone. +* `931-deploy-serve.sh`: `up --foreground --kar-fd ...` with the real model (typed load, `/ready`), one request through the API, an unauthenticated request (must be refused), SIGTERM, the logs and a check that no process is left. + +The release is unpacked at `~/work/deploy-run/rel`, state is `~/work/deploy-run/state`. At the time of writing the holder was busy with earlier queue entries (the holder takes a snapshot of the job list per pass, so entries added later run in the next pass), so +**these two jobs had not run**; read `930-deploy-prepare.log` and `931-deploy-serve.log` next to the scripts. The strict re-verification of the existing archive (`ensure-sharded-streamed` without `--trust-archive`) was deliberately not queued: +it re-derives the 708 GB virtual F32 stream (the analysis tool was stopped after 13 minutes at the same step, `build-validation.md`). diff --git a/docs/rust-runtime-run.md b/docs/rust-runtime-run.md index 8a416dd6..d8d225ec 100644 --- a/docs/rust-runtime-run.md +++ b/docs/rust-runtime-run.md @@ -5,6 +5,10 @@ against the model assets, and what was and was not executed to check it. **No mo was involved in any check on this page**; it makes no performance or quality claim. The model-facing steps (`load-mtp`, a real `/v1/responses`) belong to the GPU bring-up and are written down here from the code, not from a run. +> **One command instead of the manual steps below:** `leleka up` ([`deploy.md`](deploy.md)) preflights the host, fetches and verifies the +> model, builds the archive, installs, creates the sealed KAR descriptor itself (no `kar_holder.py`), loads the model and waits for readiness. +> This page stays the reference for what each process does. + ## Processes ```text diff --git a/scripts/package-release.py b/scripts/package-release.py new file mode 100755 index 00000000..88fc0ab7 --- /dev/null +++ b/scripts/package-release.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Assemble the Leleka release tarball (offline build tooling; production serving has no Python dependency). + +Inputs: a release build of the seven binaries (`cargo build --release --locked ...`, see docs/deploy.md), the +repository tree (for templates, sealed PTX and docs) and a provenance record. Output, in --out: + + leleka-VERSION-COMMIT12-linux-x86_64.tar.xz bin/ share/ MANIFEST.json PROVENANCE.json SHA256SUMS install.sh + leleka-VERSION-COMMIT12-linux-x86_64.tar.xz.sha256 + +The provenance record names the git commit, whether the tree was clean, and the local changes to the imported +Strata source relative to the upstream commit in docs/upstream.md. Builds happen in WSL/Linux from an exported tree +(no .git there), so the record is produced where git exists: + + python3 scripts/package-release.py provenance --repo . --out provenance.json + python3 scripts/package-release.py package --repo . --target-dir ~/target --provenance provenance.json --out dist + +`package` alone also works inside a git checkout (it computes the provenance itself). Nothing here downloads +anything; cuBLAS is not bundled (the NVIDIA redistributable is fetched by `leleka up`, or add --with-cublas DIR). +""" +import argparse +import datetime +import hashlib +import io +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tarfile + +RUNTIME_BINARIES = ['leleka', 'strata-next', 'leleka-inference', 'leleka-daemon', 'leleka-cli', 'leleka-seal-exec'] +TEMPLATES = [ + 'deploy/rust-runtime/leleka-daemon.service', + 'deploy/rust-runtime/leleka-inference.service', + 'deploy/rust-runtime/runtime.env.example', +] +UPSTREAM_DOC = 'docs/upstream.md' +SUBTREE = 'engine/strata' + + +def run(args, cwd=None, check=True): + result = subprocess.run([str(a) for a in args], cwd=cwd, capture_output=True, text=True) + if check and result.returncode != 0: + raise RuntimeError(f'{" ".join(map(str, args))} failed: {result.stderr.strip()}') + return result.stdout.strip() + + +def sha256(path): + digest = hashlib.sha256() + with open(path, 'rb') as source: + for chunk in iter(lambda: source.read(1 << 20), b''): + digest.update(chunk) + return digest.hexdigest() + + +def upstream_record(repo): + text = (repo / UPSTREAM_DOC).read_text(encoding='utf-8') + url = re.search(r'Upstream repository URL \| (\S+)', text) + sha = re.search(r'Upstream commit SHA \| `([0-9a-f]{40})`', text) + if not url or not sha: + raise RuntimeError(f'{UPSTREAM_DOC} does not name the upstream repository and commit') + return url.group(1), sha.group(1) + + +def provenance(repo, allow_dirty=False): + """Git commit, cleanliness, and the local changes to engine/strata relative to the recorded upstream commit.""" + url, upstream_sha = upstream_record(repo) + commit = run(['git', '-C', repo, 'rev-parse', 'HEAD']) + status = run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=normal']) + dirty_files = [line for line in status.splitlines() if line] + # Windows checkouts report CRLF-only differences as modified; hash what git would actually record. + diff_digest = hashlib.sha256(run(['git', '-C', repo, 'diff', 'HEAD', '--binary'], check=False).encode()).hexdigest() if dirty_files else None + if dirty_files and not allow_dirty: + raise RuntimeError(f'the tree has {len(dirty_files)} uncommitted change(s); commit them or pass --allow-dirty (the release is then marked dirty)') + # Import commit(s): the first commit that touched the subtree. + history = run(['git', '-C', repo, 'log', '--format=%H %s', '--reverse', '--', SUBTREE]).splitlines() + import_commit = history[0].split(' ', 1)[0] if history else None + subtree_tree = run(['git', '-C', repo, 'rev-parse', f'HEAD:{SUBTREE}']) + record = { + 'schema_version': 1, + 'git_commit': commit, + 'git_describe': run(['git', '-C', repo, 'describe', '--always', '--dirty', '--abbrev=12'], check=False), + 'git_branch': run(['git', '-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], check=False), + 'dirty': bool(dirty_files), + 'dirty_file_count': len(dirty_files), + 'dirty_diff_sha256': diff_digest, + 'cargo_lock_sha256': sha256(repo / 'Cargo.lock'), + 'strata': { + 'upstream_url': url, + 'upstream_commit': upstream_sha, + 'subtree_path': SUBTREE, + 'subtree_tree_at_head': subtree_tree, + 'import_commit': import_commit, + 'commits_touching_subtree': len(history), + 'local_patch_commits': [line.split(' ', 1) for line in history[1:]][:200], + }, + } + # Local changes since the import (the committed ones), and against the upstream tree when it is present. + if import_commit: + stat = run(['git', '-C', repo, 'diff', '--shortstat', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False) + diff = run(['git', '-C', repo, 'diff', '--binary', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False) + record['strata']['diff_since_import'] = { + 'shortstat': stat or 'no change', + 'diff_sha256': hashlib.sha256(diff.encode()).hexdigest(), + } + have_upstream = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', f'{upstream_sha}^{{commit}}'], capture_output=True).returncode == 0 + if have_upstream: + upstream_tree = run(['git', '-C', repo, 'rev-parse', f'{upstream_sha}^{{tree}}']) + record['strata']['diff_vs_upstream'] = { + 'upstream_tree': upstream_tree, + 'shortstat': run(['git', '-C', repo, 'diff', '--shortstat', upstream_tree, f'HEAD:{SUBTREE}'], check=False) or 'identical', + } + else: + record['strata']['diff_vs_upstream'] = { + 'available': False, + 'why': f'the upstream commit {upstream_sha} is not in this repository (fetch the strata-upstream remote to compare)', + } + return record + + +def version_of(repo): + text = (repo / 'crates/deploy/Cargo.toml').read_text(encoding='utf-8') + return re.search(r'^version = "([^"]+)"', text, re.M).group(1) + + +def tool_version(*args): + return run(args, check=False).splitlines()[0] if run(args, check=False) else None + + +def add_tree(tar, source_dir, arc_prefix, epoch): + for path in sorted(source_dir.rglob('*')): + if path.is_file(): + add_file(tar, path, f'{arc_prefix}/{path.relative_to(source_dir).as_posix()}', epoch, executable=os.access(path, os.X_OK)) + + +def add_file(tar, path, name, epoch, executable=False, data=None): + info = tarfile.TarInfo(name) + payload = data if data is not None else path.read_bytes() + info.size = len(payload) + info.mtime = epoch + info.mode = 0o755 if executable else 0o644 + info.uid = info.gid = 0 + info.uname = info.gname = 'root' + tar.addfile(info, io.BytesIO(payload)) + + +def package(args): + repo = Path(args.repo).resolve() + target = Path(args.target_dir).expanduser().resolve() / 'release' + out = Path(args.out).resolve() + out.mkdir(parents=True, exist_ok=True) + if args.provenance: + record = json.loads(Path(args.provenance).read_text(encoding='utf-8')) + else: + record = provenance(repo, args.allow_dirty) + if record.get('dirty') and not args.allow_dirty: + raise RuntimeError('the provenance record says the tree was dirty; pass --allow-dirty to package it anyway (the manifest keeps the mark)') + commit = record['git_commit'] + version = args.version or version_of(repo) + features = sorted(set(args.feature or ['sm86'])) + name = f'leleka-{version}-{commit[:12]}-linux-x86_64' + epoch = int(os.environ.get('SOURCE_DATE_EPOCH', datetime.datetime.now(datetime.timezone.utc).timestamp())) + + members = {} # archive path -> (bytes, executable) + binaries = {} + for binary in RUNTIME_BINARIES: + path = target / binary + if not path.is_file(): + raise RuntimeError(f'{path} is missing; build it first (docs/deploy.md, "Build a release")') + data = path.read_bytes() + members[f'bin/{binary}'] = (data, True) + binaries[binary] = hashlib.sha256(data).hexdigest() + for template in TEMPLATES: + members[f'share/leleka/templates/{Path(template).name}'] = ((repo / template).read_bytes(), False) + for profile in sorted((repo / 'deploy/rust-runtime/profiles').glob('*.json')): + members[f'share/leleka/profiles/{profile.name}'] = (profile.read_bytes(), False) + for doc in ['docs/deploy.md', 'docs/upstream.md', 'docs/rust-runtime-run.md', 'docs/laptop-profile.md', 'docs/sm86-assets.md']: + if (repo / doc).is_file(): + members[f'share/leleka/docs/{Path(doc).name}'] = ((repo / doc).read_bytes(), False) + members['install.sh'] = ((repo / 'deploy/rust-runtime/install.sh').read_bytes(), True) + + ptx_lines = [] + if not args.no_ptx: + sets = {'sm_120': [p for p in (repo / 'crates/cuda-driver').rglob('*.ptx') if 'ptx-sm86' not in p.parts], + 'sm_86': sorted((repo / 'crates/cuda-driver/ptx-sm86').glob('*.ptx'))} + for arch, files in sets.items(): + for path in sorted(files): + data = path.read_bytes() + members[f'share/leleka/ptx/{arch}/{path.name}'] = (data, False) + ptx_lines.append(f'{hashlib.sha256(data).hexdigest()} {arch}/{path.name}') + if (repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').is_file(): + members['share/leleka/ptx/sm_86-MANIFEST.json'] = ((repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').read_bytes(), False) + members['share/leleka/ptx/SHA256SUMS'] = (('\n'.join(ptx_lines) + '\n').encode(), False) + + if args.with_cublas: + for path in sorted(Path(args.with_cublas).glob('libcublas*.so*')): + members[f'lib/cublas/{path.name}'] = (path.read_bytes(), False) + + manifest = { + 'schema_version': 1, + 'name': 'leleka', + 'version': version, + 'git_commit': commit, + 'dirty': bool(record.get('dirty')), + 'features': features, + 'binaries': binaries, + 'built_with': { + 'rustc': tool_version('rustc', '--version'), + 'cargo': tool_version('cargo', '--version'), + 'host': tool_version('uname', '-sr'), + 'glibc': tool_version('ldd', '--version'), + }, + 'runtime_requirements': { + 'os': 'linux x86_64, glibc', + 'nvidia_driver_min': 595, + 'cublas': 'libcublas.so.12 and libcublasLt.so.12 (CUDA 12; pinned redistributable 12.9.1.4 is fetched by `leleka up`)' if not args.with_cublas else 'bundled in lib/cublas (CUDA 12.9.1.4 redistributable, NVIDIA license applies)', + 'gpu_architectures': ['sm_120'] + (['sm_86..sm_119 (companion PTX, feature sm86)'] if 'sm86' in features else []), + }, + 'ptx_included': not args.no_ptx, + 'created_utc': datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), + } + members['MANIFEST.json'] = ((json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode(), False) + members['PROVENANCE.json'] = ((json.dumps(record, indent=2, sort_keys=True) + '\n').encode(), False) + sums = ''.join(f'{hashlib.sha256(data).hexdigest()} {path}\n' for path, (data, _) in sorted(members.items())) + members['SHA256SUMS'] = (sums.encode(), False) + + tarball = out / f'{name}.tar' + with tarfile.open(tarball, 'w', format=tarfile.PAX_FORMAT) as tar: + for path, (data, executable) in sorted(members.items()): + add_file(tar, None, f'{name}/{path}', epoch, executable, data) + compressed = out / f'{name}.tar.xz' + import lzma + with open(tarball, 'rb') as source, lzma.open(compressed, 'wb', preset=6) as target_file: + shutil.copyfileobj(source, target_file) + tarball.unlink() + digest = sha256(compressed) + (out / f'{name}.tar.xz.sha256').write_text(f'{digest} {compressed.name}\n', encoding='ascii') + + # Verify what was written: the member list matches SHA256SUMS byte for byte. + with tarfile.open(compressed, 'r:xz') as tar: + names = {m.name for m in tar.getmembers() if m.isfile()} + sums_member = tar.extractfile(f'{name}/SHA256SUMS').read().decode() + for line in sums_member.splitlines(): + expected, rel = line.split(' ', 1) + actual = hashlib.sha256(tar.extractfile(f'{name}/{rel}').read()).hexdigest() + if actual != expected: + raise RuntimeError(f'verification failed for {rel}') + assert names == {f'{name}/{p}' for p in members} + print(json.dumps({'tarball': str(compressed), 'sha256': digest, 'bytes': compressed.stat().st_size, 'files': len(members), 'git_commit': commit, 'dirty': manifest['dirty'], 'features': features}, indent=2)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest='command', required=True) + prov = sub.add_parser('provenance', help='write the provenance record of a git checkout') + prov.add_argument('--repo', default='.') + prov.add_argument('--out', required=True) + prov.add_argument('--allow-dirty', action='store_true') + pack = sub.add_parser('package', help='assemble the tarball') + pack.add_argument('--repo', default='.') + pack.add_argument('--target-dir', required=True, help='cargo target dir that holds release/') + pack.add_argument('--out', default='dist') + pack.add_argument('--provenance', help='record made by the `provenance` command (needed when the tree has no .git)') + pack.add_argument('--version') + pack.add_argument('--feature', action='append', help='Cargo feature the runtime binaries were built with (repeatable; default: sm86)') + pack.add_argument('--allow-dirty', action='store_true') + pack.add_argument('--no-ptx', action='store_true', help='omit the sealed PTX files (they are embedded in the binaries anyway)') + pack.add_argument('--with-cublas', help='directory with libcublas.so.12* / libcublasLt.so.12* to bundle') + args = parser.parse_args() + try: + if args.command == 'provenance': + record = provenance(Path(args.repo).resolve(), args.allow_dirty) + Path(args.out).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n', encoding='utf-8') + print(f'wrote {args.out}: {record["git_commit"]} dirty={record["dirty"]}') + else: + package(args) + except (RuntimeError, OSError) as error: + print(f'package-release: {error}', file=sys.stderr) + sys.exit(1) + + +if __name__ == '__main__': + main()