diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index bf38af1a..327a9c07 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -103,6 +103,7 @@ pub async fn main_native(mut args: Vec) -> i32 { Command::Run { config, kar_fd } => { supervisor::run(supervisor::Options { config, kar_fd }).await } + Command::SealProbe(file) => seal_probe(&file), Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { Ok(never) => match never {}, Err(message) => { @@ -113,6 +114,65 @@ pub async fn main_native(mut args: Vec) -> i32 { } } +/// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the file. +#[cfg(unix)] +fn seal_probe(file: &std::path::Path) -> i32 { + use sha2::{Digest, Sha256}; + use std::os::unix::fs::FileExt; + let started = std::time::Instant::now(); + let (memfd, _identity, report) = match crate::sealed::seal_file_report(file, None, &mut |done, total| { + eprintln!("sealing: {:.1} of {:.1} GiB", done as f64 / 1073741824.0, total as f64 / 1073741824.0); + }) { + Ok(done) => done, + Err(message) => { + eprintln!("leleka seal-probe: {message}"); + return 1; + } + }; + let sealed_s = started.elapsed().as_secs_f64(); + let length = memfd.metadata().map_or(0, |m| m.len()); + let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new()); + let source = match std::fs::File::open(file) { + Ok(f) => f, + Err(error) => { + eprintln!("leleka seal-probe: {error}"); + return 1; + } + }; + let mut block = vec![0u8; 8 << 20]; + let mut other = vec![0u8; 8 << 20]; + let mut offset = 0u64; + while offset < length { + let n = (length - offset).min(block.len() as u64) as usize; + if memfd.read_exact_at(&mut block[..n], offset).is_err() || source.read_exact_at(&mut other[..n], offset).is_err() { + eprintln!("leleka seal-probe: read failed at {offset}"); + return 1; + } + from_memfd.update(&block[..n]); + from_file.update(&other[..n]); + offset += n as u64; + } + let (a, b) = (hex::encode(from_memfd.finalize()), hex::encode(from_file.finalize())); + println!( + "seal-probe {} bytes {} read={} sealed in {:.1} s ({:.0} MB/s) sha256(memfd)={} sha256(file)={} {}", + file.display(), + length, + report.strategy.as_str(), + sealed_s, + length as f64 / sealed_s.max(1e-9) / 1e6, + a, + b, + if a == b { "IDENTICAL" } else { "DIFFERENT" } + ); + i32::from(a != b) +} + +#[cfg(not(unix))] +fn seal_probe(_file: &std::path::Path) -> i32 { + eprintln!("leleka seal-probe needs Linux"); + 2 +} + fn print_report(report: &Report) { eprint!("{}", report.render()); } @@ -445,18 +505,7 @@ pub fn print_status( println!("systemd unit {name}: {state}"); } match supervisor { - 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("") - ), + Some(s) => print!("{}", render_supervisor(&s, unix_now())), None => println!("supervisor: no status file in {run_dir} (never started?)"), } if let Some(machine) = &machine { @@ -468,6 +517,65 @@ pub fn print_status( i32::from(!ready) } +fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +fn duration_text(seconds: u64) -> String { + match seconds { + s if s < 120 => format!("{s} s"), + s if s < 7200 => format!("{} min", s / 60), + s if s < 172_800 => format!("{} h {:02} min", s / 3600, s % 3600 / 60), + s => format!("{} days {} h", s / 86_400, s % 86_400 / 3600), + } +} + +/// The supervisor part of `leleka status`: what it does, for how long, what it restarted and why, whether it is alive. +pub fn render_supervisor(s: &Value, now: u64) -> String { + let updated = s["updated_unix"].as_u64().unwrap_or(0); + let age = now.saturating_sub(updated); + let mut out = format!( + "supervisor: phase {} (pid {}), updated {} ({} ago)\n {}\n", + s["phase"].as_str().unwrap_or("?"), + s["supervisor_pid"], + supervisor::format_utc(updated), + duration_text(age), + s["message"].as_str().unwrap_or("") + ); + // The supervisor rewrites its status at least every 30 s while it lives. + let live = !matches!(s["phase"].as_str(), Some("stopped" | "failed")); + if live && age > 120 { + out.push_str(&format!( + " WARNING: the status is {} old although the phase is {}: the supervisor is not running (crashed or killed)\n", + duration_text(age), + s["phase"].as_str().unwrap_or("?") + )); + } + if let Some(started) = s["started_unix"].as_u64() { + out.push_str(&format!(" up {}", duration_text(now.saturating_sub(started)))); + out.push_str(&format!( + ", engine restarts {} in total ({} in a row)", + s["restarts_total"].as_u64().unwrap_or(0), + s["engine_restarts"].as_u64().unwrap_or(0) + )); + if let (Some(at), Some(why)) = (s["last_restart_unix"].as_u64(), s["last_restart_reason"].as_str()) { + out.push_str(&format!("\n last restart {} ago: {why}", duration_text(now.saturating_sub(at)))); + } + out.push('\n'); + } else { + out.push_str(&format!(" engine restarts {}\n", s["engine_restarts"])); + } + if let Some(health) = s["health"].as_str() { + out.push_str(&format!( + " health: {health}; logs {} MiB\n", + s["log_bytes"].as_u64().unwrap_or(0) >> 20 + )); + } + out +} + /// `leleka reconfigure`. /// /// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A @@ -732,8 +840,103 @@ pub fn render_machine(machine: &Value) -> String { /// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the /// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. +/// `leleka verify --quick`: the health of the installation without reading the model. Reports, from what is on disk and what the +/// service says: whether each model file is stamped as verified in its present state (a stamped file is not hashed again at a start), +/// whether the service runs and answers, how old and how restarted it is, and how big the logs are. Exit 0 only when all is well. +async fn verify_quick(opts: &UpOptions) -> i32 { + use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; + let paths = opts.dirs.paths(); + let config = match crate::config::RunConfig::read(&paths.run_config()) { + Ok(config) => config, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + let stamps = VerifyStamps::new(paths.engine_stamps(), false); + let mut problems: Vec = Vec::new(); + let mut notes: Vec = Vec::new(); + let decode = |hex_text: &str| { + let mut out = [0u8; 32]; + hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out) + }; + let identity_of = |path: &std::path::Path| std::fs::File::open(path).and_then(|f| f.metadata()).ok().and_then(|m| FileIdentity::of(&m)); + println!("model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):"); + for index in 0..2 { + let path = paths.shard(index); + let state = match (decode(crate::profile::SHARD_SHA256_HEX[index]), identity_of(&path)) { + (_, None) => { + problems.push(format!("shard {index} is missing: {}", path.display())); + "MISSING" + } + (Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => "stamped (verified in its present state)", + _ => { + notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp")); + "not stamped" + } + }; + println!(" shard {index}: {state} {}", path.display()); + } + let kar = paths.kar(); + let kar_state = match identity_of(&kar) { + None => { + problems.push(format!("the archive is missing: {}", kar.display())); + "MISSING".to_owned() + } + Some(id) if id.size != crate::profile::ARCHIVE_BYTES => { + problems.push(format!("the archive has {} bytes, the pinned archive {}", id.size, crate::profile::ARCHIVE_BYTES)); + "WRONG SIZE".to_owned() + } + Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => "stamped (verified in its present state)".to_owned(), + Some(_) => { + notes.push("the archive is not stamped: the next start of the engine hashes the sealed copy (about a minute)".into()); + "not stamped".to_owned() + } + }; + println!(" archive: {kar_state} {}", kar.display()); + let api = config.ports.api.clone(); + let supervisor: Option = std::fs::read_to_string(paths.status_file()).ok().and_then(|t| serde_json::from_str(&t).ok()); + let ready = steps::probe_ready_at(&paths, &api).await; + println!("service:"); + match &supervisor { + Some(s) => print!(" {}", render_supervisor(s, unix_now()).replace('\n', "\n ").trim_end_matches(' ')), + None => println!(" no status file in {} (the service has not run)", paths.run_dir().display()), + } + println!(" API answers /ready: {}", if ready { "yes" } else { "NO" }); + if !ready { + problems.push("the API does not answer /ready".into()); + } + if let Some(s) = &supervisor { + let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0)); + if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) { + problems.push(format!("the supervisor's status is {age} s old: it is not running")); + } + if s["phase"].as_str() == Some("failed") { + problems.push(format!("the supervisor failed: {}", s["message"].as_str().unwrap_or(""))); + } + } + let log_bytes = crate::logs::total_bytes(&paths.logs()); + println!(" logs: {} MiB in {} (rotated at {} MiB per file, {} generations)", log_bytes >> 20, paths.logs().display(), config.logs.limit_mib, config.logs.keep); + for note in ¬es { + println!("note: {note}"); + } + if problems.is_empty() { + println!("health: OK"); + 0 + } else { + for problem in &problems { + println!("PROBLEM: {problem}"); + } + println!("health: NOT OK"); + 1 + } +} + async fn verify(opts: UpOptions) -> i32 { use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; + if opts.quick { + return verify_quick(&opts).await; + } use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; let paths = opts.dirs.paths(); let config = match crate::config::RunConfig::read(&paths.run_config()) { @@ -954,3 +1157,26 @@ mod machine_tests { } } + +#[cfg(test)] +mod status_tests { + use super::*; + use serde_json::json; + + #[test] + fn the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor() { + let s = json!({"phase": "ready", "supervisor_pid": 7, "updated_unix": 1_000_000, "started_unix": 900_000, "message": "ready", + "engine_restarts": 0, "restarts_total": 3, "last_restart_unix": 990_000, "last_restart_reason": "the engine process exited (signal: 9)", + "health": "healthy", "log_bytes": 5 * 1024 * 1024}); + let fresh = render_supervisor(&s, 1_000_010); + assert!(fresh.contains("phase ready (pid 7)") && fresh.contains("up 27 h 46 min"), "{fresh}"); + assert!(fresh.contains("3 in total") && fresh.contains("signal: 9") && fresh.contains("health: healthy; logs 5 MiB"), "{fresh}"); + assert!(!fresh.contains("WARNING"), "{fresh}"); + let stale = render_supervisor(&s, 1_000_000 + 3 * 3600); + assert!(stale.contains("WARNING") && stale.contains("not running"), "{stale}"); + // A supervisor that stopped cleanly is not "dead". + let stopped = json!({"phase": "stopped", "updated_unix": 1_000_000}); + assert!(!render_supervisor(&stopped, 2_000_000).contains("WARNING")); + } + +} diff --git a/crates/deploy/src/cli.rs b/crates/deploy/src/cli.rs index eb002bba..44a15aac 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -16,7 +16,8 @@ USAGE keep the service running without a terminal: a Task Scheduler task at logon on Windows (native route), the user unit in the distribution (+ a task that keeps the VM alive) on the WSL route leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the - verification stamps that let a restart skip the hashing (needs a prepared state) + verification stamps that let a restart skip the hashing (needs a prepared state); + --quick hashes nothing: it reports the health of the installation (stamps, service, disk, logs) leleka profiles [show NAME] list the memory profiles, or print one as JSON leleka version @@ -110,6 +111,8 @@ pub struct UpOptions { pub context_tokens: Option, pub fetch: bool, pub reverify: bool, + /// `leleka verify --quick`: report the health of the installation from the stamps and the status file, hash nothing. + pub quick: bool, /// Accept an existing archive of the pinned length without the strict F32 re-derivation. pub trust_archive: bool, pub mtp_pack: Option, @@ -164,6 +167,9 @@ pub enum Command { kar_fd: Option, }, ExecInherit(Vec), + /// `leleka seal-probe FILE` (not in `--help`): seal FILE into a memfd with the code `leleka run` uses for the archive and compare + /// the memfd with the file byte for byte (SHA-256 of both). A measurement and identity tool for the cold-load work. + SealProbe(PathBuf), Status(UpOptions), Down(UpOptions), /// The options locate the running service; the arguments are what to change. @@ -196,6 +202,7 @@ const UP_FLAGS: &[(&str, bool)] = &[ ("--context-tokens", true), ("--no-fetch", false), ("--reverify", false), + ("--quick", false), ("--trust-archive", false), ("--mtp-pack", true), ("--cublas-dir", true), @@ -404,6 +411,7 @@ fn up_options(args: &[String], env: &Environment) -> Result { kar_fd, fetch: !flags.contains_key("--no-fetch"), reverify: flags.contains_key("--reverify"), + quick: flags.contains_key("--quick"), trust_archive: flags.contains_key("--trust-archive"), mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), cublas_dir, @@ -556,6 +564,10 @@ pub fn parse(args: &[String], env: &Environment) -> Result { up_options(rest, env).map(|options| Command::Service(action, options)) } "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), + "seal-probe" => match rest { + [file] if !file.starts_with("--") => Ok(Command::SealProbe(PathBuf::from(file))), + _ => Err("usage: leleka seal-probe FILE".into()), + }, other => Err(format!("unknown command {other:?}; see `leleka --help`")), } } @@ -771,5 +783,10 @@ mod tests { parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), Command::ExecInherit(_) )); + assert!(matches!( + parse_as(false, &["seal-probe", "/x/y"]).unwrap(), + Command::SealProbe(_) + )); + assert!(parse_as(false, &["seal-probe"]).is_err()); } } diff --git a/crates/deploy/src/facts.rs b/crates/deploy/src/facts.rs index 228b213b..f98b2d59 100644 --- a/crates/deploy/src/facts.rs +++ b/crates/deploy/src/facts.rs @@ -67,6 +67,9 @@ pub struct Facts { pub busy_ports: Vec, pub binaries: BTreeMap, pub hf_token_set: bool, + /// The lab's KAR holder (`kar_holder*.py`, outside this repository) runs on this host: it keeps its own sealed copy of the + /// archive (51 GB of RAM) and the GPU job queue, so a product start next to it cannot fit. Linux only. + pub lab_holder: bool, } impl Facts { @@ -423,6 +426,7 @@ mod linux { arch: std::env::consts::ARCH.to_owned(), root: rustix::process::geteuid().is_root(), hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), + lab_holder: lab_holder_running(), ..Facts::default() }; facts.wsl = is_wsl(&read("/proc/version")); @@ -640,3 +644,23 @@ mod tests { assert!(!env.contains_key("export X")); } } + +/// Is a process whose command line names `kar_holder` alive? (`/proc/*/cmdline`; the lab holder is `python3 .../kar_holder2.py`.) +#[cfg(target_os = "linux")] +fn lab_holder_running() -> bool { + let me = std::process::id().to_string(); + std::fs::read_dir("/proc") + .into_iter() + .flatten() + .flatten() + .filter(|entry| entry.file_name().to_str().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()) && n != me)) + .any(|entry| { + std::fs::read(entry.path().join("cmdline")) + .is_ok_and(|bytes| bytes.split(|&b| b == 0).any(|arg| arg.windows(10).any(|w| w == b"kar_holder"))) + }) +} + +#[cfg(not(target_os = "linux"))] +fn lab_holder_running() -> bool { + false +} diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index e3d60614..8996ea0e 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -307,7 +307,11 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { 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()), + Some(if facts.lab_holder { + "the lab KAR holder (kar_holder*.py) is running and its jobs use the GPU: the service and the lab queue exclude each other (docs/unattended.md, \"Lab mode\"); stop the holder (touch STOP in its jobs directory) or run the lab jobs instead".into() + } else { + "stop the other GPU users (`nvidia-smi` lists them), or lower the budget with --gpu-budget-gib N".into() + }), )); } else { checks.push(pass( @@ -865,6 +869,19 @@ mod tests { assert!(text.contains("--gpu-budget-gib"), "{text}"); } + #[test] + fn a_running_lab_holder_is_named_as_the_reason_the_gpu_is_taken() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].vram_free_mib = 1200; + facts.lab_holder = true; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!(text.contains("kar_holder") && text.contains("Lab mode"), "{text}"); + facts.lab_holder = false; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!(!text.contains("kar_holder") && text.contains("--gpu-budget-gib"), "{text}"); + } + #[test] fn no_gpu_names_the_wsl_remedy_under_wsl() { let profile = Profile::builtin("rtx3080-16g").unwrap(); diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs index 46e4e182..52a5cd7b 100644 --- a/crates/deploy/tests/e2e.rs +++ b/crates/deploy/tests/e2e.rs @@ -474,6 +474,57 @@ fn logs_past_their_limit_are_rotated_while_the_service_runs() { assert!(wait_exit(&mut supervisor, Duration::from_secs(60)).unwrap().success()); } +#[test] +fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model() { + let fixture = Fixture::new("quick"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + fs::create_dir_all(fixture.fake_dir()).unwrap(); + let config = fixture.write_state(file_profile()); + let paths = fixture.dirs.paths(); + fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap(); + for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] { + fs::File::create(paths.shard(index)).unwrap().set_len(size).unwrap(); + } + fs::File::create(paths.kar()).unwrap().set_len(55_295_529_472).unwrap(); + let quick = || { + Process::new(LELEKA) + .args(["verify", "--quick", "--state-dir"]) + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap() + }; + // Not running: the files are there (unstamped, a note), the service is not (a problem). + let before = quick(); + let text = String::from_utf8_lossy(&before.stdout).into_owned(); + assert_eq!(before.status.code(), Some(1), "{text}"); + assert!(text.contains("not stamped") && text.contains("PROBLEM: the API does not answer") && text.contains("health: NOT OK"), "{text}"); + // Running: healthy. + let mut supervisor = start_supervisor(&fixture, &config, None); + fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready"); + let after = quick(); + let text = String::from_utf8_lossy(&after.stdout).into_owned(); + assert_eq!(after.status.code(), Some(0), "{text}"); + assert!(text.contains("health: OK") && text.contains("API answers /ready: yes") && text.contains("engine restarts 0 in total"), "{text}"); + // `leleka status` shows the same supervisor facts. + let status = Process::new(LELEKA) + .args(["status", "--state-dir"]) + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&status.stdout).into_owned(); + assert!(text.contains("supervisor: phase ready") && text.contains("health: "), "{text}"); + signal(u64::from(supervisor.id()), "TERM"); + assert!(wait_exit(&mut supervisor, Duration::from_secs(60)).unwrap().success()); +} + #[test] fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() { let fixture = Fixture::new("fail");