Files
leleka/crates/deploy/tests/e2e.rs
T

2119 lines
76 KiB
Rust

//! Black-box and flow tests with a test double for the runtime programs (no GPU, no model).
//! Run with `cargo test -p leleka-deploy --features test-fakes`.
#![cfg(all(target_os = "linux", feature = "test-fakes"))]
use leleka_deploy::{
app::run_up,
cli::{Command, Environment, UpOptions, parse},
config::{GATEWAY_TOKEN_ENV, Ports, RUNTIME_TOKEN_ENV, RunConfig, to_file_text},
facts::{DirFact, Gpu, Memory},
layout::{BINARIES, Dirs, MTP_FILES},
plan::{Context, FsState, gather, plan_steps},
preflight::evaluate,
profile::{KarSource, Profile},
steps::gather_fs,
};
use std::{
collections::BTreeMap,
fs,
net::TcpListener,
os::unix::fs::{PermissionsExt, symlink},
path::{Path, PathBuf},
process::{Child, Command as Process, Stdio},
time::{Duration, Instant},
};
const FAKE: &str = env!("CARGO_BIN_EXE_leleka-fake-runtime");
const LELEKA: &str = env!("CARGO_BIN_EXE_leleka");
const KEY: &str = "fake-api-key-0123456789abcdef0123456789abcdef";
/// A port from the range below the ephemeral one (32768+), so that the source ports of the many short
/// connections the tests make cannot collide with a port a fixture reserved but has not bound yet.
fn free_port() -> u16 {
use std::sync::atomic::{AtomicU16, Ordering};
static NEXT: AtomicU16 = AtomicU16::new(0);
loop {
let step = NEXT.fetch_add(1, Ordering::Relaxed);
let candidate = 20_000
+ ((std::process::id() as u16)
.wrapping_mul(31)
.wrapping_add(step.wrapping_mul(7)))
% 9_000;
if TcpListener::bind(("127.0.0.1", candidate)).is_ok() {
return candidate;
}
}
}
struct Fixture {
root: PathBuf,
dirs: Dirs,
ports: Ports,
}
impl Fixture {
fn new(name: &str) -> Fixture {
let root = std::env::temp_dir().join(format!("leleka-e2e-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let dirs = Dirs {
prefix: root.join("prefix"),
state: root.join("state"),
assets: root.join("assets"),
};
let ports = Ports {
api: format!("127.0.0.1:{}", free_port()),
engine: format!("127.0.0.1:{}", free_port()),
daemon: format!("127.0.0.1:{}", free_port()),
};
Fixture { root, dirs, ports }
}
fn fake_dir(&self) -> PathBuf {
self.dirs.prefix.join("fake")
}
/// `PREFIX/bin` with the real `leleka` and fakes for the other five (symlinks named like the programs).
fn install_fake_binaries(&self, bin: &Path) {
fs::create_dir_all(bin).unwrap();
for name in BINARIES {
let target = if name == "leleka" { LELEKA } else { FAKE };
let _ = fs::remove_file(bin.join(name));
symlink(target, bin.join(name)).unwrap();
}
}
fn write_state(&self, profile: Profile) -> PathBuf {
let paths = self.dirs.paths();
fs::create_dir_all(paths.logs()).unwrap();
fs::create_dir_all(paths.run_dir()).unwrap();
fs::write(
paths.env_file(),
format!(
"{RUNTIME_TOKEN_ENV}={}\n{GATEWAY_TOKEN_ENV}={}\n",
"r".repeat(40),
"g".repeat(40)
),
)
.unwrap();
fs::write(paths.api_key(), KEY).unwrap();
let mut config =
RunConfig::new(&self.dirs, self.ports.clone(), 0, profile, BTreeMap::new());
config.shutdown_grace_s = 2;
// The flow tests are not about the expert tier (it has no table here): it is off on purpose, as after `--no-expert-tier`.
config.expert_tier = false;
fs::write(paths.run_config(), to_file_text(&config)).unwrap();
fs::write(paths.daemon_config(), to_file_text(&config.daemon_json())).unwrap();
fs::write(paths.strata_config(), to_file_text(&config.strata_json())).unwrap();
paths.run_config()
}
fn status(&self) -> Option<serde_json::Value> {
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<std::process::ExitStatus> {
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<i32>) -> Child {
start_supervisor_with_env(fixture, config, kar_fd, &[])
}
fn start_supervisor_with_env(
fixture: &Fixture,
config: &Path,
kar_fd: Option<i32>,
env: &[(&str, &str)],
) -> Child {
let mut command = Process::new(LELEKA);
command.arg("run").arg("--config").arg(config);
command.envs(env.iter().copied());
if let Some(fd) = kar_fd {
command.arg("--kar-fd").arg(fd.to_string());
}
// A token in the environment of the supervisor must not reach any child.
command
.env("HF_TOKEN", "hf_test_value_that_must_not_leak")
.stdin(Stdio::null());
let log = fs::File::create(fixture.root.join("supervisor.out")).unwrap();
command.stdout(log.try_clone().unwrap()).stderr(log);
command.spawn().unwrap()
}
fn lifecycle(source: KarSource) {
let fixture = Fixture::new(match source {
KarSource::Memfd => "memfd",
KarSource::File => "file",
});
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 first engine hashed the sealed archive; the restarted one is told the same memfd was verified already
// (stamps are on by default), and both get the stamp directory.
let starts: Vec<&str> = calls
.lines()
.filter(|l| l.starts_with("leleka-inference "))
.collect();
assert!(
starts.iter().all(|l| l.contains("--verify-stamps")),
"{calls}"
);
assert!(
!starts[0].contains("--kar-attested-by-stamp"),
"{}",
starts[0]
);
assert_eq!(
starts[1].contains("--kar-attested-by-stamp"),
source == KarSource::Memfd,
"{}",
starts[1]
);
// The sealed descriptor was reused, not copied again (one process held it the whole time).
assert!(!supervisor.try_wait().unwrap().is_some());
// SIGTERM drains and stops everything with status 0.
let new_engine = again["engine_pid"].as_u64().unwrap();
signal(u64::from(supervisor.id()), "TERM");
let status = wait_exit(&mut supervisor, Duration::from_secs(60))
.expect("the supervisor must exit after SIGTERM");
assert!(status.success(), "exit {status:?}\n{}", fixture.logs());
assert_eq!(fixture.status().unwrap()["phase"], "stopped");
for pid in [new_engine, gateway_pid, api_pid] {
assert!(!pid_alive(pid), "pid {pid} outlived the supervisor");
}
assert_eq!(
fixture.http_status("/ready"),
0,
"the API port must be closed"
);
// No child ever saw the Hugging Face token (the fake engine exits 3 if it does).
assert!(
!fs::read_to_string(paths.logs().join("engine.log"))
.unwrap()
.contains("leaked")
);
}
#[test]
fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() {
lifecycle(KarSource::Memfd);
}
/// `memfd_extents: ple_only` profile of the test double (the laptop profile with a sealed memfd and an explicit prefix cap).
fn sparse_profile() -> Profile {
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::Memfd;
profile.memfd_extents = leleka_deploy::profile::MemfdExtents::PleOnly;
profile.memory.prefix_cache_mib = Some("4096".into());
profile.validate().unwrap();
profile
}
#[test]
fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims_the_archive_was_verified()
{
let fixture = Fixture::new("sparse");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let config = fixture.write_state(sparse_profile());
let paths = fixture.dirs.paths();
let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]);
let pin = "ab".repeat(32);
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
let expected: String = if compiled == [0u8; 32] {
pin.clone()
} else {
compiled.iter().map(|b| format!("{b:02x}")).collect()
};
let mut supervisor = start_supervisor_with_env(
&fixture,
&config,
Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)),
&[("LELEKA_KAR_EXTENTS_SHA256", &pin)],
);
let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
assert_eq!(ready["memfd_extents"], "ple_only");
signal(ready["engine_pid"].as_u64().unwrap(), "KILL");
fixture.wait_for("engine restart", Duration::from_secs(60), |s| {
s["phase"] == "ready" && s["engine_restarts"] == 1
});
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap();
let starts: Vec<&str> = calls
.lines()
.filter(|l| l.starts_with("leleka-inference "))
.collect();
assert_eq!(starts.len(), 2, "{calls}");
for (i, line) in starts.iter().enumerate() {
assert!(
line.contains(&format!("--kar-sparse-extents-sha256 {expected}")),
"engine {i}: {line}"
);
assert!(line.contains("--kar-archive-fd"), "{line}");
// the memfd is not the archive: no attestation by a stamp of the archive file, not even for the restarted engine
assert!(
!line.contains("--kar-attested-by-stamp"),
"engine {i}: {line}"
);
}
// and no stamp of the archive was recorded from it
let stamps: Vec<String> = fs::read_dir(paths.stamps())
.map(|d| {
d.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
assert!(
!stamps.iter().any(|name| name.starts_with("kar")),
"{stamps:?}"
);
let log = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap_or_default()
+ &fixture.logs();
// (the sparse memfd was EXPERIMENTAL until it became the rtx5090-32g form; the digest line is the contract)
assert!(log.contains(&expected), "{log}");
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()),
"{}",
fixture.logs()
);
}
#[test]
fn a_sparse_memfd_profile_starts_on_the_compiled_digest_and_refuses_when_none_is_pinned() {
let fixture = Fixture::new("sparse-nopin");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let config = fixture.write_state(sparse_profile());
let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]);
let mut supervisor = start_supervisor_with_env(
&fixture,
&config,
Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)),
&[],
);
if leleka_model_format::kar::PLE_EXTENTS_SHA256 != [0u8; 32] {
// the extents digest is pinned in the binary (the release form): no operator pin is needed and the supervisor starts
fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()),
"{}",
fixture.logs()
);
return;
}
let status =
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must refuse");
{
assert_eq!(status.code(), Some(1));
let message = fixture.status().unwrap()["message"]
.as_str()
.unwrap()
.to_owned();
assert!(
message.contains("kar_census") && message.contains("--hash-extents"),
"{message}"
);
// no engine was started
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default();
assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}");
}
}
#[test]
fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_cannot_seal() {
let dir = std::env::temp_dir().join(format!("leleka-seal-exec-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let file = dir.join("archive.bin");
let bytes: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
fs::write(&file, &bytes).unwrap();
let run = |extra: &[&str]| {
Process::new(LELEKA)
.args(["seal-exec", "--file"])
.arg(&file)
.args(extra)
.output()
.unwrap()
};
let ok = run(&[
"--expect-bytes",
"300000",
"--",
"sh",
"-c",
"wc -c < /proc/self/fd/{FD}; readlink /proc/self/fd/{FD}; cksum < /proc/self/fd/{FD}",
]);
let out = String::from_utf8_lossy(&ok.stdout);
assert!(
ok.status.success(),
"{}{}",
out,
String::from_utf8_lossy(&ok.stderr)
);
assert!(
out.contains("300000") && out.contains("/memfd:leleka-sealed-archive"),
"{out}"
);
let want = Process::new("cksum")
.stdin(fs::File::open(&file).unwrap())
.output()
.unwrap();
assert!(
out.contains(String::from_utf8_lossy(&want.stdout).trim()),
"the descriptor holds the file byte for byte: {out}"
);
// a wrong length, a missing command and the sparse form without its length are refused (exit 2), nothing is run
for extra in [
vec!["--expect-bytes", "1", "--", "true"],
vec!["--expect-bytes", "300000"],
vec!["--sparse-ple", "--", "true"],
] {
let refused = run(&extra);
assert_eq!(
refused.status.code(),
Some(2),
"{extra:?}: {}",
String::from_utf8_lossy(&refused.stderr)
);
}
// a file that is not a KAR archive cannot be sealed sparse
let sparse = run(&["--sparse-ple", "--expect-bytes", "300000", "--", "true"]);
assert_eq!(sparse.status.code(), Some(2));
assert!(
String::from_utf8_lossy(&sparse.stderr).contains("not a valid KAR archive"),
"{}",
String::from_utf8_lossy(&sparse.stderr)
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn supervisor_lifecycle_with_a_read_only_archive_file() {
lifecycle(KarSource::File);
}
/// Rewrite `leleka.json` with `change` applied (the fixture writes the defaults).
fn tune(config: &Path, change: impl FnOnce(&mut serde_json::Value)) {
let mut value: serde_json::Value =
serde_json::from_str(&fs::read_to_string(config).unwrap()).unwrap();
change(&mut value);
fs::write(config, serde_json::to_string_pretty(&value).unwrap()).unwrap();
}
fn file_profile() -> Profile {
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
profile
}
#[test]
fn a_hung_engine_is_killed_and_restarted_by_the_health_check() {
// `max_request_s` is 3 here; the fake API reports a request that has been active for 600 s.
let fixture = Fixture::new("hang");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
tune(&config, |c| {
c["health"] =
serde_json::json!({"enabled": true, "interval_s": 1, "fail_s": 30, "max_request_s": 3});
c["restart"]["backoff_initial_s"] = serde_json::json!(1);
});
let mut supervisor = start_supervisor(&fixture, &config, None);
let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
assert_eq!(ready["restarts_total"], 0);
let hung_pid = ready["engine_pid"].as_u64().unwrap();
// The process lives and the API answers, but a request has been active for ten minutes.
fs::write(fixture.fake_dir().join("hang-decode"), "").unwrap();
let again = fixture.wait_for("restart after the stall", Duration::from_secs(60), |s| {
s["phase"] == "ready"
&& s["restarts_total"] == 1
&& s["engine_pid"].as_u64() != Some(hung_pid)
});
let reason = again["last_restart_reason"].as_str().unwrap();
assert!(
reason.contains("request has been active") && reason.contains("600"),
"{reason}"
);
assert!(!pid_alive(hung_pid), "the hung engine must be gone");
// The fake reports the hang once; afterwards the new engine is judged healthy.
let healthy = fixture.wait_for("healthy again", Duration::from_secs(30), |s| {
s["health"] == "healthy"
});
assert_eq!(
healthy["restarts_total"], 1,
"no second restart without a second stall"
);
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
.unwrap()
.success()
);
}
#[test]
fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() {
let fixture = Fixture::new("backoff");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
tune(&config, |c| {
c["health"]["enabled"] = serde_json::json!(false);
c["restart"] = serde_json::json!({"max_engine_restarts": 3, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2});
});
let mut supervisor = start_supervisor(&fixture, &config, None);
let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
// Crash it and make every restart fail: three attempts in a row, then the service ends with a message.
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
signal(ready["engine_pid"].as_u64().unwrap(), "KILL");
let status =
wait_exit(&mut supervisor, Duration::from_secs(90)).expect("the supervisor must give up");
assert_eq!(status.code(), Some(1));
let state = fixture.status().unwrap();
assert_eq!(state["phase"], "failed");
let message = state["message"].as_str().unwrap();
assert!(message.contains("failed 3 times in a row"), "{message}");
assert_eq!(state["restarts_total"], 1);
let log = fs::read_to_string(fixture.dirs.paths().logs().join("leleka.log")).unwrap();
assert!(
log.matches("the engine did not come back").count() >= 3,
"{log}"
);
// A restart that fails once and then works is just a slower restart.
let fixture = Fixture::new("backoff2");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
tune(&config, |c| {
c["health"]["enabled"] = serde_json::json!(false);
c["restart"] = serde_json::json!({"max_engine_restarts": 5, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2});
});
let mut supervisor = start_supervisor(&fixture, &config, None);
let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
signal(ready["engine_pid"].as_u64().unwrap(), "KILL");
fixture.wait_for("restart attempts", Duration::from_secs(30), |s| {
s["phase"] == "engine_restarting"
});
std::thread::sleep(Duration::from_millis(2500));
fs::remove_file(fixture.fake_dir().join("fail-engine")).unwrap();
let again = fixture.wait_for("recovered", Duration::from_secs(60), |s| {
s["phase"] == "ready" && s["restarts_total"] == 1
});
assert!(again["engine_restarts"].as_u64().unwrap() >= 2, "{again}");
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
.unwrap()
.success()
);
}
#[test]
fn logs_past_their_limit_are_rotated_while_the_service_runs() {
let fixture = Fixture::new("logs");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
tune(&config, |c| {
c["logs"] = serde_json::json!({"limit_mib": 1, "keep": 2})
});
let big = fixture.dirs.paths().logs().join("api.log");
fs::write(&big, "x".repeat(300) + "\n").unwrap();
{
use std::io::Write;
let mut file = fs::OpenOptions::new().append(true).open(&big).unwrap();
for _ in 0..(3 << 20) / 100 {
writeln!(file, "{}", "y".repeat(99)).unwrap();
}
}
let mut supervisor = start_supervisor(&fixture, &config, None);
fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
let rotated = fixture.dirs.paths().logs().join("api.log.1");
let started = Instant::now();
while !rotated.exists() && started.elapsed() < Duration::from_secs(30) {
std::thread::sleep(Duration::from_millis(200));
}
assert!(rotated.exists(), "{}", fixture.logs());
assert!(fs::metadata(&rotated).unwrap().len() <= 1 << 20);
assert!(fs::metadata(&big).unwrap().len() < 1 << 20);
let doc = fixture.status().unwrap();
assert!(doc["log_bytes"].as_u64().unwrap() > 0);
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
.unwrap()
.success()
);
}
#[test]
fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model() {
let fixture = Fixture::new("quick");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
let paths = fixture.dirs.paths();
fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap();
for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] {
fs::File::create(paths.shard(index))
.unwrap()
.set_len(size)
.unwrap();
}
fs::File::create(paths.kar())
.unwrap()
.set_len(55_295_529_472)
.unwrap();
let quick = || {
Process::new(LELEKA)
.args(["verify", "--quick", "--state-dir"])
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--assets")
.arg(&fixture.dirs.assets)
.output()
.unwrap()
};
// Not running: the files are there (unstamped, a note), the service is not (a problem).
let before = quick();
let text = String::from_utf8_lossy(&before.stdout).into_owned();
assert_eq!(before.status.code(), Some(1), "{text}");
assert!(
text.contains("not stamped")
&& text.contains("PROBLEM: the API does not answer")
&& text.contains("health: NOT OK"),
"{text}"
);
// Running: healthy.
let mut supervisor = start_supervisor(&fixture, &config, None);
fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
let after = quick();
let text = String::from_utf8_lossy(&after.stdout).into_owned();
assert_eq!(after.status.code(), Some(0), "{text}");
assert!(
text.contains("health: OK")
&& text.contains("API answers /ready: yes")
&& text.contains("engine restarts 0 in total"),
"{text}"
);
// `leleka status` shows the same supervisor facts.
let status = Process::new(LELEKA)
.args(["status", "--state-dir"])
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--assets")
.arg(&fixture.dirs.assets)
.output()
.unwrap();
let text = String::from_utf8_lossy(&status.stdout).into_owned();
assert!(
text.contains("supervisor: phase ready") && text.contains("health: "),
"{text}"
);
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
.unwrap()
.success()
);
}
#[test]
fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone() {
let fixture = Fixture::new("sidecars");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
let config = fixture.write_state(file_profile());
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
tune(&config, |c| {
c["health"]["enabled"] = serde_json::json!(false)
});
let mut supervisor = start_supervisor(&fixture, &config, None);
let ready = fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
let (engine, gateway, api) = (
ready["engine_pid"].as_u64().unwrap(),
ready["gateway_pid"].as_u64().unwrap(),
ready["api_pid"].as_u64().unwrap(),
);
signal(api, "KILL");
let after_api = fixture.wait_for("a new API", Duration::from_secs(30), |s| {
s["api_pid"].as_u64().is_some_and(|p| p != api) && s["phase"] == "ready"
});
assert_eq!(after_api["engine_pid"].as_u64(), Some(engine));
assert_eq!(
after_api["restarts_total"], 0,
"an API restart is not an engine restart"
);
signal(gateway, "KILL");
let after_gateway = fixture.wait_for("a new gateway", Duration::from_secs(30), |s| {
s["gateway_pid"].as_u64().is_some_and(|p| p != gateway)
});
assert_eq!(after_gateway["engine_pid"].as_u64(), Some(engine));
let started = Instant::now();
while fixture.http_status("/ready") != 200 && started.elapsed() < Duration::from_secs(30) {
std::thread::sleep(Duration::from_millis(200));
}
assert_eq!(fixture.http_status("/ready"), 200);
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
.unwrap()
.success()
);
}
#[test]
fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() {
let fixture = Fixture::new("fail");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
let config = fixture.write_state(profile);
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
let mut supervisor = start_supervisor(&fixture, &config, None);
let status =
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
assert_eq!(status.code(), Some(1));
let state = fixture.status().unwrap();
assert_eq!(state["phase"], "failed");
let message = state["message"].as_str().unwrap();
assert!(
message.contains("engine") && message.contains("exited"),
"{message}"
);
let output = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap();
assert!(output.contains("fatal:"), "{output}");
// The gateway started for the load is not left behind.
assert!(state["gateway_pid"].is_null() || !pid_alive(state["gateway_pid"].as_u64().unwrap()));
}
#[test]
fn a_refused_load_fails_fast_and_shows_the_engine_log() {
// The real engine stays alive when its load fails; only the operation record says so.
let fixture = Fixture::new("refused");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
fs::write(fixture.fake_dir().join("fail-load"), "").unwrap();
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
let config = fixture.write_state(profile);
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
let started = Instant::now();
let mut supervisor = start_supervisor(&fixture, &config, None);
let status =
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
assert_eq!(status.code(), Some(1));
assert!(
started.elapsed() < Duration::from_secs(40),
"a refused load must not wait for the load timeout"
);
let state = fixture.status().unwrap();
let message = state["message"].as_str().unwrap();
assert!(
message.contains("refused the load") && message.contains("BackendUnavailable"),
"{message}"
);
// The engine it started is gone.
let engine_pid = fs::read_to_string(fixture.fake_dir().join("engine.pid"))
.unwrap()
.trim()
.parse()
.unwrap();
assert!(!pid_alive(engine_pid));
}
#[test]
fn verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure() {
let fixture = Fixture::new("verify");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
fixture.write_state(profile);
let run = |fixture: &Fixture| {
Process::new(LELEKA)
.arg("verify")
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--assets")
.arg(&fixture.dirs.assets)
.output()
.unwrap()
};
let output = run(&fixture);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap();
let line = calls
.lines()
.find(|l| l.starts_with("leleka-inference "))
.unwrap();
assert!(
line.contains("--verify-only")
&& line.contains("--verify-rehash")
&& line.contains("--verify-stamps"),
"{line}"
);
// The file profile hands the archive to the engine (which stamps it itself) and no serving switches.
assert!(
line.contains("--kar-archive-file") && !line.contains("--backend-mode"),
"{line}"
);
assert!(fixture.dirs.paths().engine_stamps().is_dir());
fs::write(fixture.fake_dir().join("fail-verify"), "").unwrap();
let output = run(&fixture);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("verification FAILED"));
}
#[test]
fn a_broken_configuration_is_exit_code_two_with_a_clear_message() {
let fixture = Fixture::new("badconfig");
fs::create_dir_all(&fixture.root).unwrap();
let missing = fixture.root.join("nope.json");
let output = Process::new(LELEKA)
.arg("run")
.arg("--config")
.arg(&missing)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
let text = String::from_utf8_lossy(&output.stderr);
assert!(text.contains("run `leleka up` first"), "{text}");
// Weak tokens are refused before anything starts.
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
let config = fixture.write_state(profile);
fs::write(
fixture.dirs.paths().env_file(),
format!("{RUNTIME_TOKEN_ENV}=short\n{GATEWAY_TOKEN_ENV}=short\n"),
)
.unwrap();
let output = Process::new(LELEKA)
.arg("run")
.arg("--config")
.arg(&config)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8_lossy(&output.stderr).contains("32..4096 printable ASCII"));
}
// -----------------------------------------------------------------------------------------------------------
// the `up` flow
/// `up` options of the 3080 profile with the expert tier switched off on purpose: the flow tests must not download
/// the real table. The tier itself is covered by `up_installs_the_expert_profile_offline_and_reports_it`.
fn up_options(
fixture: &Fixture,
bin_src: &Path,
cublas: &Path,
mtp: &Path,
extra: &[&str],
) -> UpOptions {
let mut all = vec!["--no-expert-tier"];
all.extend_from_slice(extra);
up_options_with(fixture, bin_src, cublas, mtp, "rtx3080-16g", &all)
}
fn up_options_with(
fixture: &Fixture,
bin_src: &Path,
cublas: &Path,
mtp: &Path,
profile: &str,
extra: &[&str],
) -> UpOptions {
let var = |_: &str| None;
let args: Vec<String> = [
"up",
"--assets",
&fixture.dirs.assets.display().to_string(),
"--state-dir",
&fixture.dirs.state.display().to_string(),
"--prefix",
&fixture.dirs.prefix.display().to_string(),
"--bin-src",
&bin_src.display().to_string(),
"--cublas-dir",
&cublas.display().to_string(),
"--mtp-pack",
&mtp.display().to_string(),
"--api-port",
fixture.ports.api.rsplit(':').next().unwrap(),
"--engine-port",
fixture.ports.engine.rsplit(':').next().unwrap(),
"--daemon-port",
fixture.ports.daemon.rsplit(':').next().unwrap(),
"--profile",
profile,
"--mode",
"none",
]
.iter()
.map(|s| s.to_string())
.chain(extra.iter().map(|s| s.to_string()))
.collect();
match parse(
&args,
&Environment {
root: false,
home: Some(fixture.root.clone()),
var: &var,
},
)
.unwrap()
{
Command::Up(options) => options,
_ => unreachable!(),
}
}
/// A host that passes the preflight, whatever machine runs the test.
fn healthy_context(opts: &UpOptions) -> Context {
let mut ctx = gather(opts, &|_| None);
let gpu = Gpu {
index: 0,
name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(),
driver: "617.42".into(),
vram_total_mib: 16384,
vram_free_mib: 15500,
sm: Some(86),
};
ctx.facts.os = "linux".into();
ctx.facts.arch = "x86_64".into();
ctx.facts.gpus = vec![gpu];
ctx.facts.memory = Memory {
total: 39 << 30,
available: 37 << 30,
swap_total: 0,
};
ctx.facts.proc_fd = true;
ctx.facts.memfd_ok = true;
ctx.facts.busy_ports.clear();
ctx.facts.libs.insert(
"libcuda.so.1".into(),
Some("/usr/lib/wsl/lib/libcuda.so.1".into()),
);
for key in ["assets", "state", "prefix"] {
ctx.facts.dirs.insert(
key.into(),
DirFact {
path: PathBuf::from("/x"),
free_bytes: Some(2 << 40),
fs_type: Some("ext4".into()),
},
);
}
ctx.needs.binary_has_sm86 = Some(true);
let profile = ctx.profile.as_ref().unwrap().clone();
ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs));
assert!(
!ctx.report.as_ref().unwrap().failed(),
"{}",
ctx.report.as_ref().unwrap().render()
);
ctx
}
fn fake_libraries(dir: &Path) {
fs::create_dir_all(dir).unwrap();
fs::write(dir.join("libcublas.so.12"), b"x").unwrap();
fs::write(dir.join("libcublasLt.so.12"), b"x").unwrap();
}
fn mtp_source(dir: &Path) {
fs::create_dir_all(dir).unwrap();
for name in MTP_FILES {
fs::write(dir.join(name), b"pack").unwrap();
}
}
fn count_calls(fixture: &Fixture, needle: &str) -> usize {
fs::read_to_string(fixture.fake_dir().join("calls.log"))
.unwrap_or_default()
.matches(needle)
.count()
}
#[tokio::test]
async fn up_is_idempotent_resumable_and_never_rotates_secrets() {
let fixture = Fixture::new("up");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
// The fakes find their shared state through the *installed* bin directory.
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
fake_libraries(&cublas);
mtp_source(&mtp);
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]);
let paths = fixture.dirs.paths();
// First run: everything is a todo, then everything exists.
let ctx = healthy_context(&opts);
let fs0 = gather_fs(&ctx).await;
let steps = plan_steps(&ctx, &fs0);
assert!(
steps
.iter()
.filter(|s| matches!(
s.id,
"binaries" | "secrets" | "model" | "kar" | "tokenizer" | "config" | "mtp-pack"
))
.all(|s| s.state.tag() == "todo")
);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
for (what, file) in [
("binary", paths.bin("leleka-inference")),
("run config", paths.run_config()),
("env", paths.env_file()),
("api key", paths.api_key()),
("tokenizer", paths.tokenizer_dir()),
("mtp", paths.mtp_pack().join("experts.bin")),
("stamp", paths.stamps().join("model.json")),
] {
assert!(file.exists(), "{what}: {} missing", file.display());
}
assert_eq!(
fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777,
0o600
);
assert_eq!(
fs::metadata(paths.kar()).unwrap().permissions().mode() & 0o222,
0,
"the file-mode archive must have no write bits"
);
let config = RunConfig::read(&paths.run_config()).unwrap();
assert_eq!(config.profile.name, "rtx3080-16g");
let env_first = fs::read_to_string(paths.env_file()).unwrap();
assert!(
env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())),
"{env_first}"
);
assert_eq!(
(
count_calls(&fixture, "model fetch"),
count_calls(&fixture, "ensure-sharded-streamed"),
count_calls(&fixture, "api-key init")
),
(0, 1, 1),
"the archive step fetches and verifies the shards itself"
);
// Second run: the plan has nothing to do and no tool is invoked again.
let ctx = healthy_context(&opts);
let fs1 = gather_fs(&ctx).await;
let steps = plan_steps(&ctx, &fs1);
for step in &steps {
assert!(
matches!(step.state.tag(), "done" | "skip") || step.id == "preflight",
"{} is {:?} on a re-run",
step.id,
step.state
);
}
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
assert_eq!(
(
count_calls(&fixture, "model fetch"),
count_calls(&fixture, "model verify"),
count_calls(&fixture, "ensure-sharded-streamed"),
count_calls(&fixture, "extract-tokenizer")
),
(0, 0, 1, 1)
);
assert_eq!(
fs::read_to_string(paths.env_file()).unwrap(),
env_first,
"tokens must never rotate"
);
// Resumable: a lost archive is rebuilt, everything else is left alone.
fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap();
fs::remove_file(paths.kar()).unwrap();
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(
steps.iter().find(|s| s.id == "kar").unwrap().state.tag(),
"todo"
);
assert_eq!(
steps.iter().find(|s| s.id == "model").unwrap().state.tag(),
"done"
);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
assert_eq!(
(
count_calls(&fixture, "model fetch"),
count_calls(&fixture, "ensure-sharded-streamed")
),
(0, 2)
);
// --reverify forces the verification again.
let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]);
let ctx = healthy_context(&reverify);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(
steps.iter().find(|s| s.id == "model").unwrap().state.tag(),
"todo"
);
let _ = FsState::default();
}
#[tokio::test]
async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() {
let fixture = Fixture::new("trust");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
fake_libraries(&cublas);
mtp_source(&mtp);
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &["--trust-archive"]);
let paths = fixture.dirs.paths();
// An archive of the pinned length with its provenance sidecar, as left by an earlier build.
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::File::create(paths.kar())
.unwrap()
.set_len(55_295_529_472)
.unwrap();
fs::write(paths.kar_provenance(), "{}").unwrap();
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
let kar = steps.iter().find(|s| s.id == "kar").unwrap();
assert_eq!(kar.state.tag(), "todo");
assert!(
kar.state.why().contains("--trust-archive"),
"{:?}",
kar.state
);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
assert_eq!(
(
count_calls(&fixture, "model fetch"),
count_calls(&fixture, "model verify"),
count_calls(&fixture, "ensure-sharded-streamed")
),
(1, 1, 0)
);
assert!(paths.stamps().join("kar.json").exists() && paths.stamps().join("model.json").exists());
// Without the flag the same archive would be re-verified by the real tool.
let strict = healthy_context(&up_options(
&fixture,
&bin_src,
&cublas,
&mtp,
&["--reverify"],
));
let steps = plan_steps(&strict, &gather_fs(&strict).await);
assert!(
!steps
.iter()
.find(|s| s.id == "kar")
.unwrap()
.state
.why()
.contains("--trust-archive")
);
}
#[tokio::test]
async fn up_installs_the_expert_profile_offline_and_reports_it() {
use leleka_deploy::expert_profile::{
FileState, PROFILE_ENV, file_state, sha256_hex, tier_report,
};
let fixture = Fixture::new("expert");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
fake_libraries(&cublas);
mtp_source(&mtp);
// A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table.
let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec();
let digest = sha256_hex(&table);
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.expert_profile_sha256 = Some(digest.clone());
let profile_file = fixture.root.join("profile.json");
fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap();
let local = fixture.root.join("table.bin");
fs::write(&local, &table).unwrap();
let paths = fixture.dirs.paths();
let table_path = fixture.dirs.assets.join("data/expert-profile.bin");
let flags = [
profile_file.display().to_string(),
local.display().to_string(),
];
// No table, offline, no override: the plan blocks with both ways out, before anything is downloaded.
let opts = up_options_with(
&fixture,
&bin_src,
&cublas,
&mtp,
&flags[0],
&["--no-fetch"],
);
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
let step = steps.iter().find(|s| s.id == "expert-profile").unwrap();
assert_eq!(step.state.tag(), "BLOCKED", "{step:?}");
assert!(
step.state.why().contains("--expert-profile-file")
&& step.state.why().contains("--no-expert-tier")
);
// With the local copy: installed, verified, configured, reported ON.
let opts = up_options_with(
&fixture,
&bin_src,
&cublas,
&mtp,
&flags[0],
&["--expert-profile-file", &flags[1]],
);
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(
steps
.iter()
.find(|s| s.id == "expert-profile")
.unwrap()
.state
.tag(),
"todo"
);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
assert_eq!(file_state(&table_path, &digest), FileState::Valid);
let config = RunConfig::read(&paths.run_config()).unwrap();
assert_eq!(
config.engine_env.get(PROFILE_ENV),
Some(&table_path.display().to_string())
);
let report = tier_report(&config, &fixture.dirs.assets);
assert!(
report.on && report.line().starts_with("expert tier ON"),
"{}",
report.line()
);
// Second run: done, nothing rewritten.
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(
steps
.iter()
.find(|s| s.id == "expert-profile")
.unwrap()
.state
.tag(),
"done"
);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
// The file changes behind the service's back: the report turns OFF and the start drops the switches.
fs::write(&table_path, b"corrupted").unwrap();
let report = tier_report(&config, &fixture.dirs.assets);
assert!(
!report.on && report.line().starts_with("WARNING expert tier OFF"),
"{}",
report.line()
);
let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets);
assert!(!env.contains_key(PROFILE_ENV));
// `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored).
let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]);
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(
steps
.iter()
.find(|s| s.id == "expert-profile")
.unwrap()
.state
.tag(),
"BLOCKED"
);
assert!(
run_up(&ctx, &steps)
.await
.unwrap_err()
.contains("expert-profile")
);
// The explicit opt-out is recorded and reported as such.
let opts = up_options_with(
&fixture,
&bin_src,
&cublas,
&mtp,
&flags[0],
&["--no-expert-tier"],
);
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
let config = RunConfig::read(&paths.run_config()).unwrap();
assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV));
let report = tier_report(&config, &fixture.dirs.assets);
assert!(
!report.on && report.opted_out && report.line().contains("explicit opt-out"),
"{}",
report.line()
);
}
#[tokio::test]
async fn first_start_installs_the_embedded_expert_profile_without_a_network() {
use leleka_deploy::expert_profile::{
FileState, PINNED_BYTES, PINNED_SHA256, file_state, tier_report,
};
let fixture = Fixture::new("embedded");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
fake_libraries(&cublas);
mtp_source(&mtp);
// The real 3080 profile pins the upstream table; no --no-expert-tier, no --expert-profile-file, no network tool on PATH.
let opts = up_options_with(
&fixture,
&bin_src,
&cublas,
&mtp,
"rtx3080-16g",
&["--no-fetch"],
);
let mut ctx = healthy_context(&opts);
ctx.facts.tools.insert("curl".into(), false);
ctx.facts.tools.insert("wget".into(), false);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
let step = steps.iter().find(|s| s.id == "expert-profile").unwrap();
assert_eq!(step.state.tag(), "todo", "{step:?}");
assert!(
step.state.why().contains("embedded in this binary"),
"{step:?}"
);
leleka_deploy::steps::provision_expert_profile(&ctx).unwrap();
let table = fixture.dirs.assets.join("data/expert-profile.bin");
assert_eq!(file_state(&table, PINNED_SHA256), FileState::Valid);
assert_eq!(fs::metadata(&table).unwrap().len(), PINNED_BYTES);
let config = ctx.config.as_ref().unwrap();
let report = tier_report(config, &fixture.dirs.assets);
assert!(
report.on && report.line().contains("8f59b4aa...388975baf"),
"{}",
report.line()
);
// Re-planned: nothing left to do.
let steps = plan_steps(&healthy_context(&opts), &FsState::default());
assert_eq!(
steps
.iter()
.find(|s| s.id == "expert-profile")
.unwrap()
.state
.tag(),
"done"
);
}
#[tokio::test]
async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() {
let fixture = Fixture::new("wrongkar");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
fake_libraries(&cublas);
mtp_source(&mtp);
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]);
// A pre-existing archive of the wrong length: the fake `ensure` reuses it, the size gate must object.
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"short").unwrap();
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
let error = run_up(&ctx, &steps).await.unwrap_err();
assert!(error.contains("engine only admits the pinned"), "{error}");
}
// -----------------------------------------------------------------------------------------------------------
// the command line
#[test]
fn dry_run_prints_the_plan_and_changes_nothing() {
let fixture = Fixture::new("dry");
let bin = fixture.root.join("bin");
fixture.install_fake_binaries(&bin);
let output = Process::new(LELEKA)
.args([
"up",
"--dry-run",
"--profile",
"rtx5090-32g",
"--mode",
"foreground",
"--assets",
])
.arg(&fixture.dirs.assets)
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--bin-src")
.arg(&bin)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stdout.contains("plan:") && stdout.contains("engine command the service runs:"),
"{stdout}"
);
assert!(
stdout.contains("--kar-archive-fd {FD}")
&& stdout.contains("nothing was changed (--dry-run)"),
"{stdout}"
);
assert!(
stderr.contains("preflight (profile rtx5090-32g)"),
"{stderr}"
);
for path in [
&fixture.dirs.assets,
&fixture.dirs.state,
&fixture.dirs.prefix,
] {
assert!(!path.exists(), "--dry-run created {}", path.display());
}
// --json is one parseable document with the steps.
let output = Process::new(LELEKA)
.args([
"up",
"--dry-run",
"--json",
"--profile",
"rtx5090-32g",
"--mode",
"foreground",
"--assets",
])
.arg(&fixture.dirs.assets)
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--bin-src")
.arg(&bin)
.output()
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json["profile"], "rtx5090-32g");
assert!(
json["steps"]
.as_array()
.unwrap()
.iter()
.any(|s| s["id"] == "kar")
);
}
#[test]
fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
let fixture = Fixture::new("preflight-fail");
let bin = fixture.root.join("bin");
fixture.install_fake_binaries(&bin);
// The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check.
let output = Process::new(LELEKA)
.args([
"up",
"--profile",
"rtx5090-32g",
"--mode",
"none",
"--assets",
])
.arg(&fixture.dirs.assets)
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--bin-src")
.arg(&bin)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("[FAIL]") && stderr.contains("fix:"),
"{stderr}"
);
assert!(stderr.contains("nothing was changed"), "{stderr}");
for path in [
&fixture.dirs.assets,
&fixture.dirs.state,
&fixture.dirs.prefix,
] {
assert!(
!path.exists(),
"a failed preflight created {}",
path.display()
);
}
}
#[test]
fn profiles_and_usage_commands() {
let list = Process::new(LELEKA).arg("profiles").output().unwrap();
let text = String::from_utf8_lossy(&list.stdout);
assert!(
text.contains("rtx5090-32g") && text.contains("rtx3080-16g"),
"{text}"
);
let show = Process::new(LELEKA)
.args(["profiles", "show", "rtx3080-16g"])
.output()
.unwrap();
let profile: Profile = serde_json::from_slice(&show.stdout).unwrap();
assert_eq!(
profile.context_tokens, 262144,
"the shipped laptop profile is the owner's 256k workload (crates/deploy/src/profile.rs)"
);
let bad = Process::new(LELEKA)
.args(["up", "--bogus"])
.output()
.unwrap();
assert_eq!(bad.status.code(), Some(2));
assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option"));
}
// ------------------------------------------------------------------------------------------------ leleka reconfigure
mod reconfigure_flow {
use super::*;
use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request};
use leleka_deploy::resources::Preset;
use serde_json::json;
const GIB: u64 = 1 << 30;
fn request(
id: &str,
budget_gib: Option<u64>,
preset: Option<Preset>,
settings: serde_json::Value,
persist: bool,
) -> Request {
Request {
id: id.to_owned(),
gpu_budget_gib: budget_gib,
preset,
settings: settings.as_object().cloned().unwrap_or_default(),
persist,
}
}
fn ask(fixture: &Fixture, request: &Request, limit: Duration) -> Outcome {
write_request(&fixture.dirs.paths(), request).unwrap();
let started = Instant::now();
loop {
if let Some(outcome) = read_outcome(&fixture.dirs.paths(), &request.id)
&& outcome.state != State::Running
{
return outcome;
}
assert!(
started.elapsed() < limit,
"no answer to {}; logs:\n{}",
request.id,
fixture.logs()
);
std::thread::sleep(Duration::from_millis(200));
}
}
/// A supervisor with the fake runtime programs and an inherited sealed archive, ready.
struct Service {
fixture: Fixture,
supervisor: Child,
_memfd: fs::File,
first: serde_json::Value,
}
fn start(name: &str) -> Service {
let fixture = Fixture::new(name);
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::Memfd;
let config = fixture.write_state(profile);
let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]);
let supervisor = start_supervisor(
&fixture,
&config,
Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)),
);
let first = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
Service {
fixture,
supervisor,
_memfd: memfd,
first,
}
}
impl Service {
fn starts(&self) -> Vec<String> {
fs::read_to_string(self.fixture.fake_dir().join("calls.log"))
.unwrap()
.lines()
.filter(|line| line.starts_with("leleka-inference "))
.map(str::to_owned)
.collect()
}
fn stop(mut self) {
signal(u64::from(self.supervisor.id()), "TERM");
assert!(
wait_exit(&mut self.supervisor, Duration::from_secs(60))
.is_some_and(|s| s.success()),
"{}",
self.fixture.logs()
);
}
}
#[test]
fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() {
let service = start("reconf-budget");
let fixture = &service.fixture;
let (engine, gateway, api) = (
service.first["engine_pid"].as_u64().unwrap(),
service.first["gateway_pid"].as_u64().unwrap(),
service.first["api_pid"].as_u64().unwrap(),
);
let before = fs::read_to_string(fixture.dirs.paths().run_config()).unwrap();
let outcome = ask(
fixture,
&request("budget", Some(2), None, json!({}), false),
Duration::from_secs(120),
);
assert_eq!(
outcome.state,
State::Done,
"{}\n{}",
outcome.message,
fixture.logs()
);
assert!(!outcome.persisted);
assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0);
let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| {
s["phase"] == "ready"
});
assert_ne!(
after["engine_pid"].as_u64().unwrap(),
engine,
"the engine process is new"
);
assert!(!pid_alive(engine), "the old engine is gone");
assert_eq!(
after["gateway_pid"].as_u64().unwrap(),
gateway,
"the gateway keeps its process"
);
assert_eq!(
after["api_pid"].as_u64().unwrap(),
api,
"the API keeps its process"
);
assert_eq!(
after["engine_restarts"], 0,
"a planned restart is not a crash"
);
assert_eq!(fixture.http_status("/ready"), 200);
let starts = service.starts();
assert_eq!(starts.len(), 2, "{starts:?}");
assert!(
starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)),
"{}",
starts[0]
);
assert!(
starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)),
"{}",
starts[1]
);
// the sealed descriptor of the first engine was handed on, and it is the one already verified
assert!(
starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"),
"{}",
starts[1]
);
let engine_log =
fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap();
assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}");
// not persisted: the file still has the old budget
assert_eq!(
fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(),
before
);
// asking for what is in force is answered at once, without another restart
let same = ask(
fixture,
&request("same", Some(2), None, json!({}), false),
Duration::from_secs(20),
);
assert_eq!(
(same.state, same.message.contains("already")),
(State::Done, true),
"{}",
same.message
);
assert_eq!(service.starts().len(), 2);
service.stop();
}
#[test]
fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() {
let service = start("reconf-persist");
let fixture = &service.fixture;
let gateway = service.first["gateway_pid"].as_u64().unwrap();
let api = service.first["api_pid"].as_u64().unwrap();
let outcome = ask(
fixture,
&request(
"persist",
Some(3),
Some(Preset::Workstation),
json!({"context_tokens": 4096, "cpu_workers": 3}),
true,
),
Duration::from_secs(120),
);
assert_eq!(
outcome.state,
State::Done,
"{}\n{}",
outcome.message,
fixture.logs()
);
assert!(outcome.persisted, "{}", outcome.message);
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB);
assert_eq!(config.profile.context_tokens, 4096);
assert_eq!(config.preset, Preset::Workstation);
assert!(
config.base_profile.is_some(),
"the unmodified profile is kept to undo the preset"
);
assert_eq!(
config
.engine_environment()
.get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS")
.map(String::as_str),
Some("3")
);
// the API advertises the new context: its process was restarted on the same port, the gateway was not
let strata: serde_json::Value = serde_json::from_str(
&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap(),
)
.unwrap();
assert_eq!(strata["runtime"]["max_context"], 4096);
let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| {
s["phase"] == "ready"
});
assert_ne!(after["api_pid"].as_u64().unwrap(), api);
assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway);
assert_eq!(fixture.http_status("/ready"), 200);
// a crash of the new engine restarts it with the new numbers, not the old ones
signal(after["engine_pid"].as_u64().unwrap(), "KILL");
let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| {
s["phase"] == "ready" && s["engine_restarts"] == 1
});
assert_ne!(again["engine_pid"], after["engine_pid"]);
let starts = service.starts();
let last = starts.last().unwrap();
assert!(
last.contains(&format!("--gpu-budget {}", 3 * GIB))
&& last.contains("--context-tokens 4096"),
"{last}"
);
service.stop();
}
#[test]
fn settings_alone_are_recorded_and_persisted_without_a_restart() {
let service = start("reconf-record");
let fixture = &service.fixture;
let engine = service.first["engine_pid"].as_u64().unwrap();
let outcome = ask(
fixture,
&request(
"record",
None,
None,
json!({"prefix_cache_tail": "prompt", "spec_min_p": 0.25}),
true,
),
Duration::from_secs(30),
);
assert_eq!(
(outcome.state, outcome.persisted),
(State::Done, true),
"{}",
outcome.message
);
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_eq!(
config.profile.memory.prefix_cache_tail.as_deref(),
Some("prompt")
);
assert_eq!(config.profile.spec_min_p, Some(0.25));
assert_eq!(
fixture.status().unwrap()["engine_pid"].as_u64().unwrap(),
engine,
"no restart"
);
assert_eq!(service.starts().len(), 1);
// not persisted: in force for this supervisor only
let quiet = ask(
fixture,
&request("quiet", None, None, json!({"context_tokens": 2048}), false),
Duration::from_secs(30),
);
assert_eq!((quiet.state, quiet.persisted), (State::Done, false));
let file =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_ne!(file.profile.context_tokens, 2048);
// an invalid document is refused and changes nothing
let bad = ask(
fixture,
&request("bad", None, None, json!({"cpu_workers": 99}), true),
Duration::from_secs(30),
);
assert_eq!(bad.state, State::Refused);
assert!(bad.message.contains("cpu_workers"), "{}", bad.message);
service.stop();
}
#[test]
fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one() {
let service = start("reconf-refuse");
let fixture = &service.fixture;
let engine = service.first["engine_pid"].as_u64().unwrap();
// refused before the engine is touched
let bad = ask(
fixture,
&request("bad", Some(2), None, json!({"cpu_workers": 99}), false),
Duration::from_secs(30),
);
assert_eq!(bad.state, State::Refused);
assert!(
bad.message.contains("nothing was changed"),
"{}",
bad.message
);
let unknown = ask(
fixture,
&request("unknown", Some(2), None, json!({"nonsense": 1}), false),
Duration::from_secs(30),
);
assert_eq!(unknown.state, State::Refused);
assert_eq!(
fixture.status().unwrap()["engine_pid"].as_u64().unwrap(),
engine,
"the engine was not stopped"
);
assert!(pid_alive(engine));
// a budget the new engine cannot start with: the previous engine is started again with the previous numbers
fs::write(
fixture.fake_dir().join("fail-engine-budget"),
(4 * GIB).to_string(),
)
.unwrap();
let outcome = ask(
fixture,
&request("fails", Some(4), None, json!({}), true),
Duration::from_secs(180),
);
assert_eq!(
outcome.state,
State::Refused,
"{}\n{}",
outcome.message,
fixture.logs()
);
assert!(
outcome.message.contains("previous settings are back"),
"{}",
outcome.message
);
let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| {
s["phase"] == "ready"
});
assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine);
assert_eq!(fixture.http_status("/ready"), 200);
let starts = service.starts();
assert_eq!(starts.len(), 3, "{starts:?}");
assert!(
starts[1].contains(&format!("--gpu-budget {}", 4 * GIB))
&& starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)),
"{starts:?}"
);
// nothing was persisted from the failed attempt
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB);
service.stop();
}
#[test]
fn the_cli_asks_the_supervisor_and_prints_the_answer() {
let service = start("reconf-cli");
let dirs = service.fixture.dirs.clone();
let run = |args: &[&str]| {
Process::new(LELEKA)
.arg("reconfigure")
.args(args)
.arg("--state-dir")
.arg(&dirs.state)
.arg("--assets")
.arg(&dirs.assets)
.arg("--prefix")
.arg(&dirs.prefix)
.output()
.unwrap()
};
let output = run(&["--gpu-budget-gib", "5", "--persist"]);
let text = String::from_utf8_lossy(&output.stdout).into_owned()
+ &String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"{text}\n{}",
service.fixture.logs()
);
assert!(
text.contains("reconfigured") && text.contains("gpu_budget_gib"),
"{text}"
);
let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap();
assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB);
// a refusal is a non-zero exit with the reason
let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]);
assert!(!refused.status.success());
let text = String::from_utf8_lossy(&refused.stderr);
assert!(
text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"),
"{text}"
);
service.stop();
// without a supervisor the restart path says what to do instead of hanging
let stopped = run(&["--preset", "workstation"]);
assert!(!stopped.status.success());
assert!(
String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"),
"{}",
String::from_utf8_lossy(&stopped.stderr)
);
}
#[test]
fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer() {
let mut service = start("reconf-lost");
let fixture = &service.fixture;
// from now on no engine starts at all: the new one fails, and so does the restored one
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
let outcome = ask(
fixture,
&request("lost", Some(4), None, json!({}), false),
Duration::from_secs(120),
);
assert_eq!(
outcome.state,
State::Failed,
"{}\n{}",
outcome.message,
fixture.logs()
);
assert!(
outcome.message.contains("could not be restored"),
"{}",
outcome.message
);
let status = wait_exit(&mut service.supervisor, Duration::from_secs(60))
.expect("the supervisor must give up");
assert_eq!(status.code(), Some(1));
assert_eq!(fixture.status().unwrap()["phase"], "failed");
}
}