Files
leleka/crates/deploy/src/app.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 98effcdabd deploy: experimental kar_source none and profile rtx5090-32g-gguf-ple (Leleka without the KAR archive, PLE rows from the GGUF shard)
kar_source none passes no --kar-archive-*/--kar-provenance, loads qwen4exp-native-mtp-v1, skips the kar step and the archive checks, rejects --kar-fd.
Engine env of the new profile: LELEKA_PLE_DIRECT=0 (page cache instead of O_DIRECT). Default profiles unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:21:01 +01:00

1491 lines
55 KiB
Rust

//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`.
use crate::{
cli::{Command, Environment, ReconfigureArgs, 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<String> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
/// What `leleka version` prints: the first line stays `leleka VERSION` (scripts parse it); the rest is the build identity embedded by
/// `build.rs` (docs/release/5090-v0.1-checklist.md, section 3).
pub fn version_text() -> String {
format!(
"leleka {}
commit {} ({})
strata pin {} (upstream commit of docs/upstream.md at build time)
built for {}, {} profile",
env!("CARGO_PKG_VERSION"),
env!("LELEKA_BUILD_COMMIT"),
env!("LELEKA_BUILD_TREE"),
env!("LELEKA_BUILD_STRATA_PIN"),
env!("LELEKA_BUILD_TARGET"),
env!("LELEKA_BUILD_PROFILE"),
)
}
fn is_root() -> bool {
#[cfg(target_os = "linux")]
{
rustix::process::geteuid().is_root()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
/// The command line of `leleka`. On Windows the WSL2 route (`winfront`) takes the deployment commands first.
pub async fn main_with(args: Vec<String>) -> i32 {
#[cfg(windows)]
if let Some(code) = crate::winfront::dispatch(&args).await {
return code;
}
main_native(args).await
}
fn home_dir() -> Option<PathBuf> {
#[cfg(windows)]
{
std::env::var_os("USERPROFILE").map(PathBuf::from)
}
#[cfg(not(windows))]
{
std::env::var_os("HOME").map(PathBuf::from)
}
}
/// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`).
pub async fn main_native(mut args: Vec<String>) -> i32 {
// `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it).
if let Some(index) = args.iter().position(|a| a == "--hidden") {
args.remove(index);
crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed);
#[cfg(windows)]
crate::winsys::hide_console();
}
let var = env_var;
let environment = Environment {
root: is_root(),
home: home_dir(),
var: &var,
};
let command = match parse(&args, &environment) {
Ok(command) => command,
Err(message) => {
eprintln!("leleka: {message}");
return 2;
}
};
match command {
Command::Help => {
print!("{USAGE}");
0
}
Command::Version => {
println!("{}", version_text());
0
}
Command::Profiles(None) => {
for (name, _) in BUILTIN {
let profile = Profile::builtin(name).expect("built-in");
println!("{name}\n {}", profile.description);
}
0
}
Command::Profiles(Some(name)) => match Profile::builtin(&name) {
Some(profile) => {
print!("{}", crate::config::to_file_text(&profile));
0
}
None => {
eprintln!("leleka: unknown profile {name:?}");
2
}
},
Command::Preflight(opts) => preflight(opts).await,
Command::Up(opts) => up(opts).await,
Command::Status(opts) => status(opts).await,
Command::Down(opts) => down(opts).await,
Command::Reconfigure(opts, args) => reconfigure(opts, args).await,
Command::Verify(opts) => verify(opts).await,
Command::Logs(opts, args) => crate::logview::run_logs(&opts, &args),
Command::Report(opts, args) => crate::logview::run_report(&opts, &args),
Command::Service(action, opts) => crate::winservice::run_native(action, opts).await,
Command::Run { config, kar_fd } => {
supervisor::run(supervisor::Options { config, kar_fd }).await
}
Command::SealProbe(file) => seal_probe(&file),
Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) {
Ok(never) => match never {},
Err(message) => {
eprintln!("leleka exec-inherit: {message}");
2
}
},
Command::SealExec(rest) => match crate::sealed::seal_exec(&rest) {
Ok(never) => match never {},
Err(message) => {
eprintln!("leleka seal-exec: {message}");
2
}
},
}
}
/// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the file.
#[cfg(unix)]
fn seal_probe(file: &std::path::Path) -> i32 {
use sha2::{Digest, Sha256};
use std::os::unix::fs::FileExt;
let started = std::time::Instant::now();
let (memfd, _identity, report) =
match crate::sealed::seal_file_report(file, None, &mut |done, total| {
eprintln!(
"sealing: {:.1} of {:.1} GiB",
done as f64 / 1073741824.0,
total as f64 / 1073741824.0
);
}) {
Ok(done) => done,
Err(message) => {
eprintln!("leleka seal-probe: {message}");
return 1;
}
};
let sealed_s = started.elapsed().as_secs_f64();
let length = memfd.metadata().map_or(0, |m| m.len());
let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new());
let source = match std::fs::File::open(file) {
Ok(f) => f,
Err(error) => {
eprintln!("leleka seal-probe: {error}");
return 1;
}
};
let mut block = vec![0u8; 8 << 20];
let mut other = vec![0u8; 8 << 20];
let mut offset = 0u64;
while offset < length {
let n = (length - offset).min(block.len() as u64) as usize;
if memfd.read_exact_at(&mut block[..n], offset).is_err()
|| source.read_exact_at(&mut other[..n], offset).is_err()
{
eprintln!("leleka seal-probe: read failed at {offset}");
return 1;
}
from_memfd.update(&block[..n]);
from_file.update(&other[..n]);
offset += n as u64;
}
let (a, b) = (
hex::encode(from_memfd.finalize()),
hex::encode(from_file.finalize()),
);
println!(
"seal-probe {} bytes {} read={} sealed in {:.1} s ({:.0} MB/s) sha256(memfd)={} sha256(file)={} {}",
file.display(),
length,
report.strategy.as_str(),
sealed_s,
length as f64 / sealed_s.max(1e-9) / 1e6,
a,
b,
if a == b { "IDENTICAL" } else { "DIFFERENT" }
);
i32::from(a != b)
}
#[cfg(not(unix))]
fn seal_probe(_file: &std::path::Path) -> i32 {
eprintln!("leleka seal-probe needs Linux");
2
}
fn print_report(report: &Report) {
eprint!("{}", report.render());
}
fn json_plan(ctx: &Context, steps: &[Step]) -> Value {
json!({
"mode": ctx.mode,
"profile": ctx.config.as_ref().map(|c| c.profile.name.clone()),
"preflight": ctx.report,
"steps": steps,
"engine_command": ctx.config.as_ref().map(|c| {
let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()];
args.extend(c.engine_args(c.kar_arg()));
args
}),
})
}
async fn preflight(opts: UpOptions) -> i32 {
let ctx = gather(&opts, &env_var);
match (&ctx.profile, &ctx.report) {
(Err(message), _) => {
eprintln!("leleka: {message}");
1
}
(Ok(_), Some(report)) => {
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(report).expect("serializable")
);
} else {
print_report(report);
}
i32::from(report.failed())
}
_ => 1,
}
}
pub async fn up(opts: UpOptions) -> i32 {
let ctx = gather(&opts, &env_var);
if let Err(message) = &ctx.profile {
eprintln!("leleka: {message}");
return 1;
}
let report = ctx
.report
.as_ref()
.expect("report exists when the profile does");
print_report(report);
if let Some(resources) = &ctx.needs.resources {
eprint!("{}", resources.render(&ctx.facts));
}
let fs = gather_fs(&ctx).await;
let steps = plan_steps(&ctx, &fs);
let blocked = steps
.iter()
.any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight");
if opts.dry_run {
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable")
);
} else {
print!("{}", render_plan(&ctx, &steps));
println!(
"mode: {}; nothing was changed (--dry-run)",
ctx.mode.label()
);
}
return i32::from(report.failed() || blocked);
}
if report.failed() {
eprintln!(
"leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command."
);
return 1;
}
eprint!("{}", render_plan(&ctx, &steps));
match run_up(&ctx, &steps).await {
Ok(code) => code,
Err(message) => {
eprintln!("leleka: {message}");
eprintln!(
"leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)."
);
1
}
}
}
pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result<i32, String> {
let changes = steps::prepare(ctx, steps).await?;
let config = steps::config_of(ctx)?;
match ctx.mode {
Mode::None => {
say(&format!(
"prepared. Start it with: {} run --config {}",
ctx.paths.bin("leleka").display(),
ctx.paths.run_config().display()
));
Ok(0)
}
Mode::Systemd(scope) => {
#[cfg(unix)]
if scope == UnitScopeTag::System {
steps::ensure_service_user(ctx).await?;
steps::hand_over_to_service_user(ctx)?;
}
let changed = steps::install_unit(ctx, scope).await?;
steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?;
steps::wait_ready(ctx, Some(scope)).await?;
summary(ctx, config);
Ok(0)
}
Mode::Foreground => {
if let Some(fd) = ctx.opts.kar_fd {
if config.profile.kar_source == crate::profile::KarSource::None {
return Err(format!(
"--kar-fd {fd} was given but profile {} has kar_source none (no archive is used); drop --kar-fd",
config.profile.name
));
}
crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?;
}
if steps::probe_ready(ctx).await {
say("a supervisor for this state directory is already ready");
summary(ctx, config);
return Ok(0);
}
if crate::plan::service_running(&ctx.paths) {
return Err(format!(
"another supervisor is running for {} (not ready yet); wait for it or stop it first",
ctx.opts.dirs.state.display()
));
}
let options = supervisor::Options {
config: ctx.paths.run_config(),
kar_fd: ctx.opts.kar_fd,
};
let run = supervisor::run(options);
tokio::pin!(run);
let mut printed = false;
loop {
tokio::select! {
code = &mut run => return Ok(code),
ready = steps::wait_ready(ctx, None), if !printed => {
printed = true;
match ready {
Ok(()) => summary(ctx, config),
Err(message) => say(&message),
}
}
}
}
}
}
}
pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value {
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
json!({
"ready": true,
"endpoint": format!("http://{}", ctx.opts.ports.api),
"model": config.model_id,
"model_digest": config.model_digest,
"api_key_file": ctx.paths.api_key().display().to_string(),
"gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})),
"profile": config.profile.name,
"gpu_budget_bytes": config.profile.gpu_budget_bytes,
"context_tokens": config.profile.context_tokens,
"kar_source": config.profile.kar_source.as_str(),
"ram_total_bytes": ctx.facts.memory.total,
"ram_available_at_start_bytes": ctx.facts.memory.available,
"service": ctx.mode.label(),
"expert_tier": crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets),
"logs": ctx.paths.logs().display().to_string(),
"state": ctx.opts.dirs.state.display().to_string(),
"assets": ctx.opts.dirs.assets.display().to_string(),
})
}
pub fn summary(ctx: &Context, config: &crate::config::RunConfig) {
let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64);
if ctx.opts.json {
println!(
"{}",
serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable")
);
return;
}
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
let key_file = ctx.paths.api_key().display().to_string();
let mut text = String::from("\nLeleka is ready.\n");
text.push_str(&format!(
" endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n",
ctx.opts.ports.api
));
text.push_str(&format!(
" model {} {}\n",
config.model_id, config.model_digest
));
text.push_str(&format!(
" api key in {key_file} (send it as `Authorization: Bearer ...`)\n"
));
if let Some(gpu) = gpu {
text.push_str(&format!(
" gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n",
gpu.name,
gpu.index,
gpu.sm.map_or("?".into(), |s| s.to_string()),
gpu.vram_total_mib,
gpu.driver
));
}
text.push_str(&format!(
" profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n",
config.profile.name,
gib(config.profile.gpu_budget_bytes),
config.profile.context_tokens,
match config.profile.kar_source {
crate::profile::KarSource::Memfd => format!(
"a sealed memfd ({} of RAM held for the life of the service{})",
gib(config.profile.memfd_bytes()),
if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly {
"; sparse copy: only the byte ranges the serve path reads, holes elsewhere"
} else {
""
}
),
crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(),
crate::profile::KarSource::None =>
"none (EXPERIMENTAL: no archive; the PLE rows are read from the GGUF shard, qwen4exp-native-mtp-v1)".to_owned(),
}
));
text.push_str(&format!(
" host RAM {} total, {} available before start\n",
gib(ctx.facts.memory.total),
gib(ctx.facts.memory.available)
));
text.push_str(&format!(
" expert {}\n",
crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets).line()
));
text.push_str(&format!(" service {}\n", ctx.mode.label()));
if ctx.mode == Mode::Systemd(UnitScopeTag::User) {
text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot
");
}
text.push_str(&format!(
" logs {} (leleka.log, engine.log, gateway.log, api.log)\n",
ctx.paths.logs().display()
));
if ctx.facts.os == "windows" {
text.push_str(&format!(
" try {}
",
powershell_try(&key_file, &ctx.opts.ports.api, &config.model_id)
));
eprintln!("{text}");
return;
}
text.push_str(&format!(
" try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n",
config.model_id, ctx.opts.ports.api
));
eprintln!("{text}");
}
/// A PowerShell one-liner that sends one request to the API (the key file may be a UNC path into WSL).
pub fn powershell_try(key_file: &str, api: &str, model: &str) -> String {
format!(
"$k=(Get-Content -Raw '{key_file}').Trim(); Invoke-RestMethod -Method Post -Uri http://{api}/v1/responses -Headers @{{Authorization=\"Bearer $k\"}} -ContentType 'application/json' -Body '{{\"model\":\"{model}\",\"input\":\"hello\",\"max_output_tokens\":32}}'"
)
}
/// Which systemd unit of this deployment exists (system first), judged by the unit file.
fn installed_scope(paths: &crate::layout::Paths) -> Option<UnitScopeTag> {
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<Value> = std::fs::read_to_string(paths.status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let ready = steps::probe_ready_at(&paths, &api).await;
let expert_tier = crate::config::RunConfig::read(&paths.run_config())
.ok()
.map(|config| crate::expert_profile::tier_report(&config, &config.dirs().assets));
let gateway = if ready {
steps::fetch_status(&paths, &api).await
} else {
None
};
let unit = match installed_scope(&paths) {
Some(scope) => {
let mut command = tokio::process::Command::new("systemctl");
if scope == UnitScopeTag::User {
command.arg("--user");
}
command.args(["is-active", paths.unit_name()]);
command
.output()
.await
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
}
None => None,
};
let requests = crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms());
print_status(
opts.json,
ready,
unit.map(|state| (paths.unit_name().to_owned(), state)),
status,
gateway.as_ref(),
expert_tier.as_ref(),
&paths.run_dir().display().to_string(),
requests.as_deref(),
)
}
/// The `leleka status` output from the pieces gathered on this host or through the WSL bridge. Exit code 1 when not ready.
#[allow(clippy::too_many_arguments)]
pub fn print_status(
json: bool,
ready: bool,
unit: Option<(String, String)>,
supervisor: Option<Value>,
gateway: Option<&Value>,
expert_tier: Option<&crate::expert_profile::TierReport>,
run_dir: &str,
requests: Option<&str>,
) -> i32 {
let machine = gateway
.map(|g| g["machine"].clone())
.filter(Value::is_object);
if json {
println!(
"{}",
serde_json::to_string_pretty(
&json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), "supervisor": supervisor, "machine": machine,
"prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), "expert_tier": expert_tier, "requests": requests})
)
.expect("serializable")
);
} else {
println!("ready: {ready}");
if let Some((name, state)) = unit {
println!("systemd unit {name}: {state}");
}
match supervisor {
Some(s) => print!("{}", render_supervisor(&s, unix_now())),
None => println!("supervisor: no status file in {run_dir} (never started?)"),
}
if let Some(tier) = expert_tier {
println!("{}", tier.line());
}
if let Some(line) = requests {
println!("{line}");
}
if let Some(machine) = &machine {
print!("{}", render_machine(machine));
} else if ready {
println!("engine load: the engine reports no telemetry yet");
}
}
i32::from(!ready)
}
fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// `3 min`, `2 h 05 min`, `4 days 3 h`: how long ago, for people.
pub fn age_text(seconds: u64) -> String {
duration_text(seconds)
}
fn duration_text(seconds: u64) -> String {
match seconds {
s if s < 120 => format!("{s} s"),
s if s < 7200 => format!("{} min", s / 60),
s if s < 172_800 => format!("{} h {:02} min", s / 3600, s % 3600 / 60),
s => format!("{} days {} h", s / 86_400, s % 86_400 / 3600),
}
}
/// The supervisor part of `leleka status`: what it does, for how long, what it restarted and why, whether it is alive.
pub fn render_supervisor(s: &Value, now: u64) -> String {
let updated = s["updated_unix"].as_u64().unwrap_or(0);
let age = now.saturating_sub(updated);
let mut out = format!(
"supervisor: phase {} (pid {}), updated {} ({} ago)\n {}\n",
s["phase"].as_str().unwrap_or("?"),
s["supervisor_pid"],
supervisor::format_utc(updated),
duration_text(age),
s["message"].as_str().unwrap_or("")
);
// The supervisor rewrites its status at least every 30 s while it lives.
let live = !matches!(s["phase"].as_str(), Some("stopped" | "failed"));
if live && age > 120 {
out.push_str(&format!(
" WARNING: the status is {} old although the phase is {}: the supervisor is not running (crashed or killed)\n",
duration_text(age),
s["phase"].as_str().unwrap_or("?")
));
}
if let Some(started) = s["started_unix"].as_u64() {
out.push_str(&format!(
" up {}",
duration_text(now.saturating_sub(started))
));
out.push_str(&format!(
", engine restarts {} in total ({} in a row)",
s["restarts_total"].as_u64().unwrap_or(0),
s["engine_restarts"].as_u64().unwrap_or(0)
));
if let (Some(at), Some(why)) = (
s["last_restart_unix"].as_u64(),
s["last_restart_reason"].as_str(),
) {
out.push_str(&format!(
"\n last restart {} ago: {why}",
duration_text(now.saturating_sub(at))
));
}
out.push('\n');
} else {
out.push_str(&format!(" engine restarts {}\n", s["engine_restarts"]));
}
if let Some(health) = s["health"].as_str() {
out.push_str(&format!(
" health: {health}; logs {} MiB\n",
s["log_bytes"].as_u64().unwrap_or(0) >> 20
));
}
out
}
/// `leleka reconfigure`.
///
/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A
/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process.
/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise).
async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 {
let paths = opts.dirs.paths();
let supervised = crate::plan::service_running(&paths);
if args.needs_restart() {
return reconfigure_by_restart(&opts, &args, supervised).await;
}
let settings = serde_json::Value::Object(args.settings.clone()).to_string();
let api = crate::config::RunConfig::read(&paths.run_config())
.map(|config| config.ports.api)
.unwrap_or_else(|_| opts.ports.api.clone());
let Ok(key) = std::fs::read_to_string(paths.api_key()) else {
eprintln!(
"leleka: no API key in {} (is the service prepared?)",
paths.api_key().display()
);
return 1;
};
let Some(address) = crate::config::probe_address(&api) else {
eprintln!("leleka: cannot reach the API address {api}");
return 1;
};
let persist = args.persist.then_some(PersistTarget {
paths: &paths,
settings: &args.settings,
supervised,
});
send_reconfigure(address, key.trim_end(), &settings, opts.json, persist).await
}
/// Where `--persist` writes after a successful runtime change.
pub struct PersistTarget<'a> {
pub paths: &'a crate::layout::Paths,
pub settings: &'a serde_json::Map<String, Value>,
/// A supervisor runs: it records the change in the configuration it holds.
pub supervised: bool,
}
/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge.
pub async fn send_reconfigure(
address: std::net::SocketAddr,
key: &str,
settings: &str,
json: bool,
persist: Option<PersistTarget<'_>>,
) -> i32 {
eprintln!(
"leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)"
);
let response = crate::http::post_json(
address,
"/v1/reconfigure",
Some(key),
settings,
std::time::Duration::from_secs(1900),
)
.await;
match response {
Ok(response) => {
let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null);
let mut persisted = None;
if response.status == 200
&& let Some(target) = &persist
{
persisted =
Some(persist_settings(target.paths, target.settings, target.supervised).await);
}
if json {
let mut shown = document.clone();
if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) {
object.insert("persisted".into(), json!(result.is_ok()));
}
println!(
"{}",
serde_json::to_string_pretty(&shown).unwrap_or(response.body)
);
} else if response.status == 200 {
println!("reconfigured; the engine runs with:");
print!("{}", render_settings(&document["settings"]));
match &persisted {
Some(Ok(note)) => println!("persisted: {note}"),
Some(Err(why)) => eprintln!(
"leleka: the engine runs with the new settings, but they were not persisted: {why}"
),
None => {}
}
} else {
let message = document["error"]["message"]
.as_str()
.unwrap_or(&response.body);
eprintln!(
"leleka: the change was refused (HTTP {}): {message}",
response.status
);
}
i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err()))
}
Err(message) => {
eprintln!("leleka: {message}");
1
}
}
}
/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine
/// keeps it) and writes the file; with no supervisor the file is edited directly.
async fn persist_settings(
paths: &crate::layout::Paths,
settings: &serde_json::Map<String, Value>,
supervised: bool,
) -> Result<String, String> {
if !supervised {
let changed = crate::reconfigure::persist_offline(paths, settings)?;
return Ok(format!(
"leleka.json updated ({} changed; no supervisor was running)",
changed.len()
));
}
let request = crate::reconfigure::Request {
id: crate::reconfigure::new_request_id(),
settings: settings.clone(),
persist: true,
..Default::default()
};
let outcome =
ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?;
if outcome.state == crate::reconfigure::State::Done && outcome.persisted {
Ok(outcome.message)
} else {
Err(outcome.message)
}
}
/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end).
async fn ask_supervisor(
paths: &crate::layout::Paths,
request: &crate::reconfigure::Request,
limit: std::time::Duration,
show_progress: bool,
) -> Result<crate::reconfigure::Outcome, String> {
use crate::reconfigure::{State, read_outcome, write_request};
write_request(paths, request)?;
let started = std::time::Instant::now();
let mut last = String::new();
loop {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
match read_outcome(paths, &request.id) {
Some(outcome) if outcome.state != State::Running => return Ok(outcome),
Some(outcome) if show_progress && outcome.message != last => {
eprintln!("leleka: {}", outcome.message);
last = outcome.message;
}
_ => {}
}
if !crate::plan::service_running(paths) {
return Err("the supervisor stopped before it answered; see the service log".into());
}
if started.elapsed() > limit {
let _ = std::fs::remove_file(paths.reconfigure_request());
return Err(format!(
"the supervisor did not answer within {} s",
limit.as_secs()
));
}
}
}
/// A budget or preset change: the supervisor restarts the engine process with the new numbers.
async fn reconfigure_by_restart(opts: &UpOptions, args: &ReconfigureArgs, supervised: bool) -> i32 {
let paths = opts.dirs.paths();
if !supervised {
eprintln!(
"leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`",
paths.dirs.state.display()
);
return 1;
}
let load_timeout = crate::config::RunConfig::read(&paths.run_config())
.map_or(1800, |config| config.load_timeout_s);
let request = crate::reconfigure::Request {
id: crate::reconfigure::new_request_id(),
gpu_budget_gib: args.gpu_budget_gib,
preset: args.preset,
settings: args.settings.clone(),
persist: args.persist,
};
eprintln!(
"leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)"
);
// two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks
let limit = std::time::Duration::from_secs(2 * load_timeout + 300);
let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await {
Ok(outcome) => outcome,
Err(why) => {
eprintln!("leleka: {why}");
return 1;
}
};
let done = outcome.state == crate::reconfigure::State::Done;
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(&outcome).unwrap_or_default()
);
} else if done {
println!("reconfigured: {}", outcome.message);
if let Some(effective) = &outcome.effective {
print!("{}", render_effective(effective));
}
} else {
eprintln!("leleka: the change was not made: {}", outcome.message);
}
i32::from(!done)
}
/// The numbers in force after a restart-in-place, one line each.
pub fn render_effective(effective: &Value) -> String {
let Some(object) = effective.as_object() else {
return String::new();
};
let mut out = String::new();
for (key, value) in object {
if !value.is_null() {
out.push_str(&format!(" {key:20} {value}\n"));
}
}
out
}
/// The settings block of the engine, one line per member.
pub fn render_settings(settings: &Value) -> String {
let Some(object) = settings.as_object() else {
return String::new();
};
let mut out = String::new();
for (key, value) in object {
if key == "prefix_cache" && value.is_object() {
out.push_str(&format!(
" prefix cache {} MiB requested {}, tail {}, block {} tokens, kept {} min\n",
value["budget_mib"]
.as_u64()
.map_or("?".to_owned(), |m| m.to_string()),
value["requested"],
value["tail"].as_str().unwrap_or("?"),
value["block_tokens"],
value["retention_min"]
));
} else if key == "prefix_cache" {
out.push_str(" prefix cache off\n");
} else {
out.push_str(&format!(" {key:13} {value}\n"));
}
}
out
}
/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context.
pub fn render_machine(machine: &Value) -> String {
let gib = |mib: &Value| {
mib.as_f64()
.map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0))
};
let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}"));
let pct = |value: &Value| {
value
.as_f64()
.map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0))
};
let mut out = format!(
"engine load ({}):\n",
machine["phase"].as_str().unwrap_or("?")
);
let gpu = &machine["gpu"];
if gpu.is_object() {
out.push_str(&format!(
" gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n",
gpu["util_pct"],
gpu["mem_util_pct"],
gib(&gpu["vram_used_mib"]),
gib(&gpu["vram_total_mib"]),
gpu["power_w"]
.as_f64()
.map_or(String::new(), |w| format!(", {w:.0} W")),
gpu["sm_clock_mhz"]
.as_u64()
.map_or(String::new(), |m| format!(", {m} MHz")),
gpu["temp_c"]
.as_u64()
.map_or(String::new(), |t| format!(", {t} C")),
));
}
let cpu = &machine["cpu"];
if cpu.is_object() {
out.push_str(&format!(
" cpu {} of {} cores busy in the engine (whole system {}%)\n",
cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"]
));
}
let ram = &machine["ram"];
if ram.is_object() {
out.push_str(&format!(
" ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n",
gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"])
));
}
let rates = &machine["throughput"];
out.push_str(&format!(
" prefill {} tok/s last, {} average, {} lifetime\n",
num(&rates["prefill_tok_s_last"]),
num(&rates["prefill_tok_s_avg"]),
num(&rates["prefill_tok_s_lifetime"])
));
out.push_str(&format!(
" decode {} tok/s last, {} average, {} lifetime{}\n",
num(&rates["decode_tok_s_last"]),
num(&rates["decode_tok_s_avg"]),
num(&rates["decode_tok_s_lifetime"]),
rates["decode_tok_s_live"]
.as_f64()
.map_or(String::new(), |v| format!(", {v:.0} now"))
));
let cache = &machine["cache"];
out.push_str(&format!(
" cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n",
pct(&cache["hit_ratio"]),
pct(&cache["token_hit_ratio"]),
cache["last_reused_tokens"],
cache["last_prompt_tokens"]
));
let context = &machine["context"];
out.push_str(&format!(
" context {} of {} tokens{}\n",
context["live_tokens"],
context["max_tokens"],
context["used_pct"]
.as_f64()
.map_or(String::new(), |p| format!(" ({p:.1}%)"))
));
if machine["settings"].is_object() {
out.push_str("settings in force:\n");
out.push_str(&render_settings(&machine["settings"]));
}
out
}
/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the
/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched.
/// `leleka verify --quick`: the health of the installation without reading the model. Reports, from what is on disk and what the
/// service says: whether each model file is stamped as verified in its present state (a stamped file is not hashed again at a start),
/// whether the service runs and answers, how old and how restarted it is, and how big the logs are. Exit 0 only when all is well.
async fn verify_quick(opts: &UpOptions) -> i32 {
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
let paths = opts.dirs.paths();
let config = match crate::config::RunConfig::read(&paths.run_config()) {
Ok(config) => config,
Err(message) => {
eprintln!("leleka: {message}");
return 2;
}
};
let stamps = VerifyStamps::new(paths.engine_stamps(), false);
let mut problems: Vec<String> = Vec::new();
let mut notes: Vec<String> = Vec::new();
let decode = |hex_text: &str| {
let mut out = [0u8; 32];
hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out)
};
let identity_of = |path: &std::path::Path| {
std::fs::File::open(path)
.and_then(|f| f.metadata())
.ok()
.and_then(|m| FileIdentity::of(&m))
};
println!(
"model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):"
);
for index in 0..2 {
let path = paths.shard(index);
let state = match (
decode(crate::profile::SHARD_SHA256_HEX[index]),
identity_of(&path),
) {
(_, None) => {
problems.push(format!("shard {index} is missing: {}", path.display()));
"MISSING"
}
(Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => {
"stamped (verified in its present state)"
}
_ => {
notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp"));
"not stamped"
}
};
println!(" shard {index}: {state} {}", path.display());
}
let kar = paths.kar();
let kar_state = match identity_of(&kar) {
_ if config.profile.kar_source == crate::profile::KarSource::None => "not used (kar_source none)".to_owned(),
None => {
problems.push(format!("the archive is missing: {}", kar.display()));
"MISSING".to_owned()
}
Some(id) if id.size != crate::profile::ARCHIVE_BYTES => {
problems.push(format!(
"the archive has {} bytes, the pinned archive {}",
id.size,
crate::profile::ARCHIVE_BYTES
));
"WRONG SIZE".to_owned()
}
Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => {
"stamped (verified in its present state)".to_owned()
}
Some(_) => {
notes.push("the archive is not stamped: the next start of the engine hashes the sealed copy (about a minute)".into());
"not stamped".to_owned()
}
};
println!(" archive: {kar_state} {}", kar.display());
let api = config.ports.api.clone();
let supervisor: Option<Value> = std::fs::read_to_string(paths.status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let ready = steps::probe_ready_at(&paths, &api).await;
println!("service:");
match &supervisor {
Some(s) => print!(
" {}",
render_supervisor(s, unix_now())
.replace('\n', "\n ")
.trim_end_matches(' ')
),
None => println!(
" no status file in {} (the service has not run)",
paths.run_dir().display()
),
}
println!(" API answers /ready: {}", if ready { "yes" } else { "NO" });
if !ready {
problems.push("the API does not answer /ready".into());
}
if let Some(s) = &supervisor {
let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0));
if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) {
problems.push(format!(
"the supervisor's status is {age} s old: it is not running"
));
}
if s["phase"].as_str() == Some("failed") {
problems.push(format!(
"the supervisor failed: {}",
s["message"].as_str().unwrap_or("")
));
}
}
let log_bytes = crate::logs::total_bytes(&paths.logs());
println!(
" logs: {} MiB in {} (rotated at {} MiB per file, {} generations)",
log_bytes >> 20,
paths.logs().display(),
config.logs.limit_mib,
config.logs.keep
);
match crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()) {
Some(line) => println!(" {line}"),
None => println!(
" requests: no request record yet in {} (`leleka logs --source requests`)",
paths.logs().join("requests.log").display()
),
}
let recent = crate::logview::recent_requests(&paths.logs(), 200);
let failed = recent
.iter()
.filter(|r| matches!(r["fin"].as_str(), Some("error" | "rejected")))
.count();
if recent.len() >= 10 && failed * 5 > recent.len() {
notes.push(format!("{failed} of the last {} requests failed or were rejected: see `leleka logs --level warn --since 1h`", recent.len()));
}
for note in &notes {
println!("note: {note}");
}
if problems.is_empty() {
println!("health: OK");
0
} else {
for problem in &problems {
println!("PROBLEM: {problem}");
}
println!("health: NOT OK");
1
}
}
async fn verify(opts: UpOptions) -> i32 {
use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource};
if opts.quick {
return verify_quick(&opts).await;
}
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file};
let paths = opts.dirs.paths();
let config = match crate::config::RunConfig::read(&paths.run_config()) {
Ok(config) => config,
Err(message) => {
eprintln!("leleka: {message}");
return 2;
}
};
let stamp_dir = paths.engine_stamps();
if let Err(error) = std::fs::create_dir_all(&stamp_dir) {
eprintln!("leleka: cannot create {}: {error}", stamp_dir.display());
return 1;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700));
}
let env = std::fs::read_to_string(paths.env_file())
.map(|text| parse_env_file(&text))
.unwrap_or_default();
let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else {
eprintln!(
"leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`",
paths.env_file().display()
);
return 2;
};
// The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown.
let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets);
say(&tier.line());
let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some();
let started = std::time::Instant::now();
say(
"hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps",
);
let engine = tokio::process::Command::new(paths.bin("leleka-inference"))
.args(config.verify_args(true))
.env(RUNTIME_TOKEN_ENV, token)
.env_remove("HF_TOKEN")
.stdin(std::process::Stdio::null())
.status();
// A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is
// hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`).
let archive = tokio::task::spawn_blocking({
let kar = paths.kar();
let memfd = config.profile.kar_source == KarSource::Memfd;
let stamps = VerifyStamps::new(stamp_dir.clone(), true);
move || -> Result<Option<f64>, String> {
if !memfd {
return Ok(None);
}
let begun = std::time::Instant::now();
let file = std::fs::File::open(&kar)
.map_err(|e| format!("cannot open {}: {e}", kar.display()))?;
let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
let digest =
sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?;
if digest != crate::profile::archive_sha256() {
return Err(format!(
"{} does not match the pinned archive digest",
kar.display()
));
}
let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
if let (Some(before), true) = (before, before == after) {
stamps
.record("kar-source", &crate::profile::archive_sha256(), &before)
.map_err(|e| format!("cannot record the archive stamp: {e}"))?;
}
Ok(Some(begun.elapsed().as_secs_f64()))
}
});
let (engine, archive) = tokio::join!(engine, archive);
let mut code = 0;
match engine {
Ok(status) if status.success() => {}
Ok(status) => {
eprintln!(
"leleka: the engine's verification failed ({status}); a file does not match its pinned digest"
);
code = 1;
}
Err(error) => {
eprintln!(
"leleka: cannot run {}: {error}",
paths.bin("leleka-inference").display()
);
code = 1;
}
}
match archive {
Ok(Ok(Some(seconds))) => say(&format!(
"archive file matches the pinned SHA-256 ({seconds:.1}s); stamped"
)),
Ok(Ok(None)) => {}
Ok(Err(message)) => {
eprintln!("leleka: {message}");
code = 1;
}
Err(error) => {
eprintln!("leleka: archive verification failed to run: {error}");
code = 1;
}
}
if tier_failed {
eprintln!(
"leleka: the expert profile is missing or does not match its pinned digest; rerun `leleka up` (or pass --no-expert-tier to accept the slower decode)"
);
code = 1;
}
say(&format!(
"verification {} in {:.1}s",
if code == 0 { "passed" } else { "FAILED" },
started.elapsed().as_secs_f32()
));
code
}
async fn down(opts: UpOptions) -> i32 {
let paths = opts.dirs.paths();
match installed_scope(&paths) {
Some(scope) => {
let mut command = tokio::process::Command::new("systemctl");
if scope == UnitScopeTag::User {
command.arg("--user");
}
match command.args(["stop", paths.unit_name()]).status().await {
Ok(status) if status.success() => {
eprintln!("leleka: stopped {}", paths.unit_name());
0
}
Ok(status) => {
eprintln!("leleka: systemctl stop failed ({status})");
1
}
Err(error) => {
eprintln!("leleka: cannot run systemctl: {error}");
1
}
}
}
None => {
#[cfg(windows)]
{
return stop_foreground(&paths).await;
}
#[cfg(not(windows))]
{
eprintln!(
"leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)"
);
0
}
}
}
}
/// Windows: a supervisor in another console cannot be sent Ctrl-C, so it watches for a stop file in its run directory.
#[cfg(windows)]
pub async fn stop_foreground(paths: &crate::layout::Paths) -> i32 {
if !crate::plan::service_running(paths) {
eprintln!(
"leleka: no running supervisor for {} (Ctrl-C stops one that runs in a terminal)",
paths.dirs.state.display()
);
return 0;
}
let request = paths.run_dir().join(supervisor::STOP_REQUEST_FILE);
if let Err(error) = std::fs::write(
&request, b"stop
",
) {
eprintln!("leleka: cannot write {}: {error}", request.display());
return 1;
}
eprintln!("leleka: stop requested: the API drains first, then the gateway and the engine");
let started = std::time::Instant::now();
while started.elapsed() < std::time::Duration::from_secs(120) {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
if !crate::plan::service_running(paths) {
eprintln!("leleka: stopped");
return 0;
}
}
eprintln!("leleka: the supervisor is still draining after 120 s; check `leleka status`");
1
}
#[cfg(test)]
mod version_tests {
use super::version_text;
#[test]
fn the_version_names_the_commit_and_the_strata_pin_and_keeps_the_first_line() {
let text = version_text();
assert_eq!(
text.lines().next(),
Some(concat!("leleka ", env!("CARGO_PKG_VERSION")))
);
let pin = env!("LELEKA_BUILD_STRATA_PIN");
// docs/upstream.md is in the repository this crate is built from; an exported tree without it reports `unknown`.
assert!(
pin == "unknown" || (pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit())),
"{pin}"
);
assert!(text.contains(env!("LELEKA_BUILD_COMMIT")), "{text}");
assert!(["clean", "dirty", "unknown"].contains(&env!("LELEKA_BUILD_TREE")));
}
}
#[cfg(test)]
mod machine_tests {
use super::render_machine;
use serde_json::json;
#[test]
fn the_machine_view_names_every_figure_the_operator_asked_for() {
let text = render_machine(&json!({
"phase": "decode",
"gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900},
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
"throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0,
"decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2},
"cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968},
"context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65}
}));
for needle in [
"engine load (decode)",
"91% busy",
"VRAM 29.3 of 31.8 GiB",
"480 W",
"7.4 of 32 cores",
"prefill 5050 tok/s",
"decode 131 tok/s",
"135 now",
"87% of requests",
"91% of prompt",
"179968 of 262144 tokens (68.7%)",
] {
assert!(
text.contains(needle),
"{needle}\
{text}"
);
}
}
#[test]
fn the_settings_block_lists_every_member_and_the_prefix_cache_on_one_line() {
let text = super::render_settings(&json!({
"context_tokens": 65536, "prefill_capacity": 8192, "cpu_workers": 8,
"prefix_cache": {"budget_mib": 20480, "requested": 20480, "tail": "reply", "block_tokens": 8192, "retention_min": 60}
}));
for needle in [
"context_tokens",
"65536",
"prefill_capacity",
"cpu_workers",
"prefix cache 20480 MiB requested 20480, tail reply, block 8192 tokens, kept 60 min",
] {
assert!(
text.contains(needle),
"{needle}
{text}"
);
}
assert!(
super::render_settings(&json!({"prefix_cache": null})).contains("prefix cache off")
);
}
#[test]
fn missing_blocks_are_left_out_not_invented() {
let text = render_machine(
&json!({"phase": "idle", "gpu": null, "cpu": null, "ram": null,
"throughput": {}, "cache": {}, "context": {"live_tokens": 0, "max_tokens": 8192}}),
);
assert!(
!text.contains(" gpu ") && !text.contains(" cpu ") && !text.contains(" ram "),
"{text}"
);
assert!(text.contains("prefill - tok/s"));
}
}
#[cfg(test)]
mod status_tests {
use super::*;
use serde_json::json;
#[test]
fn the_supervisor_part_of_status_shows_age_restarts_and_a_dead_supervisor() {
let s = json!({"phase": "ready", "supervisor_pid": 7, "updated_unix": 1_000_000, "started_unix": 900_000, "message": "ready",
"engine_restarts": 0, "restarts_total": 3, "last_restart_unix": 990_000, "last_restart_reason": "the engine process exited (signal: 9)",
"health": "healthy", "log_bytes": 5 * 1024 * 1024});
let fresh = render_supervisor(&s, 1_000_010);
assert!(
fresh.contains("phase ready (pid 7)") && fresh.contains("up 27 h 46 min"),
"{fresh}"
);
assert!(
fresh.contains("3 in total")
&& fresh.contains("signal: 9")
&& fresh.contains("health: healthy; logs 5 MiB"),
"{fresh}"
);
assert!(!fresh.contains("WARNING"), "{fresh}");
let stale = render_supervisor(&s, 1_000_000 + 3 * 3600);
assert!(
stale.contains("WARNING") && stale.contains("not running"),
"{stale}"
);
// A supervisor that stopped cleanly is not "dead".
let stopped = json!({"phase": "stopped", "updated_unix": 1_000_000});
assert!(!render_supervisor(&stopped, 2_000_000).contains("WARNING"));
}
}