Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1207 lines
46 KiB
Rust
1207 lines
46 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;
|
|
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 {
|
|
let mut command = Process::new(LELEKA);
|
|
command.arg("run").arg("--config").arg(config);
|
|
if let Some(fd) = kar_fd {
|
|
command.arg("--kar-fd").arg(fd.to_string());
|
|
}
|
|
// A token in the environment of the supervisor must not reach any child.
|
|
command
|
|
.env("HF_TOKEN", "hf_test_value_that_must_not_leak")
|
|
.stdin(Stdio::null());
|
|
let log = fs::File::create(fixture.root.join("supervisor.out")).unwrap();
|
|
command.stdout(log.try_clone().unwrap()).stderr(log);
|
|
command.spawn().unwrap()
|
|
}
|
|
|
|
fn lifecycle(source: KarSource) {
|
|
let fixture = Fixture::new(match source {
|
|
KarSource::Memfd => "memfd",
|
|
KarSource::File => "file",
|
|
});
|
|
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
|
|
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
|
profile.kar_source = source;
|
|
let config = fixture.write_state(profile);
|
|
let paths = fixture.dirs.paths();
|
|
let memfd = (source == KarSource::Memfd).then(|| inheritable_sealed_memfd(&vec![7u8; 100_000]));
|
|
if source == KarSource::File {
|
|
fs::create_dir_all(&fixture.dirs.assets).unwrap();
|
|
fs::write(paths.kar(), b"archive").unwrap();
|
|
}
|
|
let fd = memfd.as_ref().map(std::os::fd::AsRawFd::as_raw_fd);
|
|
let mut supervisor = start_supervisor(&fixture, &config, fd);
|
|
|
|
let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
|
|
assert_eq!(ready["engine_restarts"], 0);
|
|
assert_eq!(fixture.http_status("/ready"), 200);
|
|
let (engine_pid, gateway_pid, api_pid) = (
|
|
ready["engine_pid"].as_u64().unwrap(),
|
|
ready["gateway_pid"].as_u64().unwrap(),
|
|
ready["api_pid"].as_u64().unwrap(),
|
|
);
|
|
let engine_log = fs::read_to_string(paths.logs().join("engine.log")).unwrap();
|
|
match source {
|
|
KarSource::Memfd => assert!(engine_log.contains("kar fd "), "{engine_log}"),
|
|
KarSource::File => assert!(engine_log.contains("listening"), "{engine_log}"),
|
|
}
|
|
// The status file is private and never holds a secret.
|
|
let mode = fs::metadata(paths.status_file())
|
|
.unwrap()
|
|
.permissions()
|
|
.mode()
|
|
& 0o777;
|
|
assert_eq!(mode, 0o600);
|
|
assert!(
|
|
!fs::read_to_string(paths.status_file())
|
|
.unwrap()
|
|
.contains(KEY)
|
|
);
|
|
|
|
// Kill the engine: the API reports not ready, the supervisor restarts it and loads again.
|
|
signal(engine_pid, "KILL");
|
|
let again = fixture.wait_for("engine restart", Duration::from_secs(60), |s| {
|
|
s["phase"] == "ready" && s["engine_restarts"] == 1
|
|
});
|
|
assert_ne!(again["engine_pid"].as_u64().unwrap(), engine_pid);
|
|
assert_eq!(
|
|
again["gateway_pid"].as_u64().unwrap(),
|
|
gateway_pid,
|
|
"the gateway must survive an engine restart"
|
|
);
|
|
assert_eq!(
|
|
again["api_pid"].as_u64().unwrap(),
|
|
api_pid,
|
|
"the API must survive an engine restart"
|
|
);
|
|
assert_eq!(fixture.http_status("/ready"), 200);
|
|
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap();
|
|
assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}");
|
|
assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}");
|
|
// The first engine hashed the sealed archive; the restarted one is told the same memfd was verified already
|
|
// (stamps are on by default), and both get the stamp directory.
|
|
let starts: Vec<&str> = calls
|
|
.lines()
|
|
.filter(|l| l.starts_with("leleka-inference "))
|
|
.collect();
|
|
assert!(
|
|
starts.iter().all(|l| l.contains("--verify-stamps")),
|
|
"{calls}"
|
|
);
|
|
assert!(
|
|
!starts[0].contains("--kar-attested-by-stamp"),
|
|
"{}",
|
|
starts[0]
|
|
);
|
|
assert_eq!(
|
|
starts[1].contains("--kar-attested-by-stamp"),
|
|
source == KarSource::Memfd,
|
|
"{}",
|
|
starts[1]
|
|
);
|
|
// The sealed descriptor was reused, not copied again (one process held it the whole time).
|
|
assert!(!supervisor.try_wait().unwrap().is_some());
|
|
|
|
// SIGTERM drains and stops everything with status 0.
|
|
let new_engine = again["engine_pid"].as_u64().unwrap();
|
|
signal(u64::from(supervisor.id()), "TERM");
|
|
let status = wait_exit(&mut supervisor, Duration::from_secs(60))
|
|
.expect("the supervisor must exit after SIGTERM");
|
|
assert!(status.success(), "exit {status:?}\n{}", fixture.logs());
|
|
assert_eq!(fixture.status().unwrap()["phase"], "stopped");
|
|
for pid in [new_engine, gateway_pid, api_pid] {
|
|
assert!(!pid_alive(pid), "pid {pid} outlived the supervisor");
|
|
}
|
|
assert_eq!(
|
|
fixture.http_status("/ready"),
|
|
0,
|
|
"the API port must be closed"
|
|
);
|
|
// No child ever saw the Hugging Face token (the fake engine exits 3 if it does).
|
|
assert!(
|
|
!fs::read_to_string(paths.logs().join("engine.log"))
|
|
.unwrap()
|
|
.contains("leaked")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() {
|
|
lifecycle(KarSource::Memfd);
|
|
}
|
|
|
|
#[test]
|
|
fn supervisor_lifecycle_with_a_read_only_archive_file() {
|
|
lifecycle(KarSource::File);
|
|
}
|
|
|
|
#[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
|
|
|
|
fn up_options(
|
|
fixture: &Fixture,
|
|
bin_src: &Path,
|
|
cublas: &Path,
|
|
mtp: &Path,
|
|
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",
|
|
"rtx3080-16g",
|
|
"--mode",
|
|
"none",
|
|
]
|
|
.iter()
|
|
.map(|s| s.to_string())
|
|
.chain(extra.iter().map(|s| s.to_string()))
|
|
.collect();
|
|
match parse(
|
|
&args,
|
|
&Environment {
|
|
root: false,
|
|
home: Some(fixture.root.clone()),
|
|
var: &var,
|
|
},
|
|
)
|
|
.unwrap()
|
|
{
|
|
Command::Up(options) => options,
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
|
|
/// A host that passes the preflight, whatever machine runs the test.
|
|
fn healthy_context(opts: &UpOptions) -> Context {
|
|
let mut ctx = gather(opts, &|_| None);
|
|
let gpu = Gpu {
|
|
index: 0,
|
|
name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(),
|
|
driver: "617.42".into(),
|
|
vram_total_mib: 16384,
|
|
vram_free_mib: 15500,
|
|
sm: Some(86),
|
|
};
|
|
ctx.facts.os = "linux".into();
|
|
ctx.facts.arch = "x86_64".into();
|
|
ctx.facts.gpus = vec![gpu];
|
|
ctx.facts.memory = Memory {
|
|
total: 39 << 30,
|
|
available: 37 << 30,
|
|
swap_total: 0,
|
|
};
|
|
ctx.facts.proc_fd = true;
|
|
ctx.facts.memfd_ok = true;
|
|
ctx.facts.busy_ports.clear();
|
|
ctx.facts.libs.insert(
|
|
"libcuda.so.1".into(),
|
|
Some("/usr/lib/wsl/lib/libcuda.so.1".into()),
|
|
);
|
|
for key in ["assets", "state", "prefix"] {
|
|
ctx.facts.dirs.insert(
|
|
key.into(),
|
|
DirFact {
|
|
path: PathBuf::from("/x"),
|
|
free_bytes: Some(2 << 40),
|
|
fs_type: Some("ext4".into()),
|
|
},
|
|
);
|
|
}
|
|
ctx.needs.binary_has_sm86 = Some(true);
|
|
let profile = ctx.profile.as_ref().unwrap().clone();
|
|
ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs));
|
|
assert!(
|
|
!ctx.report.as_ref().unwrap().failed(),
|
|
"{}",
|
|
ctx.report.as_ref().unwrap().render()
|
|
);
|
|
ctx
|
|
}
|
|
|
|
fn fake_libraries(dir: &Path) {
|
|
fs::create_dir_all(dir).unwrap();
|
|
fs::write(dir.join("libcublas.so.12"), b"x").unwrap();
|
|
fs::write(dir.join("libcublasLt.so.12"), b"x").unwrap();
|
|
}
|
|
|
|
fn mtp_source(dir: &Path) {
|
|
fs::create_dir_all(dir).unwrap();
|
|
for name in MTP_FILES {
|
|
fs::write(dir.join(name), b"pack").unwrap();
|
|
}
|
|
}
|
|
|
|
fn count_calls(fixture: &Fixture, needle: &str) -> usize {
|
|
fs::read_to_string(fixture.fake_dir().join("calls.log"))
|
|
.unwrap_or_default()
|
|
.matches(needle)
|
|
.count()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn up_is_idempotent_resumable_and_never_rotates_secrets() {
|
|
let fixture = Fixture::new("up");
|
|
let bin_src = fixture.root.join("release/bin");
|
|
fixture.install_fake_binaries(&bin_src);
|
|
// The fakes find their shared state through the *installed* bin directory.
|
|
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
|
|
fake_libraries(&cublas);
|
|
mtp_source(&mtp);
|
|
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]);
|
|
let paths = fixture.dirs.paths();
|
|
|
|
// First run: everything is a todo, then everything exists.
|
|
let ctx = healthy_context(&opts);
|
|
let fs0 = gather_fs(&ctx).await;
|
|
let steps = plan_steps(&ctx, &fs0);
|
|
assert!(
|
|
steps
|
|
.iter()
|
|
.filter(|s| matches!(
|
|
s.id,
|
|
"binaries" | "secrets" | "model" | "kar" | "tokenizer" | "config" | "mtp-pack"
|
|
))
|
|
.all(|s| s.state.tag() == "todo")
|
|
);
|
|
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
|
|
for (what, file) in [
|
|
("binary", paths.bin("leleka-inference")),
|
|
("run config", paths.run_config()),
|
|
("env", paths.env_file()),
|
|
("api key", paths.api_key()),
|
|
("tokenizer", paths.tokenizer_dir()),
|
|
("mtp", paths.mtp_pack().join("experts.bin")),
|
|
("stamp", paths.stamps().join("model.json")),
|
|
] {
|
|
assert!(file.exists(), "{what}: {} missing", file.display());
|
|
}
|
|
assert_eq!(
|
|
fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777,
|
|
0o600
|
|
);
|
|
assert_eq!(
|
|
fs::metadata(paths.kar()).unwrap().permissions().mode() & 0o222,
|
|
0,
|
|
"the file-mode archive must have no write bits"
|
|
);
|
|
let config = RunConfig::read(&paths.run_config()).unwrap();
|
|
assert_eq!(config.profile.name, "rtx3080-16g");
|
|
let env_first = fs::read_to_string(paths.env_file()).unwrap();
|
|
assert!(
|
|
env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())),
|
|
"{env_first}"
|
|
);
|
|
assert_eq!(
|
|
(
|
|
count_calls(&fixture, "model fetch"),
|
|
count_calls(&fixture, "ensure-sharded-streamed"),
|
|
count_calls(&fixture, "api-key init")
|
|
),
|
|
(0, 1, 1),
|
|
"the archive step fetches and verifies the shards itself"
|
|
);
|
|
|
|
// Second run: the plan has nothing to do and no tool is invoked again.
|
|
let ctx = healthy_context(&opts);
|
|
let fs1 = gather_fs(&ctx).await;
|
|
let steps = plan_steps(&ctx, &fs1);
|
|
for step in &steps {
|
|
assert!(
|
|
matches!(step.state.tag(), "done" | "skip") || step.id == "preflight",
|
|
"{} is {:?} on a re-run",
|
|
step.id,
|
|
step.state
|
|
);
|
|
}
|
|
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
|
|
assert_eq!(
|
|
(
|
|
count_calls(&fixture, "model fetch"),
|
|
count_calls(&fixture, "model verify"),
|
|
count_calls(&fixture, "ensure-sharded-streamed"),
|
|
count_calls(&fixture, "extract-tokenizer")
|
|
),
|
|
(0, 0, 1, 1)
|
|
);
|
|
assert_eq!(
|
|
fs::read_to_string(paths.env_file()).unwrap(),
|
|
env_first,
|
|
"tokens must never rotate"
|
|
);
|
|
|
|
// Resumable: a lost archive is rebuilt, everything else is left alone.
|
|
fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap();
|
|
fs::remove_file(paths.kar()).unwrap();
|
|
let ctx = healthy_context(&opts);
|
|
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
|
|
assert_eq!(
|
|
steps.iter().find(|s| s.id == "kar").unwrap().state.tag(),
|
|
"todo"
|
|
);
|
|
assert_eq!(
|
|
steps.iter().find(|s| s.id == "model").unwrap().state.tag(),
|
|
"done"
|
|
);
|
|
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
|
|
assert_eq!(
|
|
(
|
|
count_calls(&fixture, "model fetch"),
|
|
count_calls(&fixture, "ensure-sharded-streamed")
|
|
),
|
|
(0, 2)
|
|
);
|
|
|
|
// --reverify forces the verification again.
|
|
let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]);
|
|
let ctx = healthy_context(&reverify);
|
|
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
|
|
assert_eq!(
|
|
steps.iter().find(|s| s.id == "model").unwrap().state.tag(),
|
|
"todo"
|
|
);
|
|
let _ = FsState::default();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() {
|
|
let fixture = Fixture::new("trust");
|
|
let bin_src = fixture.root.join("release/bin");
|
|
fixture.install_fake_binaries(&bin_src);
|
|
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
|
|
fake_libraries(&cublas);
|
|
mtp_source(&mtp);
|
|
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &["--trust-archive"]);
|
|
let paths = fixture.dirs.paths();
|
|
// An archive of the pinned length with its provenance sidecar, as left by an earlier build.
|
|
fs::create_dir_all(&fixture.dirs.assets).unwrap();
|
|
fs::File::create(paths.kar())
|
|
.unwrap()
|
|
.set_len(55_295_529_472)
|
|
.unwrap();
|
|
fs::write(paths.kar_provenance(), "{}").unwrap();
|
|
let ctx = healthy_context(&opts);
|
|
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
|
|
let kar = steps.iter().find(|s| s.id == "kar").unwrap();
|
|
assert_eq!(kar.state.tag(), "todo");
|
|
assert!(
|
|
kar.state.why().contains("--trust-archive"),
|
|
"{:?}",
|
|
kar.state
|
|
);
|
|
assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0);
|
|
assert_eq!(
|
|
(
|
|
count_calls(&fixture, "model fetch"),
|
|
count_calls(&fixture, "model verify"),
|
|
count_calls(&fixture, "ensure-sharded-streamed")
|
|
),
|
|
(1, 1, 0)
|
|
);
|
|
assert!(paths.stamps().join("kar.json").exists() && paths.stamps().join("model.json").exists());
|
|
// Without the flag the same archive would be re-verified by the real tool.
|
|
let strict = healthy_context(&up_options(
|
|
&fixture,
|
|
&bin_src,
|
|
&cublas,
|
|
&mtp,
|
|
&["--reverify"],
|
|
));
|
|
let steps = plan_steps(&strict, &gather_fs(&strict).await);
|
|
assert!(
|
|
!steps
|
|
.iter()
|
|
.find(|s| s.id == "kar")
|
|
.unwrap()
|
|
.state
|
|
.why()
|
|
.contains("--trust-archive")
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() {
|
|
let fixture = Fixture::new("wrongkar");
|
|
let bin_src = fixture.root.join("release/bin");
|
|
fixture.install_fake_binaries(&bin_src);
|
|
let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src"));
|
|
fake_libraries(&cublas);
|
|
mtp_source(&mtp);
|
|
let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]);
|
|
// A pre-existing archive of the wrong length: the fake `ensure` reuses it, the size gate must object.
|
|
fs::create_dir_all(&fixture.dirs.assets).unwrap();
|
|
fs::write(fixture.dirs.paths().kar(), b"short").unwrap();
|
|
let ctx = healthy_context(&opts);
|
|
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
|
|
let error = run_up(&ctx, &steps).await.unwrap_err();
|
|
assert!(error.contains("engine only admits the pinned"), "{error}");
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------------------------------------
|
|
// the command line
|
|
|
|
#[test]
|
|
fn dry_run_prints_the_plan_and_changes_nothing() {
|
|
let fixture = Fixture::new("dry");
|
|
let bin = fixture.root.join("bin");
|
|
fixture.install_fake_binaries(&bin);
|
|
let output = Process::new(LELEKA)
|
|
.args([
|
|
"up",
|
|
"--dry-run",
|
|
"--profile",
|
|
"rtx5090-32g",
|
|
"--mode",
|
|
"foreground",
|
|
"--assets",
|
|
])
|
|
.arg(&fixture.dirs.assets)
|
|
.arg("--state-dir")
|
|
.arg(&fixture.dirs.state)
|
|
.arg("--prefix")
|
|
.arg(&fixture.dirs.prefix)
|
|
.arg("--bin-src")
|
|
.arg(&bin)
|
|
.output()
|
|
.unwrap();
|
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
assert!(
|
|
stdout.contains("plan:") && stdout.contains("engine command the service runs:"),
|
|
"{stdout}"
|
|
);
|
|
assert!(
|
|
stdout.contains("--kar-archive-fd {FD}")
|
|
&& stdout.contains("nothing was changed (--dry-run)"),
|
|
"{stdout}"
|
|
);
|
|
assert!(
|
|
stderr.contains("preflight (profile rtx5090-32g)"),
|
|
"{stderr}"
|
|
);
|
|
for path in [
|
|
&fixture.dirs.assets,
|
|
&fixture.dirs.state,
|
|
&fixture.dirs.prefix,
|
|
] {
|
|
assert!(!path.exists(), "--dry-run created {}", path.display());
|
|
}
|
|
// --json is one parseable document with the steps.
|
|
let output = Process::new(LELEKA)
|
|
.args([
|
|
"up",
|
|
"--dry-run",
|
|
"--json",
|
|
"--profile",
|
|
"rtx5090-32g",
|
|
"--mode",
|
|
"foreground",
|
|
"--assets",
|
|
])
|
|
.arg(&fixture.dirs.assets)
|
|
.arg("--state-dir")
|
|
.arg(&fixture.dirs.state)
|
|
.arg("--prefix")
|
|
.arg(&fixture.dirs.prefix)
|
|
.arg("--bin-src")
|
|
.arg(&bin)
|
|
.output()
|
|
.unwrap();
|
|
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
|
assert_eq!(json["profile"], "rtx5090-32g");
|
|
assert!(
|
|
json["steps"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|s| s["id"] == "kar")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
|
|
let fixture = Fixture::new("preflight-fail");
|
|
let bin = fixture.root.join("bin");
|
|
fixture.install_fake_binaries(&bin);
|
|
// The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check.
|
|
let output = Process::new(LELEKA)
|
|
.args([
|
|
"up",
|
|
"--profile",
|
|
"rtx5090-32g",
|
|
"--mode",
|
|
"none",
|
|
"--assets",
|
|
])
|
|
.arg(&fixture.dirs.assets)
|
|
.arg("--state-dir")
|
|
.arg(&fixture.dirs.state)
|
|
.arg("--prefix")
|
|
.arg(&fixture.dirs.prefix)
|
|
.arg("--bin-src")
|
|
.arg(&bin)
|
|
.output()
|
|
.unwrap();
|
|
assert_eq!(output.status.code(), Some(1));
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
assert!(
|
|
stderr.contains("[FAIL]") && stderr.contains("fix:"),
|
|
"{stderr}"
|
|
);
|
|
assert!(stderr.contains("nothing was changed"), "{stderr}");
|
|
for path in [
|
|
&fixture.dirs.assets,
|
|
&fixture.dirs.state,
|
|
&fixture.dirs.prefix,
|
|
] {
|
|
assert!(
|
|
!path.exists(),
|
|
"a failed preflight created {}",
|
|
path.display()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn profiles_and_usage_commands() {
|
|
let list = Process::new(LELEKA).arg("profiles").output().unwrap();
|
|
let text = String::from_utf8_lossy(&list.stdout);
|
|
assert!(
|
|
text.contains("rtx5090-32g") && text.contains("rtx3080-16g"),
|
|
"{text}"
|
|
);
|
|
let show = Process::new(LELEKA)
|
|
.args(["profiles", "show", "rtx3080-16g"])
|
|
.output()
|
|
.unwrap();
|
|
let profile: Profile = serde_json::from_slice(&show.stdout).unwrap();
|
|
assert_eq!(profile.context_tokens, 8192);
|
|
let bad = Process::new(LELEKA)
|
|
.args(["up", "--bogus"])
|
|
.output()
|
|
.unwrap();
|
|
assert_eq!(bad.status.code(), Some(2));
|
|
assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option"));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ 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");
|
|
}
|
|
}
|