Files
leleka/crates/deploy/src/plan.rs
T
Pavlo Ratushnyi e64a3da1b7 Merge branch 'claude/platform' into claude/port-gpu-bringup
# Conflicts:
#	crates/deploy/src/app.rs
#	crates/deploy/src/cli.rs
2026-10-25 14:06:50 +01:00

1195 lines
40 KiB
Rust

//! The deployment plan: what `up` would do, derived from what is already on the machine.
//!
//! `gather` reads the host (no writes, no hashing of model files, no network). `plan_steps` is pure over the
//! gathered state, so a fresh machine, a half-finished run and a finished deployment are all unit-tested.
//! `--dry-run` prints this plan; execution (`steps.rs`) walks the same list and runs only the `Todo` entries,
//! which is what makes a re-run idempotent and a crashed run resumable.
use crate::{
cli::{ModeChoice, UpOptions},
config::{KarArg, RunConfig},
facts::{Facts, ProbeRequest, probe},
layout::{BINARIES, MANIFEST, MTP_FILES, Paths, missing_asset_bytes},
manifest::Manifest,
preflight::{ExpertProfileState, Needs, Report, evaluate},
profile::{ARCHIVE_BYTES, KarSource, Profile, resolve},
units::UnitScope,
};
use serde::Serialize;
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
pub const CUBLAS_VERSION: &str = "12.9.1.4";
pub const CUBLAS_URL: &str = "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz";
pub const CUBLAS_SHA256: &str = "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057";
pub const CUBLAS_BYTES: u64 = 933_611_504;
pub const EXPERT_PROFILE_SHA256: &str =
"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
Systemd(UnitScopeTag),
Foreground,
/// Prepare everything, start nothing.
None,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitScopeTag {
System,
User,
}
impl UnitScopeTag {
pub fn scope(self) -> UnitScope {
match self {
UnitScopeTag::System => UnitScope::System,
UnitScopeTag::User => UnitScope::User,
}
}
}
impl Mode {
pub fn label(self) -> &'static str {
match self {
Mode::Systemd(UnitScopeTag::System) => "systemd (system unit)",
Mode::Systemd(UnitScopeTag::User) => "systemd (user unit)",
Mode::Foreground => "foreground",
Mode::None => "prepare only",
}
}
}
/// `--mode auto`: root with systemd gets a system unit, a user with a systemd user session a user unit, everything
/// else (WSL without systemd, containers) runs in the foreground.
pub fn resolve_mode(choice: ModeChoice, facts: &Facts, user_session: bool) -> Mode {
match choice {
ModeChoice::System => Mode::Systemd(UnitScopeTag::System),
ModeChoice::User => Mode::Systemd(UnitScopeTag::User),
ModeChoice::Foreground => Mode::Foreground,
ModeChoice::None => Mode::None,
ModeChoice::Auto => {
if facts.systemd_system && facts.tool("systemctl") {
if facts.root {
Mode::Systemd(UnitScopeTag::System)
} else if user_session {
Mode::Systemd(UnitScopeTag::User)
} else {
Mode::Foreground
}
} else {
Mode::Foreground
}
}
}
}
#[derive(Debug)]
pub struct Context {
pub opts: UpOptions,
pub facts: Facts,
pub paths: Paths,
pub bin_src: PathBuf,
pub manifest: Option<Result<Manifest, String>>,
pub profile: Result<Profile, String>,
pub mode: Mode,
pub service_user: String,
pub config: Option<RunConfig>,
pub report: Option<Report>,
pub needs: Needs,
}
fn current_bin_dir() -> PathBuf {
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf))
.unwrap_or_else(|| PathBuf::from("."))
}
pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option<ExpertProfileState> {
let relative = profile.expert_profile.as_ref()?;
let path = assets.join(relative);
let Ok(bytes) = std::fs::read(&path) else {
return Some(ExpertProfileState::Absent);
};
if bytes.len() > 16 << 20 {
return Some(ExpertProfileState::WrongDigest);
}
let expected = profile
.expert_profile_sha256
.as_deref()
.unwrap_or(EXPERT_PROFILE_SHA256);
Some(if sha256_hex(&bytes) == expected {
ExpertProfileState::Valid
} else {
ExpertProfileState::WrongDigest
})
}
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
/// Is the supervisor of this state directory alive? (`run/status.json` names its pid.)
pub fn service_running(paths: &Paths) -> bool {
let Ok(text) = std::fs::read_to_string(paths.status_file()) else {
return false;
};
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
return false;
};
let pid = value.get("supervisor_pid").and_then(|v| v.as_u64());
let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or("");
matches!(pid, Some(pid) if process_alive(pid))
&& !matches!(phase, "stopped" | "failed")
}
#[cfg(not(windows))]
fn process_alive(pid: u64) -> bool {
Path::new(&format!("/proc/{pid}")).exists()
}
#[cfg(windows)]
fn process_alive(pid: u64) -> bool {
u32::try_from(pid).is_ok_and(crate::winsys::process_alive)
}
fn user_session_available(var: &dyn Fn(&str) -> Option<String>) -> bool {
var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists())
}
pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context {
let paths = opts.dirs.paths();
let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir);
let installed = paths.bin_dir();
// Probe the source of the binaries, or the installed copy when the source has none (re-run after install).
let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) {
bin_src.clone()
} else {
installed.clone()
};
let mut extra_library_dirs: Vec<PathBuf> = Vec::new();
if let Some(dir) = &opts.cublas_dir {
extra_library_dirs.push(dir.clone());
} else {
extra_library_dirs.push(paths.cublas_dir());
}
let ports: Vec<u16> = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon]
.iter()
.filter_map(|p| p.rsplit(':').next()?.parse().ok())
.collect();
let request = ProbeRequest {
dirs: vec![
("assets".into(), opts.dirs.assets.clone()),
("state".into(), opts.dirs.state.clone()),
("prefix".into(), opts.dirs.prefix.clone()),
],
ports,
binary_dir: Some(binary_dir.clone()),
binaries: BINARIES.iter().map(|b| b.to_string()).collect(),
extra_library_dirs,
};
let facts = probe(&request);
let manifest = Manifest::find(&binary_dir);
let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu);
let mut profile = resolve(opts.profile.as_deref(), gpu);
if let Ok(p) = &mut profile {
if let Some(gib) = opts.gpu_budget_gib {
p.gpu_budget_bytes = gib << 30;
}
if let Some(tokens) = opts.context_tokens {
p.context_tokens = tokens;
}
if let Err(message) = p.validate() {
profile = Err(message);
}
}
let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto {
ModeChoice::Foreground
} else {
opts.mode
};
let mode = resolve_mode(choice, &facts, user_session_available(var));
let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) {
opts.service_user
.clone()
.unwrap_or_else(|| "leleka".to_owned())
} else {
var("USER")
.or_else(|| var("LOGNAME"))
.unwrap_or_else(|| "root".to_owned())
};
let (shards, kar) = missing_asset_bytes(&paths);
let installed_same_dir = same_dir(&bin_src, &installed);
let mut needs = Needs {
gpu_index: opts.gpu,
assets_dir: opts.dirs.assets.clone(),
state_dir: opts.dirs.state.clone(),
prefix_dir: opts.dirs.prefix.clone(),
// Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not).
shard_bytes_missing: if opts.fetch && facts.os != "windows" { shards } else { 0 },
kar_bytes_missing: if opts.fetch && facts.os != "windows" { kar } else { 0 },
install_binaries: !installed_same_dir,
may_install_cublas: opts.install_cublas && opts.cublas_dir.is_none() && facts.os != "windows",
cublas_download_bytes: CUBLAS_BYTES,
wants_systemd: matches!(mode, Mode::Systemd(_)),
service_ports: vec![
("api".into(), port_of(&opts.ports.api)),
("engine".into(), port_of(&opts.ports.engine)),
("gateway".into(), port_of(&opts.ports.daemon)),
],
require_binaries: true,
binary_has_sm86: manifest
.as_ref()
.and_then(|m| m.as_ref().ok())
.map(Manifest::has_sm86),
service_running: service_running(&paths),
kar_fd_inherited: opts.kar_fd.is_some(),
api_bind_open: crate::config::probe_address(&opts.ports.api)
.is_some_and(|a| !a.ip().is_loopback()),
expert_profile: None,
resources: None,
};
let (config, report) = match &mut profile {
Ok(p) => {
needs.expert_profile = expert_profile_state(p, &opts.dirs.assets);
let mut engine_env = BTreeMap::new();
let base_profile = p.clone();
// An inherited sealed archive is already resident: it is not part of what the engine still needs from the host.
let planned_host = if opts.kar_fd.is_some() { crate::resources::with_resident_archive(&facts) } else { facts.clone() };
let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset);
crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some());
needs.resources = Some(resources);
if needs.expert_profile == Some(ExpertProfileState::Valid)
&& let Some(relative) = &p.expert_profile
{
engine_env.insert(
"LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".to_owned(),
"auto".to_owned(),
);
engine_env.insert(
"LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE".to_owned(),
opts.dirs.assets.join(relative).display().to_string(),
);
}
let mut config = RunConfig::new(
&opts.dirs,
opts.ports.clone(),
opts.gpu,
p.clone(),
engine_env,
);
config.preset = opts.preset;
config.base_profile = Some(base_profile);
let report = evaluate(&facts, p, &needs);
(Some(config), Some(report))
}
Err(_) => (None, None),
};
Context {
opts: opts.clone(),
facts,
paths,
bin_src,
manifest,
profile,
mode,
service_user,
config,
report,
needs,
}
}
fn port_of(address: &str) -> u16 {
address
.rsplit(':')
.next()
.and_then(|p| p.parse().ok())
.unwrap_or(0)
}
fn same_dir(a: &Path, b: &Path) -> bool {
match (a.canonicalize(), b.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => a == b,
}
}
/// What exists on disk now, reduced to the facts the plan needs.
#[derive(Clone, Debug, Default)]
pub struct FsState {
pub dirs_exist: bool,
pub binaries_current: bool,
pub binaries_source_ok: bool,
pub cublas_ready: bool,
pub secrets_present: bool,
pub shards_stamp_ok: bool,
pub kar_stamp_ok: bool,
/// The archive file has the pinned length and its provenance sidecar exists.
pub kar_present: bool,
pub mtp_present: bool,
pub tokenizer_present: bool,
pub configs_current: bool,
pub unit_current: bool,
pub service_ready: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "state", content = "why", rename_all = "lowercase")]
pub enum StepState {
Done(String),
Todo(String),
Skip(String),
Blocked(String),
}
impl StepState {
pub fn tag(&self) -> &'static str {
match self {
StepState::Done(_) => "done",
StepState::Todo(_) => "todo",
StepState::Skip(_) => "skip",
StepState::Blocked(_) => "BLOCKED",
}
}
pub fn why(&self) -> &str {
match self {
StepState::Done(s)
| StepState::Todo(s)
| StepState::Skip(s)
| StepState::Blocked(s) => s,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct Step {
pub id: &'static str,
pub title: String,
#[serde(flatten)]
pub state: StepState,
pub commands: Vec<String>,
}
fn step(id: &'static str, title: &str, state: StepState, commands: Vec<String>) -> Step {
Step {
id,
title: title.to_owned(),
state,
commands,
}
}
pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec<Step> {
let paths = &ctx.paths;
let opts = &ctx.opts;
let sn = paths.bin("strata-next").display().to_string();
let manifest_name = MANIFEST;
let windows = ctx.facts.os == "windows";
let mut steps = Vec::new();
let pre_state = match &ctx.report {
Some(report) if report.failed() => StepState::Blocked(format!(
"{} check(s) failed",
report.count(crate::preflight::Level::Fail)
)),
Some(report) => StepState::Todo(format!(
"{} warning(s)",
report.count(crate::preflight::Level::Warn)
)),
None => StepState::Blocked(ctx.profile.as_ref().err().cloned().unwrap_or_default()),
};
steps.push(step(
"preflight",
"host checks",
pre_state,
vec![if windows {
"nvidia-smi.exe, GlobalMemoryStatusEx, GetDiskFreeSpaceEx, DLL search, loopback ports".into()
} else {
"nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create".into()
}],
));
steps.push(step(
"layout",
"create directories",
if fs.dirs_exist {
StepState::Done("present".into())
} else {
StepState::Todo("create state (0700), logs, run, stamps, assets".into())
},
vec![format!(
"mkdir -p {} {} {}",
opts.dirs.prefix.display(),
opts.dirs.state.display(),
opts.dirs.assets.display()
)],
));
steps.push(step(
"binaries",
"install the six runtime binaries",
if !fs.binaries_source_ok {
StepState::Blocked(format!(
"not all of {} are in {} or {}",
BINARIES.join(", "),
ctx.bin_src.display(),
paths.bin_dir().display()
))
} else if fs.binaries_current {
StepState::Done(format!("{} is current", paths.bin_dir().display()))
} else {
StepState::Todo(format!(
"copy from {} (SHA-256 checked against MANIFEST.json when present)",
ctx.bin_src.display()
))
},
vec![format!(
"install {{{}}} -> {}",
BINARIES.join(","),
paths.bin_dir().display()
)],
));
let cublas_cmd = vec![
format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"),
format!(
"tar -xJf libcublas-{CUBLAS_VERSION}.tar.xz -> {}",
paths.cublas_dir().display()
),
];
steps.push(step(
"cublas",
"CUDA 12 cuBLAS for the PLE batch GEMM",
if fs.cublas_ready {
StepState::Done(if windows {
"cublas64_12.dll and cublasLt64_12.dll found".into()
} else {
"libcublas.so.12 and libcublasLt.so.12 found".into()
})
} else if windows {
StepState::Blocked(
"cublas64_12.dll and cublasLt64_12.dll (CUDA 12.x) were not found; pass --cublas-dir DIR that holds them (a CUDA 12 toolkit's bin folder, or the NVIDIA cuBLAS 12 redistributable)".into(),
)
} else if opts.cublas_dir.is_some() {
StepState::Blocked(
"--cublas-dir does not contain libcublas.so.12 and libcublasLt.so.12".into(),
)
} else if opts.install_cublas {
StepState::Todo(format!(
"download the pinned {CUBLAS_VERSION} redistributable ({} MiB)",
CUBLAS_BYTES >> 20
))
} else {
StepState::Blocked("missing and --no-install-cublas was given".into())
},
if windows { Vec::new() } else { cublas_cmd },
));
steps.push(step(
"secrets",
"service tokens and API key",
if fs.secrets_present {
StepState::Done("runtime.env and api-key exist (never rotated)".into())
} else {
StepState::Todo("generate two tokens (0600) and run `strata-next api-key init`".into())
},
vec![format!(
"{sn} api-key init --file {}",
paths.api_key().display()
)],
));
let trusted = opts.trust_archive && fs.kar_present;
let kar_state = if windows {
if fs.kar_present {
StepState::Done(format!("{} bytes with its provenance file (the engine checks SHA-256 and CRCs at each load)", ARCHIVE_BYTES))
} else {
StepState::Blocked(format!(
"{} (pinned length {ARCHIVE_BYTES}) and its .provenance.json must already be on the model volume; the Windows tool does not build the archive (build it in WSL and copy it, see docs/windows.md)",
paths.kar().display()
))
}
} else if fs.kar_stamp_ok && !opts.reverify {
StepState::Done(format!("{} bytes, verified earlier", ARCHIVE_BYTES))
} else if trusted {
StepState::Todo(
"accept the existing archive without the strict re-derivation (--trust-archive); the engine verifies its SHA-256 and every CRC at each load"
.into(),
)
} else if !opts.fetch {
StepState::Blocked("--no-fetch given but the archive is missing or unverified".into())
} else {
StepState::Todo(
"build the level-2 KAR archive (bounded memory, hours on a first run) or re-verify the existing one (strict, tens of minutes), then stamp it"
.into(),
)
};
let kar_runs_tool = matches!(kar_state, StepState::Todo(_)) && !trusted;
let model_cmds = vec![
format!(
"{sn} model fetch {manifest_name} --output {}",
paths.model_dir().display()
),
format!(
"{sn} model verify {manifest_name} --output {}",
paths.model_dir().display()
),
];
steps.push(step(
"model",
"fetch and verify the two IQ3_S GGUF shards",
if windows {
if ctx.needs.shard_bytes_missing == 0 && windows_shards_present(paths) {
StepState::Done("both shards are present with the pinned sizes (the engine hashes them at each load, or skips it with a verification stamp)".into())
} else {
StepState::Blocked(format!(
"the two shards must already be in {} with their pinned sizes (the Windows tool does not download or build; copy them from the WSL volume, see docs/windows.md)",
paths.model_dir().display()
))
}
} else if fs.shards_stamp_ok && !opts.reverify {
StepState::Done(
"verified earlier; sizes and mtimes unchanged (--reverify hashes again)".into(),
)
} else if kar_runs_tool {
StepState::Todo(
"downloaded and verified inside the archive step (ensure-sharded-streamed fetches and verifies the shards first)"
.into(),
)
} else if !opts.fetch {
if fs.shards_stamp_ok {
StepState::Todo("--no-fetch: verify only".into())
} else {
StepState::Blocked(
"--no-fetch given but the shards are not verified yet; run without --no-fetch"
.into(),
)
}
} else {
StepState::Todo(format!(
"{} still to download; resumable, SHA-256 of 83.6 GB",
gib_text(ctx.needs.shard_bytes_missing)
))
},
if windows { Vec::new() } else { model_cmds },
));
let kar_cmd = vec![format!(
"{sn} model ensure-sharded-streamed {manifest_name} --source-dir {} --output {} --levels 2",
paths.model_dir().display(),
paths.kar().display()
)];
steps.push(step(
"kar",
"KAR level-2 archive (+ provenance)",
kar_state,
if windows { Vec::new() } else { kar_cmd },
));
steps.push(step(
"mtp-pack",
"MTP draft pack (data/mtp-rt)",
if let Some(src) = &opts.mtp_pack {
if fs.mtp_present { StepState::Done("present; --mtp-pack ignored".into()) } else { StepState::Todo(format!("import from {}", src.display())) }
} else if fs.mtp_present {
StepState::Done(format!("{} present", paths.mtp_pack().display()))
} else {
StepState::Blocked(format!("{} is missing and no --mtp-pack was given; the pack ({}) has no automated producer yet", paths.mtp_pack().display(), MTP_FILES.join(", ")))
},
vec![format!("copy/unpack -> {}", paths.mtp_pack().display())],
));
steps.push(step(
"tokenizer",
"tokenizer assets for the API",
if fs.tokenizer_present {
StepState::Done("present".into())
} else {
StepState::Todo("extract from shard 1".into())
},
vec![format!(
"{sn} model extract-tokenizer {} --output {}",
paths.shard(0).display(),
paths.tokenizer_root().display()
)],
));
steps.push(step(
"config",
"run configuration, gateway and API configs, environment file",
if fs.configs_current {
StepState::Done("up to date".into())
} else {
StepState::Todo(
"write leleka.json, daemon.json, strata.json, profile.json, runtime.env".into(),
)
},
vec![format!(
"write {}/{{leleka,daemon,strata,profile}}.json runtime.env",
opts.dirs.state.display()
)],
));
match ctx.mode {
Mode::Systemd(scope) => {
steps.push(step(
"service",
"systemd unit",
if fs.unit_current {
StepState::Done("installed and enabled".into())
} else {
StepState::Todo(format!(
"write {} unit, daemon-reload, enable",
if scope == UnitScopeTag::System {
"system"
} else {
"user"
}
))
},
vec![format!(
"systemctl {}enable {}",
if scope == UnitScopeTag::User {
"--user "
} else {
""
},
paths.unit_name()
)],
));
steps.push(step(
"start",
"start the service",
if fs.service_ready {
StepState::Done("already ready".into())
} else {
StepState::Todo(
"systemctl start (first start copies the archive and loads the model)"
.into(),
)
},
vec![format!(
"systemctl {}start {}",
if scope == UnitScopeTag::User {
"--user "
} else {
""
},
paths.unit_name()
)],
));
}
Mode::Foreground => {
steps.push(step(
"service",
"systemd unit",
StepState::Skip("foreground mode".into()),
vec![],
));
steps.push(step(
"start",
"run the supervisor in this terminal",
if fs.service_ready {
StepState::Done("a supervisor is already ready".into())
} else {
StepState::Todo("leleka run (Ctrl-C drains and stops)".into())
},
vec![format!(
"{} run --config {}",
paths.bin("leleka").display(),
paths.run_config().display()
)],
));
}
Mode::None => {
steps.push(step(
"service",
"systemd unit",
StepState::Skip("--mode none".into()),
vec![],
));
steps.push(step(
"start",
"start the service",
StepState::Skip("--mode none".into()),
vec![],
));
}
}
steps.push(step(
"ready",
"wait for readiness",
if matches!(ctx.mode, Mode::None) {
StepState::Skip("--mode none".into())
} else if fs.service_ready {
StepState::Done("ready".into())
} else {
StepState::Todo(format!(
"poll {} /ready for up to {} s",
opts.ports.api, opts.timeout_s
))
},
vec![format!("GET http://{}/ready", opts.ports.api)],
));
steps
}
/// Both shards exist with their pinned sizes.
fn windows_shards_present(paths: &Paths) -> bool {
crate::profile::SHARD_BYTES
.iter()
.enumerate()
.all(|(index, expected)| std::fs::metadata(paths.shard(index)).is_ok_and(|m| m.len() == *expected))
}
fn gib_text(bytes: u64) -> String {
format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
}
/// A human rendering of the plan, with the engine command the service will run.
pub fn render_plan(ctx: &Context, steps: &[Step]) -> String {
let mut out = String::new();
out.push_str("plan:\n");
for (index, step) in steps.iter().enumerate() {
out.push_str(&format!(
" {:>2}. [{:7}] {} - {}\n",
index + 1,
step.state.tag(),
step.title,
step.state.why()
));
if matches!(step.state, StepState::Todo(_) | StepState::Blocked(_)) {
for command in &step.commands {
out.push_str(&format!(" $ {command}\n"));
}
}
}
if let Some(config) = &ctx.config {
let kar = match config.profile.kar_source {
KarSource::Memfd => KarArg::Fd,
KarSource::File => KarArg::File,
};
out.push_str(&format!(
"engine command the service runs:\n {} {}\n",
ctx.paths.bin("leleka-inference").display(),
config.engine_args(kar).join(" ")
));
out.push_str(&format!(
" (profile {}: budget {:.1} GiB, context {}, KAR {})\n",
config.profile.name,
config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64,
config.profile.context_tokens,
config.profile.kar_source.as_str()
));
let env = config.engine_environment();
if !env.is_empty() {
out.push_str(&format!(
" engine environment: {}\n",
env.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect::<Vec<_>>()
.join(" ")
));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
cli::{Command, Environment, parse},
facts::{Gpu, Memory},
layout::Dirs,
};
fn options(extra: &[&str]) -> UpOptions {
let var = |_: &str| None;
let mut args: Vec<String> = vec![
"up".into(),
"--assets".into(),
"/data/leleka".into(),
"--state-dir".into(),
"/var/lib/leleka/state".into(),
"--prefix".into(),
"/opt/leleka".into(),
];
args.extend(extra.iter().map(|s| s.to_string()));
match parse(
&args,
&Environment {
root: true,
home: None,
var: &var,
},
)
.unwrap()
{
Command::Up(options) => options,
_ => unreachable!(),
}
}
fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context {
let paths = opts.dirs.paths();
let gpu = Gpu {
index: 0,
name: gpu_name.into(),
driver: "595.99.02".into(),
vram_total_mib: if sm == 120 { 32607 } else { 16384 },
vram_free_mib: if sm == 120 { 32000 } else { 15500 },
sm: Some(sm),
};
let mut facts = Facts {
os: "linux".into(),
arch: "x86_64".into(),
gpus: vec![gpu.clone()],
memory: Memory {
total: 128 << 30,
available: 100 << 30,
swap_total: 0,
},
root: true,
systemd_system: true,
proc_fd: true,
memfd_ok: true,
..Facts::default()
};
facts
.libs
.insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into()));
facts.libs.insert(
"libcublasLt.so.12".into(),
Some("/x/libcublasLt.so.12".into()),
);
facts
.libs
.insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into()));
for tool in ["curl", "tar", "xz", "systemctl"] {
facts.tools.insert(tool.into(), true);
}
for name in BINARIES {
facts.binaries.insert(name.into(), true);
}
for key in ["assets", "state", "prefix"] {
facts.dirs.insert(
key.into(),
crate::facts::DirFact {
path: format!("/{key}").into(),
free_bytes: Some(2 << 40),
fs_type: Some("ext4".into()),
},
);
}
let profile = resolve(opts.profile.as_deref(), Some(&gpu));
let needs = Needs {
shard_bytes_missing: 83_617_662_656,
kar_bytes_missing: ARCHIVE_BYTES * 12 / 10,
..Needs::default()
};
let config = profile.as_ref().ok().map(|p| {
RunConfig::new(
&opts.dirs,
opts.ports.clone(),
0,
p.clone(),
BTreeMap::new(),
)
});
let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs));
Context {
service_user: "leleka".into(),
bin_src: "/src/bin".into(),
manifest: None,
profile,
mode,
facts,
paths,
config,
report,
needs,
opts,
}
}
fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState {
&steps.iter().find(|s| s.id == id).unwrap().state
}
#[test]
fn fresh_server_plans_every_step() {
let ctx = context(
options(&[]),
Mode::Systemd(UnitScopeTag::System),
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(
&ctx,
&FsState {
binaries_source_ok: true,
mtp_present: true,
..FsState::default()
},
);
for id in [
"layout",
"binaries",
"secrets",
"model",
"kar",
"tokenizer",
"config",
"service",
"start",
"ready",
] {
assert!(
matches!(state_of(&steps, id), StepState::Todo(_)),
"{id}: {:?}",
state_of(&steps, id)
);
}
let text = render_plan(&ctx, &steps).replace('\\', "/");
assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}");
assert!(text.contains("--kar-archive-fd {FD}"), "{text}");
}
#[test]
fn finished_deployment_is_done_except_nothing_to_do() {
let ctx = context(
options(&[]),
Mode::Systemd(UnitScopeTag::System),
"NVIDIA GeForce RTX 5090",
120,
);
let fs = FsState {
dirs_exist: true,
binaries_current: true,
binaries_source_ok: true,
cublas_ready: true,
secrets_present: true,
shards_stamp_ok: true,
kar_stamp_ok: true,
kar_present: true,
mtp_present: true,
tokenizer_present: true,
configs_current: true,
unit_current: true,
service_ready: true,
};
let steps = plan_steps(&ctx, &fs);
for step in &steps {
if step.id != "preflight" {
assert!(
matches!(step.state, StepState::Done(_)),
"{} is {:?}",
step.id,
step.state
);
}
}
// The plan of a finished deployment prints no commands (nothing will run).
assert!(!render_plan(&ctx, &steps[1..]).contains("$ "));
}
#[test]
fn missing_pieces_block_with_the_reason() {
let ctx = context(
options(&["--no-fetch", "--no-install-cublas"]),
Mode::Foreground,
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(&ctx, &FsState::default());
assert!(matches!(
state_of(&steps, "binaries"),
StepState::Blocked(_)
));
assert!(matches!(state_of(&steps, "cublas"), StepState::Blocked(_)));
assert!(matches!(state_of(&steps, "model"), StepState::Blocked(_)));
assert!(matches!(state_of(&steps, "kar"), StepState::Blocked(_)));
let mtp = state_of(&steps, "mtp-pack");
assert!(
matches!(mtp, StepState::Blocked(_)) && mtp.why().contains("no automated producer"),
"{mtp:?}"
);
assert!(matches!(state_of(&steps, "service"), StepState::Skip(_)));
}
#[test]
fn the_archive_step_covers_the_shards_and_trust_archive_does_not() {
let ctx = context(
options(&[]),
Mode::Foreground,
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(
&ctx,
&FsState {
binaries_source_ok: true,
..FsState::default()
},
);
assert!(
state_of(&steps, "model")
.why()
.contains("inside the archive step")
);
let trusted = context(
options(&["--trust-archive"]),
Mode::Foreground,
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(
&trusted,
&FsState {
binaries_source_ok: true,
kar_present: true,
..FsState::default()
},
);
assert!(
!state_of(&steps, "model")
.why()
.contains("inside the archive step")
);
assert!(state_of(&steps, "kar").why().contains("--trust-archive"));
// Trusting needs an archive to trust.
let steps = plan_steps(
&trusted,
&FsState {
binaries_source_ok: true,
..FsState::default()
},
);
assert!(!state_of(&steps, "kar").why().contains("--trust-archive"));
}
#[test]
fn mtp_pack_import_is_a_todo_when_given() {
let ctx = context(
options(&["--mtp-pack", "/tmp/mtp-rt.tar.gz"]),
Mode::None,
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(
&ctx,
&FsState {
binaries_source_ok: true,
..FsState::default()
},
);
assert!(matches!(state_of(&steps, "mtp-pack"), StepState::Todo(_)));
assert!(matches!(state_of(&steps, "start"), StepState::Skip(_)));
}
#[test]
fn reverify_replans_verified_assets() {
let ctx = context(
options(&["--reverify"]),
Mode::Foreground,
"NVIDIA GeForce RTX 5090",
120,
);
let steps = plan_steps(
&ctx,
&FsState {
shards_stamp_ok: true,
kar_stamp_ok: true,
binaries_source_ok: true,
..FsState::default()
},
);
assert!(
matches!(state_of(&steps, "model"), StepState::Todo(_))
&& matches!(state_of(&steps, "kar"), StepState::Todo(_))
);
}
#[test]
fn laptop_plan_uses_the_file_engine_command() {
let ctx = context(
options(&[]),
Mode::Foreground,
"NVIDIA GeForce RTX 3080 Laptop GPU",
86,
);
let steps = plan_steps(&ctx, &FsState::default());
let text = render_plan(&ctx, &steps).replace('\\', "/");
assert!(
text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar")
&& text.contains("--context-tokens 8192"),
"{text}"
);
assert!(text.contains("rtx3080-16g"));
}
#[test]
fn mode_resolution() {
let mut facts = Facts {
root: true,
systemd_system: true,
..Facts::default()
};
facts.tools.insert("systemctl".into(), true);
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, false),
Mode::Systemd(UnitScopeTag::System)
);
facts.root = false;
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, true),
Mode::Systemd(UnitScopeTag::User)
);
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, false),
Mode::Foreground
);
facts.systemd_system = false;
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, true),
Mode::Foreground
);
assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None);
let _ = Dirs {
prefix: "/".into(),
state: "/".into(),
assets: "/".into(),
};
}
#[test]
fn expert_profile_needs_the_pinned_digest() {
let dir = std::env::temp_dir().join(format!("leleka-expert-{}", std::process::id()));
std::fs::create_dir_all(dir.join("data")).unwrap();
let profile = Profile::builtin("rtx3080-16g").unwrap();
assert_eq!(
expert_profile_state(&profile, &dir),
Some(ExpertProfileState::Absent)
);
std::fs::write(dir.join("data/expert-profile.bin"), b"not the profile").unwrap();
assert_eq!(
expert_profile_state(&profile, &dir),
Some(ExpertProfileState::WrongDigest)
);
// the server profile names the same shipped routing profile (default digest)
assert_eq!(
expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir),
Some(ExpertProfileState::WrongDigest)
);
std::fs::remove_dir_all(dir).unwrap();
}
}