The Original serve Load never admitted an expert source (the serve smokes call load_resident_expert_source themselves), so the stack's prompt arena failed with InputRead on the first real Load through leleka-inference. leleka-inference gains --expert-source resident|mapped; backend.rs admits the chosen bank before the driver. leleka up passes it per profile and the supervisor stops waiting when the load operation is FAILED/INDETERMINATE. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
890 lines
30 KiB
Rust
890 lines
30 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 sealed descriptor was reused, not copied again (one process held it the whole time).
|
|
assert!(!supervisor.try_wait().unwrap().is_some());
|
|
|
|
// SIGTERM drains and stops everything with status 0.
|
|
let new_engine = again["engine_pid"].as_u64().unwrap();
|
|
signal(u64::from(supervisor.id()), "TERM");
|
|
let status = wait_exit(&mut supervisor, Duration::from_secs(60))
|
|
.expect("the supervisor must exit after SIGTERM");
|
|
assert!(status.success(), "exit {status:?}\n{}", fixture.logs());
|
|
assert_eq!(fixture.status().unwrap()["phase"], "stopped");
|
|
for pid in [new_engine, gateway_pid, api_pid] {
|
|
assert!(!pid_alive(pid), "pid {pid} outlived the supervisor");
|
|
}
|
|
assert_eq!(
|
|
fixture.http_status("/ready"),
|
|
0,
|
|
"the API port must be closed"
|
|
);
|
|
// No child ever saw the Hugging Face token (the fake engine exits 3 if it does).
|
|
assert!(
|
|
!fs::read_to_string(paths.logs().join("engine.log"))
|
|
.unwrap()
|
|
.contains("leaked")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() {
|
|
lifecycle(KarSource::Memfd);
|
|
}
|
|
|
|
#[test]
|
|
fn supervisor_lifecycle_with_a_read_only_archive_file() {
|
|
lifecycle(KarSource::File);
|
|
}
|
|
|
|
#[test]
|
|
fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() {
|
|
let fixture = Fixture::new("fail");
|
|
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
|
|
fs::create_dir_all(fixture.fake_dir()).unwrap();
|
|
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
|
|
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
|
profile.kar_source = KarSource::File;
|
|
let config = fixture.write_state(profile);
|
|
fs::create_dir_all(&fixture.dirs.assets).unwrap();
|
|
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
|
|
let mut supervisor = start_supervisor(&fixture, &config, None);
|
|
let status =
|
|
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
|
|
assert_eq!(status.code(), Some(1));
|
|
let state = fixture.status().unwrap();
|
|
assert_eq!(state["phase"], "failed");
|
|
let message = state["message"].as_str().unwrap();
|
|
assert!(
|
|
message.contains("engine") && message.contains("exited"),
|
|
"{message}"
|
|
);
|
|
let output = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap();
|
|
assert!(output.contains("fatal:"), "{output}");
|
|
// The gateway started for the load is not left behind.
|
|
assert!(state["gateway_pid"].is_null() || !pid_alive(state["gateway_pid"].as_u64().unwrap()));
|
|
}
|
|
|
|
#[test]
|
|
fn a_refused_load_fails_fast_and_shows_the_engine_log() {
|
|
// The real engine stays alive when its load fails; only the operation record says so.
|
|
let fixture = Fixture::new("refused");
|
|
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
|
|
fs::create_dir_all(fixture.fake_dir()).unwrap();
|
|
fs::write(fixture.fake_dir().join("fail-load"), "").unwrap();
|
|
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
|
profile.kar_source = KarSource::File;
|
|
let config = fixture.write_state(profile);
|
|
fs::create_dir_all(&fixture.dirs.assets).unwrap();
|
|
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
|
|
let started = Instant::now();
|
|
let mut supervisor = start_supervisor(&fixture, &config, None);
|
|
let status =
|
|
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
|
|
assert_eq!(status.code(), Some(1));
|
|
assert!(
|
|
started.elapsed() < Duration::from_secs(40),
|
|
"a refused load must not wait for the load timeout"
|
|
);
|
|
let state = fixture.status().unwrap();
|
|
let message = state["message"].as_str().unwrap();
|
|
assert!(
|
|
message.contains("refused the load") && message.contains("BackendUnavailable"),
|
|
"{message}"
|
|
);
|
|
// The engine it started is gone.
|
|
let engine_pid = fs::read_to_string(fixture.fake_dir().join("engine.pid"))
|
|
.unwrap()
|
|
.trim()
|
|
.parse()
|
|
.unwrap();
|
|
assert!(!pid_alive(engine_pid));
|
|
}
|
|
|
|
#[test]
|
|
fn a_broken_configuration_is_exit_code_two_with_a_clear_message() {
|
|
let fixture = Fixture::new("badconfig");
|
|
fs::create_dir_all(&fixture.root).unwrap();
|
|
let missing = fixture.root.join("nope.json");
|
|
let output = Process::new(LELEKA)
|
|
.arg("run")
|
|
.arg("--config")
|
|
.arg(&missing)
|
|
.output()
|
|
.unwrap();
|
|
assert_eq!(output.status.code(), Some(2));
|
|
let text = String::from_utf8_lossy(&output.stderr);
|
|
assert!(text.contains("run `leleka up` first"), "{text}");
|
|
// Weak tokens are refused before anything starts.
|
|
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
|
|
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
|
profile.kar_source = KarSource::File;
|
|
let config = fixture.write_state(profile);
|
|
fs::write(
|
|
fixture.dirs.paths().env_file(),
|
|
format!("{RUNTIME_TOKEN_ENV}=short\n{GATEWAY_TOKEN_ENV}=short\n"),
|
|
)
|
|
.unwrap();
|
|
let output = Process::new(LELEKA)
|
|
.arg("run")
|
|
.arg("--config")
|
|
.arg(&config)
|
|
.output()
|
|
.unwrap();
|
|
assert_eq!(output.status.code(), Some(2));
|
|
assert!(String::from_utf8_lossy(&output.stderr).contains("32..4096 printable ASCII"));
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------------------------------------
|
|
// the `up` flow
|
|
|
|
fn up_options(
|
|
fixture: &Fixture,
|
|
bin_src: &Path,
|
|
cublas: &Path,
|
|
mtp: &Path,
|
|
extra: &[&str],
|
|
) -> UpOptions {
|
|
let var = |_: &str| None;
|
|
let args: Vec<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"));
|
|
}
|