Merge branch 'claude/deploy' into claude/port-gpu-bringup
This commit is contained in:
@@ -38,3 +38,6 @@ logs/
|
||||
*.kar2
|
||||
*.safetensors
|
||||
*.bin
|
||||
|
||||
# Release tarballs made by scripts/package-release.py
|
||||
/dist/
|
||||
|
||||
Generated
+12
@@ -1025,6 +1025,18 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-deploy"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-experimental-ref"
|
||||
version = "0.1.0"
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"]
|
||||
members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/deploy", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "control-plane", "desktop-core"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "leleka-deploy"
|
||||
version = "0.1.0"
|
||||
description = "One-command deployment of the Leleka runtime: preflight, model assets, install, supervision and readiness (no Python)"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "leleka_deploy"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "leleka"
|
||||
path = "src/main.rs"
|
||||
|
||||
# Test double for the runtime programs; built only for the integration tests (`--features test-fakes`).
|
||||
[[bin]]
|
||||
name = "leleka-fake-runtime"
|
||||
path = "src/bin/fake_runtime.rs"
|
||||
required-features = ["test-fakes"]
|
||||
|
||||
[features]
|
||||
test-fakes = []
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.11"
|
||||
hex = "0.4"
|
||||
tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time", "sync", "net", "signal", "fs"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { version = "=1.1.5", features = ["fs", "process", "stdio"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,427 @@
|
||||
//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`.
|
||||
use crate::{
|
||||
cli::{Command, Environment, USAGE, UpOptions, parse},
|
||||
plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan},
|
||||
preflight::Report,
|
||||
profile::{BUILTIN, Profile},
|
||||
steps::{self, gather_fs, say},
|
||||
supervisor,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn env_var(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn is_root() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
rustix::process::geteuid().is_root()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn main_with(args: Vec<String>) -> i32 {
|
||||
let var = env_var;
|
||||
let environment = Environment {
|
||||
root: is_root(),
|
||||
home: std::env::var_os("HOME").map(PathBuf::from),
|
||||
var: &var,
|
||||
};
|
||||
let command = match parse(&args, &environment) {
|
||||
Ok(command) => command,
|
||||
Err(message) => {
|
||||
eprintln!("leleka: {message}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
match command {
|
||||
Command::Help => {
|
||||
print!("{USAGE}");
|
||||
0
|
||||
}
|
||||
Command::Version => {
|
||||
println!("leleka {}", env!("CARGO_PKG_VERSION"));
|
||||
0
|
||||
}
|
||||
Command::Profiles(None) => {
|
||||
for (name, _) in BUILTIN {
|
||||
let profile = Profile::builtin(name).expect("built-in");
|
||||
println!("{name}\n {}", profile.description);
|
||||
}
|
||||
0
|
||||
}
|
||||
Command::Profiles(Some(name)) => match Profile::builtin(&name) {
|
||||
Some(profile) => {
|
||||
print!("{}", crate::config::to_file_text(&profile));
|
||||
0
|
||||
}
|
||||
None => {
|
||||
eprintln!("leleka: unknown profile {name:?}");
|
||||
2
|
||||
}
|
||||
},
|
||||
Command::Preflight(opts) => preflight(opts).await,
|
||||
Command::Up(opts) => up(opts).await,
|
||||
Command::Status(opts) => status(opts).await,
|
||||
Command::Down(opts) => down(opts).await,
|
||||
Command::Run { config, kar_fd } => {
|
||||
supervisor::run(supervisor::Options { config, kar_fd }).await
|
||||
}
|
||||
Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) {
|
||||
Ok(never) => match never {},
|
||||
Err(message) => {
|
||||
eprintln!("leleka exec-inherit: {message}");
|
||||
2
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn print_report(report: &Report) {
|
||||
eprint!("{}", report.render());
|
||||
}
|
||||
|
||||
fn json_plan(ctx: &Context, steps: &[Step]) -> Value {
|
||||
json!({
|
||||
"mode": ctx.mode,
|
||||
"profile": ctx.config.as_ref().map(|c| c.profile.name.clone()),
|
||||
"preflight": ctx.report,
|
||||
"steps": steps,
|
||||
"engine_command": ctx.config.as_ref().map(|c| {
|
||||
let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()];
|
||||
args.extend(c.engine_args(c.kar_arg()));
|
||||
args
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
async fn preflight(opts: UpOptions) -> i32 {
|
||||
let ctx = gather(&opts, &env_var);
|
||||
match (&ctx.profile, &ctx.report) {
|
||||
(Err(message), _) => {
|
||||
eprintln!("leleka: {message}");
|
||||
1
|
||||
}
|
||||
(Ok(_), Some(report)) => {
|
||||
if opts.json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(report).expect("serializable")
|
||||
);
|
||||
} else {
|
||||
print_report(report);
|
||||
}
|
||||
i32::from(report.failed())
|
||||
}
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn up(opts: UpOptions) -> i32 {
|
||||
let ctx = gather(&opts, &env_var);
|
||||
if let Err(message) = &ctx.profile {
|
||||
eprintln!("leleka: {message}");
|
||||
return 1;
|
||||
}
|
||||
let report = ctx
|
||||
.report
|
||||
.as_ref()
|
||||
.expect("report exists when the profile does");
|
||||
print_report(report);
|
||||
let fs = gather_fs(&ctx).await;
|
||||
let steps = plan_steps(&ctx, &fs);
|
||||
let blocked = steps
|
||||
.iter()
|
||||
.any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight");
|
||||
if opts.dry_run {
|
||||
if opts.json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable")
|
||||
);
|
||||
} else {
|
||||
print!("{}", render_plan(&ctx, &steps));
|
||||
println!(
|
||||
"mode: {}; nothing was changed (--dry-run)",
|
||||
ctx.mode.label()
|
||||
);
|
||||
}
|
||||
return i32::from(report.failed() || blocked);
|
||||
}
|
||||
if report.failed() {
|
||||
eprintln!(
|
||||
"leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command."
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
eprint!("{}", render_plan(&ctx, &steps));
|
||||
match run_up(&ctx, &steps).await {
|
||||
Ok(code) => code,
|
||||
Err(message) => {
|
||||
eprintln!("leleka: {message}");
|
||||
eprintln!(
|
||||
"leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)."
|
||||
);
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result<i32, String> {
|
||||
let changes = steps::prepare(ctx, steps).await?;
|
||||
let config = steps::config_of(ctx)?;
|
||||
match ctx.mode {
|
||||
Mode::None => {
|
||||
say(&format!(
|
||||
"prepared. Start it with: {} run --config {}",
|
||||
ctx.paths.bin("leleka").display(),
|
||||
ctx.paths.run_config().display()
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
Mode::Systemd(scope) => {
|
||||
#[cfg(unix)]
|
||||
if scope == UnitScopeTag::System {
|
||||
steps::ensure_service_user(ctx).await?;
|
||||
steps::hand_over_to_service_user(ctx)?;
|
||||
}
|
||||
let changed = steps::install_unit(ctx, scope).await?;
|
||||
steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?;
|
||||
steps::wait_ready(ctx, Some(scope)).await?;
|
||||
summary(ctx, config);
|
||||
Ok(0)
|
||||
}
|
||||
Mode::Foreground => {
|
||||
if let Some(fd) = ctx.opts.kar_fd {
|
||||
crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?;
|
||||
}
|
||||
if steps::probe_ready(ctx).await {
|
||||
say("a supervisor for this state directory is already ready");
|
||||
summary(ctx, config);
|
||||
return Ok(0);
|
||||
}
|
||||
if crate::plan::service_running(&ctx.paths) {
|
||||
return Err(format!(
|
||||
"another supervisor is running for {} (not ready yet); wait for it or stop it first",
|
||||
ctx.opts.dirs.state.display()
|
||||
));
|
||||
}
|
||||
let options = supervisor::Options {
|
||||
config: ctx.paths.run_config(),
|
||||
kar_fd: ctx.opts.kar_fd,
|
||||
};
|
||||
let run = supervisor::run(options);
|
||||
tokio::pin!(run);
|
||||
let mut printed = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
code = &mut run => return Ok(code),
|
||||
ready = steps::wait_ready(ctx, None), if !printed => {
|
||||
printed = true;
|
||||
match ready {
|
||||
Ok(()) => summary(ctx, config),
|
||||
Err(message) => say(&message),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value {
|
||||
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
|
||||
json!({
|
||||
"ready": true,
|
||||
"endpoint": format!("http://{}", ctx.opts.ports.api),
|
||||
"model": config.model_id,
|
||||
"model_digest": config.model_digest,
|
||||
"api_key_file": ctx.paths.api_key().display().to_string(),
|
||||
"gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})),
|
||||
"profile": config.profile.name,
|
||||
"gpu_budget_bytes": config.profile.gpu_budget_bytes,
|
||||
"context_tokens": config.profile.context_tokens,
|
||||
"kar_source": config.profile.kar_source.as_str(),
|
||||
"ram_total_bytes": ctx.facts.memory.total,
|
||||
"ram_available_at_start_bytes": ctx.facts.memory.available,
|
||||
"service": ctx.mode.label(),
|
||||
"logs": ctx.paths.logs().display().to_string(),
|
||||
"state": ctx.opts.dirs.state.display().to_string(),
|
||||
"assets": ctx.opts.dirs.assets.display().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn summary(ctx: &Context, config: &crate::config::RunConfig) {
|
||||
let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64);
|
||||
if ctx.opts.json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable")
|
||||
);
|
||||
return;
|
||||
}
|
||||
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
|
||||
let key_file = ctx.paths.api_key().display().to_string();
|
||||
let mut text = String::from("\nLeleka is ready.\n");
|
||||
text.push_str(&format!(
|
||||
" endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n",
|
||||
ctx.opts.ports.api
|
||||
));
|
||||
text.push_str(&format!(
|
||||
" model {} {}\n",
|
||||
config.model_id, config.model_digest
|
||||
));
|
||||
text.push_str(&format!(
|
||||
" api key in {key_file} (send it as `Authorization: Bearer ...`)\n"
|
||||
));
|
||||
if let Some(gpu) = gpu {
|
||||
text.push_str(&format!(
|
||||
" gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n",
|
||||
gpu.name,
|
||||
gpu.index,
|
||||
gpu.sm.map_or("?".into(), |s| s.to_string()),
|
||||
gpu.vram_total_mib,
|
||||
gpu.driver
|
||||
));
|
||||
}
|
||||
text.push_str(&format!(
|
||||
" profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n",
|
||||
config.profile.name,
|
||||
gib(config.profile.gpu_budget_bytes),
|
||||
config.profile.context_tokens,
|
||||
match config.profile.kar_source {
|
||||
crate::profile::KarSource::Memfd => format!(
|
||||
"a sealed memfd ({} of RAM held for the life of the service)",
|
||||
gib(crate::profile::ARCHIVE_BYTES)
|
||||
),
|
||||
crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(),
|
||||
}
|
||||
));
|
||||
text.push_str(&format!(
|
||||
" host RAM {} total, {} available before start\n",
|
||||
gib(ctx.facts.memory.total),
|
||||
gib(ctx.facts.memory.available)
|
||||
));
|
||||
text.push_str(&format!(" service {}\n", ctx.mode.label()));
|
||||
if ctx.mode == Mode::Systemd(UnitScopeTag::User) {
|
||||
text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot
|
||||
");
|
||||
}
|
||||
text.push_str(&format!(
|
||||
" logs {} (leleka.log, engine.log, gateway.log, api.log)\n",
|
||||
ctx.paths.logs().display()
|
||||
));
|
||||
text.push_str(&format!(
|
||||
" try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n",
|
||||
config.model_id, ctx.opts.ports.api
|
||||
));
|
||||
eprintln!("{text}");
|
||||
}
|
||||
|
||||
/// Which systemd unit of this deployment exists (system first), judged by the unit file.
|
||||
fn installed_scope(paths: &crate::layout::Paths) -> Option<UnitScopeTag> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
[UnitScopeTag::System, UnitScopeTag::User]
|
||||
.into_iter()
|
||||
.find(|scope| {
|
||||
crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name())
|
||||
.is_ok_and(|path| path.is_file())
|
||||
})
|
||||
}
|
||||
|
||||
/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing.
|
||||
async fn status(opts: UpOptions) -> i32 {
|
||||
let paths = opts.dirs.paths();
|
||||
let api = crate::config::RunConfig::read(&paths.run_config())
|
||||
.map(|config| config.ports.api)
|
||||
.unwrap_or_else(|_| opts.ports.api.clone());
|
||||
let status: Option<Value> = std::fs::read_to_string(paths.status_file())
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str(&t).ok());
|
||||
let ready = steps::probe_ready_at(&paths, &api).await;
|
||||
let unit = match installed_scope(&paths) {
|
||||
Some(scope) => {
|
||||
let mut command = tokio::process::Command::new("systemctl");
|
||||
if scope == UnitScopeTag::User {
|
||||
command.arg("--user");
|
||||
}
|
||||
command.args(["is-active", paths.unit_name()]);
|
||||
command
|
||||
.output()
|
||||
.await
|
||||
.ok()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if opts.json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(
|
||||
&json!({"ready": ready, "unit": unit, "supervisor": status})
|
||||
)
|
||||
.expect("serializable")
|
||||
);
|
||||
} else {
|
||||
println!("ready: {ready}");
|
||||
if let Some(unit) = unit {
|
||||
println!("systemd unit {}: {unit}", paths.unit_name());
|
||||
}
|
||||
match status {
|
||||
Some(s) => println!(
|
||||
"supervisor: phase {} (pid {}), engine restarts {}, updated {}
|
||||
{}",
|
||||
s["phase"].as_str().unwrap_or("?"),
|
||||
s["supervisor_pid"],
|
||||
s["engine_restarts"],
|
||||
s["updated_unix"]
|
||||
.as_u64()
|
||||
.map(supervisor::format_utc)
|
||||
.unwrap_or_default(),
|
||||
s["message"].as_str().unwrap_or("")
|
||||
),
|
||||
None => println!(
|
||||
"supervisor: no status file in {} (never started?)",
|
||||
paths.run_dir().display()
|
||||
),
|
||||
}
|
||||
}
|
||||
i32::from(!ready)
|
||||
}
|
||||
|
||||
async fn down(opts: UpOptions) -> i32 {
|
||||
let paths = opts.dirs.paths();
|
||||
match installed_scope(&paths) {
|
||||
Some(scope) => {
|
||||
let mut command = tokio::process::Command::new("systemctl");
|
||||
if scope == UnitScopeTag::User {
|
||||
command.arg("--user");
|
||||
}
|
||||
match command.args(["stop", paths.unit_name()]).status().await {
|
||||
Ok(status) if status.success() => {
|
||||
eprintln!("leleka: stopped {}", paths.unit_name());
|
||||
0
|
||||
}
|
||||
Ok(status) => {
|
||||
eprintln!("leleka: systemctl stop failed ({status})");
|
||||
1
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("leleka: cannot run systemctl: {error}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
eprintln!(
|
||||
"leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)"
|
||||
);
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Test double for the six runtime programs, selected by the name it is invoked as (symlinks named
|
||||
//! `leleka-inference`, `leleka-daemon`, `leleka-cli`, `strata-next`). Used only by the integration tests of
|
||||
//! `leleka-deploy` (`--features test-fakes`); it speaks just enough of each program's command line and of the
|
||||
//! HTTP readiness contract to exercise the supervisor and the `up` flow without a GPU or a model.
|
||||
//!
|
||||
//! Shared state lives in `PREFIX/fake/` (found from the invocation path `PREFIX/bin/NAME`): `engine.pid`,
|
||||
//! `loaded`, `calls.log`, and the one-shot switches `crash-engine-once` / `fail-engine`.
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
net::{TcpListener, TcpStream},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let mut args = std::env::args();
|
||||
let invoked = args.next().unwrap_or_default();
|
||||
let name = Path::new(&invoked)
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let args: Vec<String> = args.collect();
|
||||
let bin_dir = Path::new(&invoked)
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_default();
|
||||
let fake = bin_dir
|
||||
.parent()
|
||||
.map(|p| p.join("fake"))
|
||||
.unwrap_or_else(|| PathBuf::from("fake"));
|
||||
let _ = fs::create_dir_all(&fake);
|
||||
log_call(&fake, &name, &args);
|
||||
match name.as_str() {
|
||||
"leleka-inference" => engine(&fake, &args),
|
||||
"leleka-daemon" => daemon(&args),
|
||||
"leleka-cli" => cli(&fake, &args),
|
||||
"strata-next" => strata(&fake, &args),
|
||||
other => {
|
||||
eprintln!("fake runtime invoked as {other:?}");
|
||||
std::process::exit(64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_call(fake: &Path, name: &str, args: &[String]) {
|
||||
// Tokens never appear on a command line; the log is for call counting.
|
||||
if let Ok(mut file) = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(fake.join("calls.log"))
|
||||
{
|
||||
let _ = writeln!(file, "{name} {}", args.join(" "));
|
||||
}
|
||||
}
|
||||
|
||||
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter()
|
||||
.position(|a| a == name)
|
||||
.and_then(|i| args.get(i + 1))
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
fn alive(address: &str) -> bool {
|
||||
address
|
||||
.parse()
|
||||
.is_ok_and(|a| TcpStream::connect_timeout(&a, Duration::from_secs(2)).is_ok())
|
||||
}
|
||||
|
||||
fn engine(fake: &Path, args: &[String]) {
|
||||
if fake.join("fail-engine").exists() {
|
||||
eprintln!("fake engine: failing on request");
|
||||
std::process::exit(7);
|
||||
}
|
||||
let token = std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default();
|
||||
if token.len() < 32 {
|
||||
eprintln!("fake engine: LELEKA_RUNTIME_TOKEN missing");
|
||||
std::process::exit(2);
|
||||
}
|
||||
if std::env::var_os("HF_TOKEN").is_some() {
|
||||
eprintln!("fake engine: HF_TOKEN leaked into the engine environment");
|
||||
std::process::exit(3);
|
||||
}
|
||||
let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned();
|
||||
if let Some(fd) = flag(args, "--kar-archive-fd") {
|
||||
// The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd.
|
||||
let number: u32 = fd.parse().unwrap_or(0);
|
||||
let path = format!("/proc/self/fd/{number}");
|
||||
let meta = fs::metadata(&path);
|
||||
let ok = number >= 3 && meta.as_ref().is_ok_and(|m| m.is_file());
|
||||
if !ok {
|
||||
eprintln!("fake engine: descriptor {fd} is not an inherited regular file");
|
||||
std::process::exit(4);
|
||||
}
|
||||
eprintln!(
|
||||
"fake engine: kar fd {number} bytes {}",
|
||||
meta.map(|m| m.len()).unwrap_or(0)
|
||||
);
|
||||
} else if let Some(file) = flag(args, "--kar-archive-file") {
|
||||
if !Path::new(file).is_file() {
|
||||
eprintln!("fake engine: archive file {file} missing");
|
||||
std::process::exit(4);
|
||||
}
|
||||
} else {
|
||||
eprintln!("fake engine: no archive argument");
|
||||
std::process::exit(5);
|
||||
}
|
||||
let listener = TcpListener::bind(&listen).unwrap_or_else(|e| {
|
||||
eprintln!("fake engine: cannot bind {listen}: {e}");
|
||||
std::process::exit(6);
|
||||
});
|
||||
let _ = fs::remove_file(fake.join("loaded"));
|
||||
let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string());
|
||||
eprintln!(
|
||||
"fake engine: listening on {listen} pid {}",
|
||||
std::process::id()
|
||||
);
|
||||
if fake.join("fail-load").exists() {
|
||||
// The real engine reports a failed load on its own stderr and stays up.
|
||||
eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable");
|
||||
}
|
||||
if fake.join("crash-engine-once").exists() {
|
||||
let _ = fs::remove_file(fake.join("crash-engine-once"));
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(Duration::from_millis(1500));
|
||||
eprintln!("fake engine: crashing on request");
|
||||
std::process::exit(9);
|
||||
});
|
||||
}
|
||||
for stream in listener.incoming() {
|
||||
drop(stream);
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon(args: &[String]) {
|
||||
let config: serde_json::Value = flag(args, "--config")
|
||||
.and_then(|p| fs::read_to_string(p).ok())
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
let listen = config["listen"]
|
||||
.as_str()
|
||||
.unwrap_or("127.0.0.1:0")
|
||||
.to_owned();
|
||||
if std::env::var("LELEKA_GATEWAY_TOKEN")
|
||||
.unwrap_or_default()
|
||||
.len()
|
||||
< 32
|
||||
{
|
||||
eprintln!("fake daemon: LELEKA_GATEWAY_TOKEN missing");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let listener = TcpListener::bind(&listen).unwrap_or_else(|e| {
|
||||
eprintln!("fake daemon: cannot bind {listen}: {e}");
|
||||
std::process::exit(6);
|
||||
});
|
||||
for stream in listener.incoming() {
|
||||
drop(stream);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(fake: &Path, args: &[String]) {
|
||||
let config: serde_json::Value = flag(args, "--config")
|
||||
.and_then(|p| fs::read_to_string(p).ok())
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
let engine_address = config["runtimes"][0]["address"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let id = config["runtimes"][0]["id"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let rest: Vec<&str> = args.iter().skip(2).map(String::as_str).collect();
|
||||
match rest.as_slice() {
|
||||
["status"] => {
|
||||
let connected = alive(&engine_address);
|
||||
let ready = connected && fake.join("loaded").exists();
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"schema_version":1,"runtimes":[{"id":id,"connected":connected,"epoch":"e","loaded_handle":null,"model_ready":ready,"configuration_action_required":false}]})
|
||||
);
|
||||
}
|
||||
["load-mtp", model, profile] => {
|
||||
if *model != id || *profile != "qwen4exp-kar-ple-mtp-v1" || !alive(&engine_address) {
|
||||
eprintln!("Error: \"runtime_not_connected\"");
|
||||
std::process::exit(1);
|
||||
}
|
||||
// Like the real CLI: the operation id and epoch are printed before the command is sent.
|
||||
println!("{{\"operation_id\":\"op-1\",\"epoch\":\"e\",\"model\":\"{id}\"}}");
|
||||
// Loading takes a moment in the real engine.
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
if !fake.join("fail-load").exists() {
|
||||
let _ = fs::write(fake.join("loaded"), "1");
|
||||
}
|
||||
println!("{{\"state\":1}}");
|
||||
}
|
||||
["operation", model, "op-1", "e"] if *model == id => {
|
||||
let state = if fake.join("fail-load").exists() {
|
||||
3
|
||||
} else if fake.join("loaded").exists() {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
println!(
|
||||
"{{
|
||||
\"state\": {state}
|
||||
}}"
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
eprintln!("fake cli: unsupported {rest:?}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn strata(fake: &Path, args: &[String]) {
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
match args.as_slice() {
|
||||
["api-key", "init", "--file", file] => {
|
||||
if !Path::new(file).exists() {
|
||||
let key = "fake-api-key-0123456789abcdef0123456789abcdef";
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.create_new(true).write(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let _ = options
|
||||
.open(file)
|
||||
.and_then(|mut f| f.write_all(key.as_bytes()));
|
||||
}
|
||||
println!("{{\"created\":false}}");
|
||||
}
|
||||
["model", "fetch", _, "--output", dir] => {
|
||||
fetch_shards(dir);
|
||||
println!("fetched");
|
||||
}
|
||||
["model", "verify", _, "--output", _] => println!("verified"),
|
||||
[
|
||||
"model",
|
||||
"ensure-sharded-streamed",
|
||||
_,
|
||||
"--source-dir",
|
||||
source_dir,
|
||||
"--output",
|
||||
kar,
|
||||
"--levels",
|
||||
"2",
|
||||
] => {
|
||||
// Like the real tool: fetch and verify the shards first.
|
||||
fetch_shards(source_dir);
|
||||
if !Path::new(kar).exists() {
|
||||
fs::File::create(kar)
|
||||
.and_then(|f| f.set_len(55_295_529_472))
|
||||
.expect("sparse archive");
|
||||
fs::write(format!("{kar}.provenance.json"), "{}").expect("provenance");
|
||||
}
|
||||
println!("created and verified experimental streamed KAR-2: {kar}");
|
||||
}
|
||||
["model", "extract-tokenizer", _, "--output", dir] => {
|
||||
fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir");
|
||||
fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}")
|
||||
.expect("tokenizer file");
|
||||
}
|
||||
["serve", "--config", config] => api(fake, config),
|
||||
other => {
|
||||
eprintln!("fake strata-next: unsupported {other:?}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_shards(dir: &str) {
|
||||
fs::create_dir_all(dir).expect("model dir");
|
||||
for (name, size) in [
|
||||
(
|
||||
"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
|
||||
54_817_524_224u64,
|
||||
),
|
||||
(
|
||||
"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
|
||||
28_800_138_432u64,
|
||||
),
|
||||
] {
|
||||
let path = Path::new(dir).join(name);
|
||||
if !path.exists() {
|
||||
fs::File::create(&path)
|
||||
.and_then(|f| f.set_len(size))
|
||||
.expect("sparse shard");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn api(fake: &Path, config: &str) {
|
||||
let config: serde_json::Value = fs::read_to_string(config)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
let bind = config["bind"].as_str().unwrap_or("127.0.0.1:0").to_owned();
|
||||
let engine_address = config["runtime"]["address"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let key = config["api_key_file"]
|
||||
.as_str()
|
||||
.and_then(|p| fs::read_to_string(p).ok())
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_owned();
|
||||
if std::env::var("LELEKA_RUNTIME_TOKEN")
|
||||
.unwrap_or_default()
|
||||
.len()
|
||||
< 32
|
||||
{
|
||||
eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let listener = TcpListener::bind(&bind).unwrap_or_else(|e| {
|
||||
eprintln!("fake api: cannot bind {bind}: {e}");
|
||||
std::process::exit(6);
|
||||
});
|
||||
for stream in listener.incoming().flatten() {
|
||||
let (fake, engine_address, key) = (fake.to_path_buf(), engine_address.clone(), key.clone());
|
||||
std::thread::spawn(move || respond(stream, &fake, &engine_address, &key));
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str, key: &str) {
|
||||
let mut buffer = [0u8; 4096];
|
||||
let count = stream.read(&mut buffer).unwrap_or(0);
|
||||
let request = String::from_utf8_lossy(&buffer[..count]).into_owned();
|
||||
let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned();
|
||||
let authorized = request.contains(&format!("Authorization: Bearer {key}\r\n"));
|
||||
let ready = alive(engine_address) && fake.join("loaded").exists();
|
||||
let (status, body) = match path.as_str() {
|
||||
"/health" => ("200 OK", "{\"ok\":true}".to_owned()),
|
||||
_ if !authorized => (
|
||||
"401 Unauthorized",
|
||||
"{\"error\":\"unauthorized\"}".to_owned(),
|
||||
),
|
||||
"/ready" if ready => (
|
||||
"200 OK",
|
||||
"{\"service\":\"strata-control\",\"ready\":true}".to_owned(),
|
||||
),
|
||||
"/ready" => (
|
||||
"503 Service Unavailable",
|
||||
"{\"service\":\"strata-control\",\"ready\":false}".to_owned(),
|
||||
),
|
||||
_ => ("404 Not Found", "{}".to_owned()),
|
||||
};
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`.
|
||||
use crate::{config::Ports, layout::Dirs};
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
leleka - one-command deployment of the Leleka runtime
|
||||
|
||||
USAGE
|
||||
leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready
|
||||
leleka preflight [OPTIONS] only the host checks (exit 1 when one fails)
|
||||
leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API)
|
||||
leleka status [OPTIONS] service state and readiness
|
||||
leleka down [OPTIONS] stop the systemd service
|
||||
leleka profiles [show NAME] list the memory profiles, or print one as JSON
|
||||
leleka version
|
||||
|
||||
UP / PREFLIGHT OPTIONS
|
||||
--dry-run print the plan and the preflight, change nothing
|
||||
--json machine-readable plan / summary on stdout
|
||||
--profile auto|NAME|FILE memory profile (default auto: chosen from the GPU)
|
||||
--gpu N CUDA device ordinal (default 0)
|
||||
--assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS]
|
||||
--state-dir DIR configs, tokens, logs, status [$LELEKA_STATE]
|
||||
--prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX]
|
||||
--bin-src DIR where to take the six binaries from (default: the directory of this binary)
|
||||
--mode auto|system|user|foreground|none
|
||||
--foreground same as --mode foreground (WSL without systemd, containers, terminals)
|
||||
--api-port N API port (default 8081)
|
||||
--api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port
|
||||
is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS)
|
||||
--engine-port N engine gRPC port (default 18766)
|
||||
--daemon-port N gateway port (default 18080)
|
||||
--gpu-budget-gib N override the profile's GPU memory budget
|
||||
--context-tokens N override the profile's context ceiling
|
||||
--no-fetch never download or build; require the model files to exist
|
||||
--reverify ignore the verification stamps and hash everything again
|
||||
--trust-archive accept an existing archive of the pinned length + its provenance file without the
|
||||
strict re-derivation (hours-scale); the engine still checks its SHA-256 and every
|
||||
CRC against the pinned digest at each load
|
||||
--mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets
|
||||
--cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading
|
||||
--no-install-cublas fail instead of downloading cuBLAS 12.9.1.4
|
||||
--timeout-s N wait this long for readiness (default 3600)
|
||||
--kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again,
|
||||
its RAM is not required (foreground / --mode none only)
|
||||
--service-user NAME system unit only: account the service runs as (default leleka, created if missing)
|
||||
|
||||
ENVIRONMENT
|
||||
HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co)
|
||||
";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ModeChoice {
|
||||
Auto,
|
||||
System,
|
||||
User,
|
||||
Foreground,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UpOptions {
|
||||
pub dry_run: bool,
|
||||
pub json: bool,
|
||||
pub profile: Option<String>,
|
||||
pub gpu: u32,
|
||||
pub dirs: Dirs,
|
||||
pub bin_src: Option<PathBuf>,
|
||||
pub mode: ModeChoice,
|
||||
pub ports: Ports,
|
||||
pub gpu_budget_gib: Option<u64>,
|
||||
pub context_tokens: Option<u32>,
|
||||
pub fetch: bool,
|
||||
pub reverify: bool,
|
||||
/// Accept an existing archive of the pinned length without the strict F32 re-derivation.
|
||||
pub trust_archive: bool,
|
||||
pub mtp_pack: Option<PathBuf>,
|
||||
pub cublas_dir: Option<PathBuf>,
|
||||
pub install_cublas: bool,
|
||||
pub timeout_s: u64,
|
||||
/// System unit only: the account the service runs as (created when missing). Default `leleka`.
|
||||
pub service_user: Option<String>,
|
||||
/// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs).
|
||||
pub kar_fd: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Command {
|
||||
Up(UpOptions),
|
||||
Preflight(UpOptions),
|
||||
Run {
|
||||
config: PathBuf,
|
||||
kar_fd: Option<u32>,
|
||||
},
|
||||
ExecInherit(Vec<String>),
|
||||
Status(UpOptions),
|
||||
Down(UpOptions),
|
||||
Profiles(Option<String>),
|
||||
Version,
|
||||
Help,
|
||||
}
|
||||
|
||||
type Flags = BTreeMap<String, Option<String>>;
|
||||
|
||||
const UP_FLAGS: &[(&str, bool)] = &[
|
||||
("--dry-run", false),
|
||||
("--json", false),
|
||||
("--profile", true),
|
||||
("--gpu", true),
|
||||
("--assets", true),
|
||||
("--state-dir", true),
|
||||
("--prefix", true),
|
||||
("--bin-src", true),
|
||||
("--mode", true),
|
||||
("--foreground", false),
|
||||
("--api-port", true),
|
||||
("--api-bind", true),
|
||||
("--engine-port", true),
|
||||
("--daemon-port", true),
|
||||
("--gpu-budget-gib", true),
|
||||
("--context-tokens", true),
|
||||
("--no-fetch", false),
|
||||
("--reverify", false),
|
||||
("--trust-archive", false),
|
||||
("--mtp-pack", true),
|
||||
("--cublas-dir", true),
|
||||
("--no-install-cublas", false),
|
||||
("--timeout-s", true),
|
||||
("--service-user", true),
|
||||
("--kar-fd", true),
|
||||
];
|
||||
|
||||
fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result<Flags, String> {
|
||||
let mut flags = Flags::new();
|
||||
let mut index = 0;
|
||||
while index < args.len() {
|
||||
let arg = &args[index];
|
||||
let (name, inline) = match arg.split_once('=') {
|
||||
Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())),
|
||||
_ => (arg.as_str(), None),
|
||||
};
|
||||
let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else {
|
||||
return Err(format!("unknown option {name:?}; see `leleka --help`"));
|
||||
};
|
||||
let value = if *takes_value {
|
||||
match inline {
|
||||
Some(value) => Some(value),
|
||||
None => {
|
||||
index += 1;
|
||||
Some(
|
||||
args.get(index)
|
||||
.ok_or_else(|| format!("{name} needs a value"))?
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else if inline.is_some() {
|
||||
return Err(format!("{name} takes no value"));
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if flags.insert(name.to_owned(), value).is_some() {
|
||||
return Err(format!("{name} given twice"));
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
Ok(flags)
|
||||
}
|
||||
|
||||
fn number<T: std::str::FromStr>(flags: &Flags, name: &str, default: T) -> Result<T, String> {
|
||||
match flags.get(name) {
|
||||
None => Ok(default),
|
||||
Some(value) => value
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.parse()
|
||||
.map_err(|_| format!("{name} needs a number")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `--api-bind IP`: where the public API listens. Loopback unless asked; the engine and the gateway always
|
||||
/// stay on loopback. A non-loopback bind is for containers (publish the port to 127.0.0.1 on the host).
|
||||
fn api_bind(flags: &Flags) -> Result<String, String> {
|
||||
match text(flags, "--api-bind") {
|
||||
None => Ok("127.0.0.1".into()),
|
||||
Some(ip) => match ip.parse::<std::net::IpAddr>() {
|
||||
Ok(std::net::IpAddr::V4(v4)) => Ok(v4.to_string()),
|
||||
Ok(std::net::IpAddr::V6(_)) => Err("--api-bind takes an IPv4 address".into()),
|
||||
Err(_) => Err(format!("--api-bind needs an IP address, not {ip:?}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn ranged<T: std::str::FromStr + PartialOrd + std::fmt::Display + Copy>(
|
||||
flags: &Flags,
|
||||
name: &str,
|
||||
range: std::ops::RangeInclusive<T>,
|
||||
) -> Result<Option<T>, String> {
|
||||
if !flags.contains_key(name) {
|
||||
return Ok(None);
|
||||
}
|
||||
let value: T = number(flags, name, *range.start())?;
|
||||
if !range.contains(&value) {
|
||||
return Err(format!("{name} must be {}..{}", range.start(), range.end()));
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
fn text<'a>(flags: &'a Flags, name: &str) -> Option<&'a str> {
|
||||
flags.get(name).and_then(|v| v.as_deref())
|
||||
}
|
||||
|
||||
fn port(flags: &Flags, name: &str, default: u16) -> Result<u16, String> {
|
||||
let value: u16 = number(flags, name, default)?;
|
||||
if value < 1024 {
|
||||
return Err(format!("{name} must be 1024..65535"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Environment access is injected so that parsing is testable.
|
||||
pub struct Environment<'a> {
|
||||
pub root: bool,
|
||||
pub home: Option<PathBuf>,
|
||||
pub var: &'a dyn Fn(&str) -> Option<String>,
|
||||
}
|
||||
|
||||
fn up_options(args: &[String], env: &Environment) -> Result<UpOptions, String> {
|
||||
let flags = parse_flags(args, UP_FLAGS)?;
|
||||
let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var);
|
||||
let abs = |name: &str, fallback: PathBuf| -> Result<PathBuf, String> {
|
||||
let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback);
|
||||
if !path.is_absolute() {
|
||||
return Err(format!(
|
||||
"{name} must be an absolute path (got {})",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
Ok(path)
|
||||
};
|
||||
let dirs = Dirs {
|
||||
prefix: abs("--prefix", defaults.prefix)?,
|
||||
state: abs("--state-dir", defaults.state)?,
|
||||
assets: abs("--assets", defaults.assets)?,
|
||||
};
|
||||
let mode = if flags.contains_key("--foreground") {
|
||||
if flags.contains_key("--mode") {
|
||||
return Err("use either --foreground or --mode".into());
|
||||
}
|
||||
ModeChoice::Foreground
|
||||
} else {
|
||||
match text(&flags, "--mode").unwrap_or("auto") {
|
||||
"auto" => ModeChoice::Auto,
|
||||
"system" => ModeChoice::System,
|
||||
"user" => ModeChoice::User,
|
||||
"foreground" => ModeChoice::Foreground,
|
||||
"none" => ModeChoice::None,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"--mode must be auto, system, user, foreground or none, not {other:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
let kar_fd = match flags.get("--kar-fd") {
|
||||
None => None,
|
||||
Some(_) => {
|
||||
let fd: u32 = number(&flags, "--kar-fd", 0u32)?;
|
||||
if !(3..=1_048_576).contains(&fd) {
|
||||
return Err(
|
||||
"--kar-fd must be an inherited descriptor number of 3 or higher".into(),
|
||||
);
|
||||
}
|
||||
if matches!(mode, ModeChoice::System | ModeChoice::User) {
|
||||
return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into());
|
||||
}
|
||||
Some(fd)
|
||||
}
|
||||
};
|
||||
if mode == ModeChoice::System && !env.root {
|
||||
return Err("--mode system needs root (use sudo), or --mode user / --foreground".into());
|
||||
}
|
||||
let ports = Ports {
|
||||
api: format!(
|
||||
"{}:{}",
|
||||
api_bind(&flags)?,
|
||||
port(&flags, "--api-port", 8081)?
|
||||
),
|
||||
engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?),
|
||||
daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?),
|
||||
};
|
||||
let distinct = [&ports.api, &ports.engine, &ports.daemon];
|
||||
if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] {
|
||||
return Err("the API, engine and gateway ports must differ".into());
|
||||
}
|
||||
let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from);
|
||||
if let Some(dir) = &cublas_dir
|
||||
&& !dir.is_absolute()
|
||||
{
|
||||
return Err("--cublas-dir must be an absolute path".into());
|
||||
}
|
||||
Ok(UpOptions {
|
||||
dry_run: flags.contains_key("--dry-run"),
|
||||
json: flags.contains_key("--json"),
|
||||
profile: text(&flags, "--profile").map(str::to_owned),
|
||||
gpu: number(&flags, "--gpu", 0u32)?,
|
||||
dirs,
|
||||
bin_src: text(&flags, "--bin-src").map(PathBuf::from),
|
||||
mode,
|
||||
ports,
|
||||
gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?,
|
||||
context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?,
|
||||
service_user: text(&flags, "--service-user").map(str::to_owned),
|
||||
kar_fd,
|
||||
fetch: !flags.contains_key("--no-fetch"),
|
||||
reverify: flags.contains_key("--reverify"),
|
||||
trust_archive: flags.contains_key("--trust-archive"),
|
||||
mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from),
|
||||
cublas_dir,
|
||||
install_cublas: !flags.contains_key("--no-install-cublas"),
|
||||
timeout_s: {
|
||||
let value: u64 = number(&flags, "--timeout-s", 3600)?;
|
||||
if !(1..=86_400).contains(&value) {
|
||||
return Err("--timeout-s must be 1..86400".into());
|
||||
}
|
||||
value
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
|
||||
let Some((command, rest)) = args.split_first() else {
|
||||
return Ok(Command::Help);
|
||||
};
|
||||
match command.as_str() {
|
||||
"-h" | "--help" | "help" => Ok(Command::Help),
|
||||
"version" | "--version" | "-V" => Ok(Command::Version),
|
||||
"up" => up_options(rest, env).map(Command::Up),
|
||||
"preflight" => up_options(rest, env).map(Command::Preflight),
|
||||
"status" => up_options(rest, env).map(Command::Status),
|
||||
"down" => up_options(rest, env).map(Command::Down),
|
||||
"profiles" => match rest {
|
||||
[] => Ok(Command::Profiles(None)),
|
||||
[show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))),
|
||||
_ => Err("usage: leleka profiles [show NAME]".into()),
|
||||
},
|
||||
"run" => {
|
||||
let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?;
|
||||
let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?;
|
||||
Ok(Command::Run {
|
||||
config: PathBuf::from(config),
|
||||
kar_fd: flags
|
||||
.get("--kar-fd")
|
||||
.map(|_| number(&flags, "--kar-fd", 0u32))
|
||||
.transpose()?,
|
||||
})
|
||||
}
|
||||
"exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())),
|
||||
other => Err(format!("unknown command {other:?}; see `leleka --help`")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn strings(items: &[&str]) -> Vec<String> {
|
||||
items.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
fn parse_as(root: bool, args: &[&str]) -> Result<Command, String> {
|
||||
let var = |_: &str| None;
|
||||
parse(
|
||||
&strings(args),
|
||||
&Environment {
|
||||
root,
|
||||
home: Some("/home/para".into()),
|
||||
var: &var,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_defaults_for_a_user() {
|
||||
let Command::Up(options) = parse_as(false, &["up"]).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(
|
||||
options.dirs.assets,
|
||||
PathBuf::from("/home/para/.local/share/leleka/assets")
|
||||
);
|
||||
assert_eq!(options.ports.api, "127.0.0.1:8081");
|
||||
assert!(options.fetch && options.install_cublas && !options.dry_run);
|
||||
assert_eq!(options.mode, ModeChoice::Auto);
|
||||
assert_eq!(options.timeout_s, 3600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_accept_both_forms_and_reject_mistakes() {
|
||||
let Command::Up(options) = parse_as(
|
||||
false,
|
||||
&[
|
||||
"up",
|
||||
"--assets=/data/l",
|
||||
"--gpu",
|
||||
"1",
|
||||
"--foreground",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
"--no-fetch",
|
||||
"--api-port=9000",
|
||||
],
|
||||
)
|
||||
.unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(options.dirs.assets, PathBuf::from("/data/l"));
|
||||
assert_eq!(
|
||||
(
|
||||
options.gpu,
|
||||
options.mode,
|
||||
options.dry_run,
|
||||
options.json,
|
||||
options.fetch
|
||||
),
|
||||
(1, ModeChoice::Foreground, true, true, false)
|
||||
);
|
||||
assert_eq!(options.ports.api, "127.0.0.1:9000");
|
||||
for bad in [
|
||||
&["up", "--nope"][..],
|
||||
&["up", "--gpu"],
|
||||
&["up", "--dry-run", "--dry-run"],
|
||||
&["up", "--dry-run=1"],
|
||||
&["up", "--assets", "relative/dir"],
|
||||
&["up", "--api-port", "80"],
|
||||
&["up", "--api-port", "9000", "--engine-port", "9000"],
|
||||
&["up", "--mode", "weird"],
|
||||
&["up", "--foreground", "--mode", "user"],
|
||||
&["up", "--gpu-budget-gib", "0"],
|
||||
&["up", "--context-tokens", "999999"],
|
||||
&["up", "--timeout-s", "0"],
|
||||
] {
|
||||
assert!(parse_as(false, bad).is_err(), "{bad:?} should fail");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_bind_is_explicit_and_only_for_the_api() {
|
||||
let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(options.ports.api, "0.0.0.0:8081");
|
||||
assert_eq!(options.ports.engine, "127.0.0.1:18766");
|
||||
assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err());
|
||||
assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_mode_needs_root() {
|
||||
assert!(
|
||||
parse_as(false, &["up", "--mode", "system"])
|
||||
.unwrap_err()
|
||||
.contains("root")
|
||||
);
|
||||
assert!(parse_as(true, &["up", "--mode", "system"]).is_ok());
|
||||
let Command::Up(options) = parse_as(true, &["up"]).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_commands() {
|
||||
assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help));
|
||||
assert!(matches!(
|
||||
parse_as(false, &["profiles"]).unwrap(),
|
||||
Command::Profiles(None)
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(),
|
||||
Command::Profiles(Some(_))
|
||||
));
|
||||
let Command::Run { config, kar_fd } = parse_as(
|
||||
false,
|
||||
&["run", "--config", "/s/leleka.json", "--kar-fd", "3"],
|
||||
)
|
||||
.unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3)));
|
||||
assert!(parse_as(false, &["run"]).is_err());
|
||||
assert!(parse_as(false, &["frobnicate"]).is_err());
|
||||
assert!(matches!(
|
||||
parse_as(false, &["exec-inherit", "--", "x"]).unwrap(),
|
||||
Command::ExecInherit(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
//! The run configuration written by `up` and read by `run`, and the generated configs of the child processes.
|
||||
//!
|
||||
//! `leleka.json` holds no secret. Tokens live in `runtime.env` (mode 0600) and reach the children only through
|
||||
//! their environment, never through argv.
|
||||
use crate::{
|
||||
layout::{Dirs, MODEL_DIGEST, MODEL_ID, MTP_PROFILE, Paths},
|
||||
profile::{KarSource, Profile},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const SCHEMA_VERSION: u32 = 1;
|
||||
pub const RUNTIME_TOKEN_ENV: &str = "LELEKA_RUNTIME_TOKEN";
|
||||
pub const GATEWAY_TOKEN_ENV: &str = "LELEKA_GATEWAY_TOKEN";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Ports {
|
||||
pub api: String,
|
||||
pub engine: String,
|
||||
pub daemon: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RestartPolicy {
|
||||
/// Engine restarts the supervisor performs before it gives up (each one re-reads the archive).
|
||||
pub max_engine_restarts: u32,
|
||||
/// An engine that stayed ready this long resets the restart counter.
|
||||
pub stable_after_s: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RunConfig {
|
||||
pub schema_version: u32,
|
||||
pub leleka_version: String,
|
||||
pub model_id: String,
|
||||
pub model_digest: String,
|
||||
pub prefix: String,
|
||||
pub state: String,
|
||||
pub assets: String,
|
||||
pub ports: Ports,
|
||||
pub gpu: u32,
|
||||
pub profile: Profile,
|
||||
/// Extra engine environment resolved by `up` (for example the expert-profile path when that file is valid).
|
||||
#[serde(default)]
|
||||
pub engine_env: BTreeMap<String, String>,
|
||||
pub load_timeout_s: u64,
|
||||
pub shutdown_grace_s: u64,
|
||||
pub restart: RestartPolicy,
|
||||
}
|
||||
|
||||
/// How the engine receives the archive on its command line.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum KarArg {
|
||||
/// `--kar-archive-fd {FD}`: the shim substitutes the descriptor number.
|
||||
Fd,
|
||||
/// `--kar-archive-file PATH`.
|
||||
File,
|
||||
}
|
||||
|
||||
impl RunConfig {
|
||||
pub fn new(
|
||||
dirs: &Dirs,
|
||||
ports: Ports,
|
||||
gpu: u32,
|
||||
profile: Profile,
|
||||
engine_env: BTreeMap<String, String>,
|
||||
) -> Self {
|
||||
RunConfig {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
leleka_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
model_id: MODEL_ID.to_owned(),
|
||||
model_digest: MODEL_DIGEST.to_owned(),
|
||||
prefix: dirs.prefix.display().to_string(),
|
||||
state: dirs.state.display().to_string(),
|
||||
assets: dirs.assets.display().to_string(),
|
||||
ports,
|
||||
gpu,
|
||||
profile,
|
||||
engine_env,
|
||||
load_timeout_s: 1800,
|
||||
shutdown_grace_s: 10,
|
||||
restart: RestartPolicy {
|
||||
max_engine_restarts: 2,
|
||||
stable_after_s: 600,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dirs(&self) -> Dirs {
|
||||
Dirs {
|
||||
prefix: self.prefix.clone().into(),
|
||||
state: self.state.clone().into(),
|
||||
assets: self.assets.clone().into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paths(&self) -> Paths {
|
||||
self.dirs().paths()
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.schema_version != SCHEMA_VERSION {
|
||||
return Err(format!(
|
||||
"leleka.json has schema_version {}, this binary understands {SCHEMA_VERSION}; rerun `leleka up`",
|
||||
self.schema_version
|
||||
));
|
||||
}
|
||||
self.profile.validate()?;
|
||||
for (name, address, must_be_loopback) in [
|
||||
("api", &self.ports.api, false),
|
||||
("engine", &self.ports.engine, true),
|
||||
("daemon", &self.ports.daemon, true),
|
||||
] {
|
||||
let parsed: std::net::SocketAddr = address
|
||||
.parse()
|
||||
.map_err(|_| format!("ports.{name} must be a literal ip:port"))?;
|
||||
// Only the API may leave the loopback interface (containers); the engine and the gateway never.
|
||||
if must_be_loopback && !parsed.ip().is_loopback() {
|
||||
return Err(format!(
|
||||
"ports.{name} must be a loopback address (use an SSH tunnel for remote access)"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn read(path: &std::path::Path) -> Result<RunConfig, String> {
|
||||
let bytes = std::fs::read(path).map_err(|error| {
|
||||
format!(
|
||||
"cannot read {}: {error}; run `leleka up` first",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let config: RunConfig = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| format!("invalid {}: {error}", path.display()))?;
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Arguments of `leleka-inference`, in the order its parser requires (seven fixed pairs first, then the
|
||||
/// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`].
|
||||
pub fn engine_args(&self, kar: KarArg) -> Vec<String> {
|
||||
let paths = self.paths();
|
||||
let profile = &self.profile;
|
||||
let mut args: Vec<String> = vec![
|
||||
"--listen".into(),
|
||||
self.ports.engine.clone(),
|
||||
"--token-env".into(),
|
||||
RUNTIME_TOKEN_ENV.into(),
|
||||
"--shard0".into(),
|
||||
paths.shard(0).display().to_string(),
|
||||
"--shard1".into(),
|
||||
paths.shard(1).display().to_string(),
|
||||
"--gpu".into(),
|
||||
self.gpu.to_string(),
|
||||
"--gpu-budget".into(),
|
||||
profile.gpu_budget_bytes.to_string(),
|
||||
"--context-tokens".into(),
|
||||
profile.context_tokens.to_string(),
|
||||
];
|
||||
match kar {
|
||||
KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]),
|
||||
KarArg::File => args.extend([
|
||||
"--kar-archive-file".into(),
|
||||
paths.kar().display().to_string(),
|
||||
]),
|
||||
}
|
||||
args.extend([
|
||||
"--kar-provenance".into(),
|
||||
paths.kar_provenance().display().to_string(),
|
||||
"--mtp-pack".into(),
|
||||
paths.mtp_pack().display().to_string(),
|
||||
"--mtp-staging".into(),
|
||||
paths.mtp_staging().display().to_string(),
|
||||
"--backend-mode".into(),
|
||||
"original".into(),
|
||||
"--expert-source".into(),
|
||||
profile.expert_source.as_str().into(),
|
||||
]);
|
||||
if let Some(value) = profile.prefill_capacity {
|
||||
args.extend(["--original-prefill-capacity".into(), value.to_string()]);
|
||||
}
|
||||
if let Some(value) = &profile.kv {
|
||||
args.extend(["--kv".into(), value.clone()]);
|
||||
}
|
||||
if let Some(value) = profile.kv_resident {
|
||||
args.extend(["--kv-resident".into(), value.to_string()]);
|
||||
}
|
||||
if let Some(value) = profile.prompt_cache {
|
||||
args.extend(["--prompt-cache".into(), value.to_string()]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
pub fn kar_arg(&self) -> KarArg {
|
||||
match self.profile.kar_source {
|
||||
KarSource::Memfd => KarArg::Fd,
|
||||
KarSource::File => KarArg::File,
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's extra environment: profile switches, then the `up`-resolved ones (which win).
|
||||
pub fn engine_environment(&self) -> BTreeMap<String, String> {
|
||||
let mut env = self.profile.engine_env.clone();
|
||||
env.extend(self.engine_env.clone());
|
||||
env
|
||||
}
|
||||
|
||||
pub fn daemon_json(&self) -> Value {
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"listen": self.ports.daemon,
|
||||
"token_env": GATEWAY_TOKEN_ENV,
|
||||
"runtimes": [{
|
||||
"id": self.model_id,
|
||||
"address": self.ports.engine,
|
||||
"token_env": RUNTIME_TOKEN_ENV,
|
||||
"artifact_digest": self.model_digest,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
pub fn strata_json(&self) -> Value {
|
||||
let paths = self.paths();
|
||||
json!({
|
||||
"bind": self.ports.api,
|
||||
"api_key_file": paths.api_key().display().to_string(),
|
||||
"model": self.model_id,
|
||||
"shutdown_grace_s": self.shutdown_grace_s,
|
||||
"runtime": {
|
||||
"address": self.ports.engine,
|
||||
"token_env": RUNTIME_TOKEN_ENV,
|
||||
"tokenizer_dir": paths.tokenizer_dir().display().to_string(),
|
||||
"model": {
|
||||
"family": "qwen4exp",
|
||||
"architecture": "qwen4exp",
|
||||
"weight_format": "gguf:iq3_s",
|
||||
"artifact_digest": self.model_digest,
|
||||
},
|
||||
"mode": {"type": "mtp", "profile_id": MTP_PROFILE},
|
||||
"max_context": self.profile.context_tokens,
|
||||
"max_output_tokens": 4096,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on
|
||||
/// the loopback interface.
|
||||
pub fn probe_address(bind: &str) -> Option<std::net::SocketAddr> {
|
||||
let address: std::net::SocketAddr = bind.parse().ok()?;
|
||||
Some(if address.ip().is_unspecified() {
|
||||
std::net::SocketAddr::from(([127, 0, 0, 1], address.port()))
|
||||
} else {
|
||||
address
|
||||
})
|
||||
}
|
||||
|
||||
/// Pretty JSON with a trailing newline, the byte form that is written and compared.
|
||||
pub fn to_file_text(value: &impl Serialize) -> String {
|
||||
let mut text = serde_json::to_string_pretty(value).expect("serializable");
|
||||
text.push('\n');
|
||||
text
|
||||
}
|
||||
|
||||
/// `n` random bytes from the kernel. Linux only (the deployment is).
|
||||
pub fn random_bytes(n: usize) -> Result<Vec<u8>, String> {
|
||||
use std::io::Read;
|
||||
let mut bytes = vec![0u8; n];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut file| file.read_exact(&mut bytes))
|
||||
.map_err(|error| format!("cannot read /dev/urandom: {error}"))?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// A 48-character lower-case hex token (192 bits), inside the 32..4096 printable-ASCII rule of the runtime.
|
||||
pub fn new_token() -> Result<String, String> {
|
||||
Ok(hex::encode(random_bytes(24)?))
|
||||
}
|
||||
|
||||
/// Update `KEY=VALUE` lines of a systemd environment file in place, appending missing keys and keeping every
|
||||
/// other line (including secrets) byte for byte.
|
||||
pub fn merge_env(existing: &str, updates: &[(&str, String)]) -> String {
|
||||
let mut lines: Vec<String> = existing.lines().map(str::to_owned).collect();
|
||||
for (key, value) in updates {
|
||||
let prefix = format!("{key}=");
|
||||
let mut found = false;
|
||||
for line in lines.iter_mut() {
|
||||
if line.trim_start().starts_with(&prefix) {
|
||||
*line = format!("{key}={value}");
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
lines.push(format!("{key}={value}"));
|
||||
}
|
||||
}
|
||||
let mut text = lines.join("\n");
|
||||
text.push('\n');
|
||||
text
|
||||
}
|
||||
|
||||
/// The header comment of a freshly created `runtime.env`.
|
||||
pub const ENV_HEADER: &str = "# Written by `leleka up`; mode 0600; never commit. Two independent secrets and the loader path.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(profile: &str) -> RunConfig {
|
||||
let dirs = Dirs {
|
||||
prefix: "/opt/leleka".into(),
|
||||
state: "/var/lib/leleka/state".into(),
|
||||
assets: "/data/leleka".into(),
|
||||
};
|
||||
RunConfig::new(
|
||||
&dirs,
|
||||
Ports {
|
||||
api: "127.0.0.1:8081".into(),
|
||||
engine: "127.0.0.1:18766".into(),
|
||||
daemon: "127.0.0.1:18080".into(),
|
||||
},
|
||||
0,
|
||||
Profile::builtin(profile).unwrap(),
|
||||
BTreeMap::new(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_engine_command_matches_the_documented_one() {
|
||||
let args = config("rtx5090-32g").engine_args(KarArg::Fd);
|
||||
let text = args.join(" ");
|
||||
// docs/rust-runtime-run.md, step 1.
|
||||
assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}");
|
||||
assert!(text.contains("--gpu 0 --gpu-budget 25769803776 --context-tokens 262144"));
|
||||
assert!(text.contains("--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json"));
|
||||
assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident"));
|
||||
// The engine parser reads the first 14 arguments positionally.
|
||||
assert_eq!(args[..14].len(), 14);
|
||||
assert_eq!(args[12], "--context-tokens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn laptop_uses_the_file_source_and_a_small_context() {
|
||||
let config = config("rtx3080-16g");
|
||||
assert_eq!(config.kar_arg(), KarArg::File);
|
||||
let text = config.engine_args(config.kar_arg()).join(" ");
|
||||
assert!(
|
||||
text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance")
|
||||
);
|
||||
assert!(text.contains("--gpu-budget 16106127360 --context-tokens 8192"));
|
||||
assert!(text.contains("--expert-source mapped"));
|
||||
assert!(!text.contains("{FD}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_configs_are_consistent() {
|
||||
let config = config("rtx5090-32g");
|
||||
let daemon = config.daemon_json();
|
||||
assert_eq!(daemon["runtimes"][0]["address"], "127.0.0.1:18766");
|
||||
assert_eq!(daemon["runtimes"][0]["artifact_digest"], MODEL_DIGEST);
|
||||
let strata = config.strata_json();
|
||||
assert_eq!(
|
||||
strata["runtime"]["address"],
|
||||
daemon["runtimes"][0]["address"]
|
||||
);
|
||||
assert_eq!(
|
||||
strata["runtime"]["mode"]["profile_id"],
|
||||
"qwen4exp-kar-ple-mtp-v1"
|
||||
);
|
||||
assert_eq!(
|
||||
strata["runtime"]["tokenizer_dir"],
|
||||
"/data/leleka/tokenizer-assets/tokenizer"
|
||||
);
|
||||
assert_eq!(strata["runtime"]["max_context"], 262144);
|
||||
// No secret is ever part of a generated config.
|
||||
let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config);
|
||||
assert!(!text.to_ascii_lowercase().contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_rejects_non_loopback_and_future_schemas() {
|
||||
// Only the API may be bound beyond loopback (container use); the others never.
|
||||
let mut open_api = config("rtx5090-32g");
|
||||
open_api.ports.api = "0.0.0.0:8081".into();
|
||||
assert!(open_api.validate().is_ok());
|
||||
assert_eq!(
|
||||
probe_address("0.0.0.0:8081"),
|
||||
Some("127.0.0.1:8081".parse().unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
probe_address("127.0.0.1:1"),
|
||||
Some("127.0.0.1:1".parse().unwrap())
|
||||
);
|
||||
assert_eq!(probe_address("nonsense"), None);
|
||||
let mut bad = config("rtx5090-32g");
|
||||
bad.ports.engine = "0.0.0.0:18766".into();
|
||||
assert!(bad.validate().unwrap_err().contains("loopback"));
|
||||
let mut bad = config("rtx5090-32g");
|
||||
bad.schema_version = 9;
|
||||
assert!(bad.validate().unwrap_err().contains("schema_version"));
|
||||
assert!(config("rtx3080-16g").validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_through_json() {
|
||||
let original = config("rtx3080-16g");
|
||||
let text = to_file_text(&original);
|
||||
let back: RunConfig = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(back, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_merge_keeps_secrets_and_updates_the_loader_path() {
|
||||
let existing = "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/old\nOTHER=1\n";
|
||||
let merged = merge_env(
|
||||
existing,
|
||||
&[
|
||||
("LD_LIBRARY_PATH", "/new".into()),
|
||||
("LELEKA_GATEWAY_TOKEN", "bbbb".into()),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
merged,
|
||||
"# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/new\nOTHER=1\nLELEKA_GATEWAY_TOKEN=bbbb\n"
|
||||
);
|
||||
assert_eq!(
|
||||
merge_env(&merged, &[("LD_LIBRARY_PATH", "/new".into())]),
|
||||
merged
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn tokens_are_printable_distinct_and_long_enough() {
|
||||
let (a, b) = (new_token().unwrap(), new_token().unwrap());
|
||||
assert_ne!(a, b);
|
||||
assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expert_environment_wins_over_the_profile() {
|
||||
let mut config = config("rtx3080-16g");
|
||||
config
|
||||
.profile
|
||||
.engine_env
|
||||
.insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.1".into());
|
||||
config
|
||||
.engine_env
|
||||
.insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.2".into());
|
||||
config
|
||||
.engine_env
|
||||
.insert("LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".into(), "auto".into());
|
||||
let env = config.engine_environment();
|
||||
assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2");
|
||||
assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
//! Host facts for the preflight: pure parsers (unit-tested on any OS) and a Linux probe that fills `Facts`.
|
||||
//!
|
||||
//! `Facts` is plain data so that `preflight::evaluate` can be tested with synthetic hosts. Nothing here creates
|
||||
//! a CUDA context; the GPU is read through `nvidia-smi`.
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Gpu {
|
||||
pub index: u32,
|
||||
pub name: String,
|
||||
pub driver: String,
|
||||
pub vram_total_mib: u64,
|
||||
pub vram_free_mib: u64,
|
||||
/// Compute capability times ten (12.0 -> 120, 8.6 -> 86).
|
||||
pub sm: Option<u32>,
|
||||
}
|
||||
|
||||
impl Gpu {
|
||||
pub fn driver_major(&self) -> Option<u32> {
|
||||
self.driver.split('.').next()?.parse().ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Memory {
|
||||
pub total: u64,
|
||||
pub available: u64,
|
||||
pub swap_total: u64,
|
||||
}
|
||||
|
||||
/// What `probe` reads about one directory the deployment will write to.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DirFact {
|
||||
pub path: PathBuf,
|
||||
/// Free bytes of the file system that holds (or would hold) the directory.
|
||||
pub free_bytes: Option<u64>,
|
||||
/// File system type of the mount that holds it (`ext4`, `9p`, `drvfs`, ...).
|
||||
pub fs_type: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Facts {
|
||||
pub os: String,
|
||||
pub arch: String,
|
||||
pub root: bool,
|
||||
pub nvidia_smi_found: bool,
|
||||
pub nvidia_smi_error: Option<String>,
|
||||
pub gpus: Vec<Gpu>,
|
||||
pub memory: Memory,
|
||||
/// `memory.max` of the cgroup this process runs in, when limited.
|
||||
pub cgroup_memory_max: Option<u64>,
|
||||
pub wsl: bool,
|
||||
pub systemd_system: bool,
|
||||
pub proc_fd: bool,
|
||||
pub memfd_ok: bool,
|
||||
pub libs: BTreeMap<String, Option<PathBuf>>,
|
||||
pub tools: BTreeMap<String, bool>,
|
||||
pub dirs: BTreeMap<String, DirFact>,
|
||||
pub busy_ports: Vec<u16>,
|
||||
pub binaries: BTreeMap<String, bool>,
|
||||
pub hf_token_set: bool,
|
||||
}
|
||||
|
||||
impl Facts {
|
||||
pub fn lib(&self, soname: &str) -> Option<&PathBuf> {
|
||||
self.libs.get(soname).and_then(Option::as_ref)
|
||||
}
|
||||
pub fn tool(&self, name: &str) -> bool {
|
||||
self.tools.get(name).copied().unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// `nvidia-smi --query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap --format=csv,noheader,nounits`.
|
||||
/// A missing or "[N/A]" compute capability falls back to a name table so older drivers still classify.
|
||||
pub fn parse_nvidia_smi(csv: &str) -> Vec<Gpu> {
|
||||
csv.lines()
|
||||
.filter_map(|line| {
|
||||
let fields: Vec<&str> = line.split(',').map(str::trim).collect();
|
||||
if fields.len() < 5 {
|
||||
return None;
|
||||
}
|
||||
let index = fields[0].parse().ok()?;
|
||||
let name = fields[1].to_owned();
|
||||
let sm = fields
|
||||
.get(5)
|
||||
.and_then(|cc| parse_compute_capability(cc))
|
||||
.or_else(|| sm_from_name(&name));
|
||||
Some(Gpu {
|
||||
index,
|
||||
driver: fields[2].to_owned(),
|
||||
vram_total_mib: fields[3].parse().ok()?,
|
||||
vram_free_mib: fields[4].parse().ok()?,
|
||||
name,
|
||||
sm,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn parse_compute_capability(text: &str) -> Option<u32> {
|
||||
let (major, minor) = text.trim().split_once('.')?;
|
||||
let (major, minor): (u32, u32) = (major.parse().ok()?, minor.parse().ok()?);
|
||||
(minor < 10).then_some(major * 10 + minor)
|
||||
}
|
||||
|
||||
fn sm_from_name(name: &str) -> Option<u32> {
|
||||
const TABLE: [(&str, u32); 8] = [
|
||||
("RTX 50", 120),
|
||||
("RTX 40", 89),
|
||||
("RTX 3090", 86),
|
||||
("RTX 30", 86),
|
||||
("RTX 20", 75),
|
||||
("A100", 80),
|
||||
("H100", 90),
|
||||
("L40", 89),
|
||||
];
|
||||
TABLE
|
||||
.iter()
|
||||
.find(|(needle, _)| name.contains(needle))
|
||||
.map(|(_, sm)| *sm)
|
||||
}
|
||||
|
||||
/// `/proc/meminfo` in bytes. `MemAvailable` is required; a kernel without it yields zeros (the caller fails closed).
|
||||
pub fn parse_meminfo(text: &str) -> Memory {
|
||||
let value = |key: &str| -> u64 {
|
||||
text.lines()
|
||||
.find_map(|line| line.strip_prefix(key)?.strip_prefix(':'))
|
||||
.and_then(|rest| rest.split_whitespace().next()?.parse::<u64>().ok())
|
||||
.map_or(0, |kib| kib.saturating_mul(1024))
|
||||
};
|
||||
Memory {
|
||||
total: value("MemTotal"),
|
||||
available: value("MemAvailable"),
|
||||
swap_total: value("SwapTotal"),
|
||||
}
|
||||
}
|
||||
|
||||
/// WSL2 identifies itself in the kernel version string (`...-microsoft-standard-WSL2`).
|
||||
pub fn is_wsl(proc_version: &str) -> bool {
|
||||
let lower = proc_version.to_ascii_lowercase();
|
||||
lower.contains("microsoft") || lower.contains("wsl")
|
||||
}
|
||||
|
||||
/// `memory.max` content: a byte count, or `max` for unlimited.
|
||||
pub fn parse_cgroup_max(text: &str) -> Option<u64> {
|
||||
text.trim().parse().ok()
|
||||
}
|
||||
|
||||
/// File system type of the longest mount point that contains `path` (`/proc/mounts` format).
|
||||
pub fn fs_type_for(mounts: &str, path: &Path) -> Option<String> {
|
||||
let mut best: Option<(usize, String)> = None;
|
||||
for line in mounts.lines() {
|
||||
let mut fields = line.split_whitespace();
|
||||
let (Some(_device), Some(mount), Some(kind)) =
|
||||
(fields.next(), fields.next(), fields.next())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let mount = mount.replace("\\040", " ");
|
||||
let mount_path = Path::new(&mount);
|
||||
if path.starts_with(mount_path) && best.as_ref().is_none_or(|(len, _)| mount.len() >= *len)
|
||||
{
|
||||
best = Some((mount.len(), kind.to_owned()));
|
||||
}
|
||||
}
|
||||
best.map(|(_, kind)| kind)
|
||||
}
|
||||
|
||||
/// File system types that are a Windows drive or a network share seen from WSL: far too slow for mapped reads.
|
||||
pub fn is_slow_foreign_fs(kind: &str) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
"9p" | "drvfs" | "virtiofs" | "cifs" | "smb3" | "nfs" | "nfs4" | "fuse.sshfs"
|
||||
)
|
||||
}
|
||||
|
||||
/// First directory in `dirs` that holds a file called `soname`, or the `ldconfig -p` entry for it.
|
||||
pub fn find_library(soname: &str, dirs: &[PathBuf], ldconfig: &str) -> Option<PathBuf> {
|
||||
for dir in dirs {
|
||||
let candidate = dir.join(soname);
|
||||
if candidate.exists() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
ldconfig.lines().find_map(|line| {
|
||||
let line = line.trim();
|
||||
let (name, rest) = line.split_once(" (")?;
|
||||
if name.trim() != soname {
|
||||
return None;
|
||||
}
|
||||
let path = rest.split_once("=>")?.1.trim();
|
||||
Some(PathBuf::from(path))
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse `KEY=VALUE` lines of an environment file (systemd `EnvironmentFile` subset: no export, `#` comments).
|
||||
pub fn parse_env_file(text: &str) -> BTreeMap<String, String> {
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let (key, value) = line.split_once('=')?;
|
||||
let key = key.trim();
|
||||
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
|
||||
return None;
|
||||
}
|
||||
let value = value.trim();
|
||||
let value = value
|
||||
.strip_prefix('"')
|
||||
.and_then(|v| v.strip_suffix('"'))
|
||||
.unwrap_or(value);
|
||||
Some((key.to_owned(), value.to_owned()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What `probe` must look at beyond the machine itself.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ProbeRequest {
|
||||
pub dirs: Vec<(String, PathBuf)>,
|
||||
pub ports: Vec<u16>,
|
||||
pub binary_dir: Option<PathBuf>,
|
||||
pub binaries: Vec<String>,
|
||||
pub extra_library_dirs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn probe(request: &ProbeRequest) -> Facts {
|
||||
linux::probe(request)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn probe(_request: &ProbeRequest) -> Facts {
|
||||
Facts {
|
||||
os: std::env::consts::OS.to_owned(),
|
||||
arch: std::env::consts::ARCH.to_owned(),
|
||||
..Facts::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux {
|
||||
use super::*;
|
||||
use std::{net::TcpListener, process::Command};
|
||||
|
||||
fn read(path: &str) -> String {
|
||||
std::fs::read_to_string(path).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn which(name: &str, extra: &[&str]) -> Option<PathBuf> {
|
||||
let path = std::env::var_os("PATH").unwrap_or_default();
|
||||
std::env::split_paths(&path)
|
||||
.chain(extra.iter().map(PathBuf::from))
|
||||
.map(|dir| dir.join(name))
|
||||
.find(|candidate| candidate.is_file())
|
||||
}
|
||||
|
||||
fn nearest_existing(path: &Path) -> PathBuf {
|
||||
let mut current = path.to_path_buf();
|
||||
while !current.exists() {
|
||||
if !current.pop() {
|
||||
return PathBuf::from("/");
|
||||
}
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
fn free_bytes(path: &Path) -> Option<u64> {
|
||||
let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?;
|
||||
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
|
||||
}
|
||||
|
||||
fn memfd_works() -> bool {
|
||||
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create};
|
||||
let Ok(fd) = memfd_create(
|
||||
"leleka-preflight",
|
||||
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
fcntl_add_seals(&fd, SealFlags::SEAL).is_ok()
|
||||
}
|
||||
|
||||
pub fn probe(request: &ProbeRequest) -> Facts {
|
||||
let mut facts = Facts {
|
||||
os: std::env::consts::OS.to_owned(),
|
||||
arch: std::env::consts::ARCH.to_owned(),
|
||||
root: rustix::process::geteuid().is_root(),
|
||||
hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()),
|
||||
..Facts::default()
|
||||
};
|
||||
facts.wsl = is_wsl(&read("/proc/version"));
|
||||
facts.memory = parse_meminfo(&read("/proc/meminfo"));
|
||||
facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max"));
|
||||
facts.systemd_system = Path::new("/run/systemd/system").is_dir();
|
||||
facts.proc_fd = Path::new("/proc/self/fd").is_dir();
|
||||
facts.memfd_ok = memfd_works();
|
||||
|
||||
let smi = which(
|
||||
"nvidia-smi",
|
||||
&["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"],
|
||||
);
|
||||
match smi {
|
||||
None => {
|
||||
facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into());
|
||||
}
|
||||
Some(smi) => {
|
||||
facts.nvidia_smi_found = true;
|
||||
match Command::new(smi)
|
||||
.args([
|
||||
"--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap",
|
||||
"--format=csv,noheader,nounits",
|
||||
])
|
||||
.output()
|
||||
{
|
||||
Ok(output) if output.status.success() => {
|
||||
facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout));
|
||||
}
|
||||
Ok(output) => {
|
||||
// compute_cap is unknown to old drivers: retry without it.
|
||||
let retry = Command::new("nvidia-smi")
|
||||
.args([
|
||||
"--query-gpu=index,name,driver_version,memory.total,memory.free",
|
||||
"--format=csv,noheader,nounits",
|
||||
])
|
||||
.output();
|
||||
match retry {
|
||||
Ok(second) if second.status.success() => {
|
||||
facts.gpus =
|
||||
parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout));
|
||||
}
|
||||
_ => {
|
||||
let text = String::from_utf8_lossy(&output.stderr);
|
||||
facts.nvidia_smi_error =
|
||||
Some(text.lines().next().unwrap_or("nvidia-smi failed").to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => facts.nvidia_smi_error = Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ldconfig = Command::new("ldconfig")
|
||||
.arg("-p")
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
|
||||
.unwrap_or_default();
|
||||
let mut library_dirs: Vec<PathBuf> = request.extra_library_dirs.clone();
|
||||
if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") {
|
||||
library_dirs
|
||||
.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty()));
|
||||
}
|
||||
for fixed in [
|
||||
"/usr/lib/wsl/lib",
|
||||
"/usr/local/cuda/lib64",
|
||||
"/usr/lib/x86_64-linux-gnu",
|
||||
"/usr/lib64",
|
||||
] {
|
||||
library_dirs.push(PathBuf::from(fixed));
|
||||
}
|
||||
for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] {
|
||||
facts.libs.insert(
|
||||
soname.to_owned(),
|
||||
find_library(soname, &library_dirs, &ldconfig),
|
||||
);
|
||||
}
|
||||
|
||||
for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] {
|
||||
facts.tools.insert(
|
||||
tool.to_owned(),
|
||||
which(tool, &["/usr/sbin", "/sbin"]).is_some(),
|
||||
);
|
||||
}
|
||||
|
||||
let mounts = read("/proc/mounts");
|
||||
for (key, path) in &request.dirs {
|
||||
facts.dirs.insert(
|
||||
key.clone(),
|
||||
DirFact {
|
||||
path: path.clone(),
|
||||
free_bytes: free_bytes(path),
|
||||
fs_type: fs_type_for(&mounts, &nearest_existing(path)),
|
||||
},
|
||||
);
|
||||
}
|
||||
for port in &request.ports {
|
||||
if TcpListener::bind(("127.0.0.1", *port)).is_err() {
|
||||
facts.busy_ports.push(*port);
|
||||
}
|
||||
}
|
||||
if let Some(dir) = &request.binary_dir {
|
||||
for name in &request.binaries {
|
||||
facts
|
||||
.binaries
|
||||
.insert(name.clone(), is_executable(&dir.join(name)));
|
||||
}
|
||||
}
|
||||
facts
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
path.metadata()
|
||||
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nvidia_smi_csv_for_server_and_laptop() {
|
||||
let server =
|
||||
parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n");
|
||||
assert_eq!(server.len(), 1);
|
||||
assert_eq!(server[0].sm, Some(120));
|
||||
assert_eq!(server[0].driver_major(), Some(595));
|
||||
assert_eq!(server[0].vram_free_mib, 32105);
|
||||
let laptop =
|
||||
parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n");
|
||||
assert_eq!(laptop[0].sm, Some(86));
|
||||
assert_eq!(laptop[0].driver_major(), Some(617));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_compute_capability_falls_back_to_the_name_table() {
|
||||
let gpus =
|
||||
parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n");
|
||||
assert_eq!(gpus[0].sm, Some(86));
|
||||
let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n");
|
||||
assert_eq!(gpus[0].sm, Some(120));
|
||||
let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n");
|
||||
assert_eq!(gpus[0].sm, None);
|
||||
assert!(parse_nvidia_smi("garbage\n\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meminfo_bytes() {
|
||||
let memory = parse_meminfo(
|
||||
"MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n",
|
||||
);
|
||||
assert_eq!(memory.total, 24_447_308 * 1024);
|
||||
assert_eq!(memory.available, 22_000_000 * 1024);
|
||||
assert_eq!(memory.swap_total, 2_097_152 * 1024);
|
||||
assert_eq!(parse_meminfo("nothing"), Memory::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_and_cgroup_detection() {
|
||||
assert!(is_wsl(
|
||||
"Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)"
|
||||
));
|
||||
assert!(!is_wsl(
|
||||
"Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)"
|
||||
));
|
||||
assert_eq!(parse_cgroup_max("max\n"), None);
|
||||
assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filesystem_type_uses_the_longest_mount_prefix() {
|
||||
let mounts =
|
||||
"/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n";
|
||||
assert_eq!(
|
||||
fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(),
|
||||
Some("9p")
|
||||
);
|
||||
assert_eq!(
|
||||
fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(),
|
||||
Some("ext4")
|
||||
);
|
||||
assert_eq!(
|
||||
fs_type_for(mounts, Path::new("/home/x")).as_deref(),
|
||||
Some("ext4")
|
||||
);
|
||||
assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_lookup_prefers_directories_then_ldconfig() {
|
||||
let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n";
|
||||
assert_eq!(
|
||||
find_library("libcublas.so.12", &[], ldconfig),
|
||||
Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12"))
|
||||
);
|
||||
assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_file_parser_handles_comments_and_quotes() {
|
||||
let env = parse_env_file(
|
||||
"# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n",
|
||||
);
|
||||
assert_eq!(env.get("A").map(String::as_str), Some("1"));
|
||||
assert_eq!(env.get("B").map(String::as_str), Some("two words"));
|
||||
assert_eq!(
|
||||
env.get("LD_LIBRARY_PATH").map(String::as_str),
|
||||
Some("/a:/b")
|
||||
);
|
||||
assert!(!env.contains_key("bad key"));
|
||||
assert!(!env.contains_key("export X"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! A minimal HTTP/1.1 GET against a loopback address. The readiness probes need nothing more, and a hand-written
|
||||
//! client keeps TLS, redirects and proxies out of a path that must only ever talk to 127.0.0.1.
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
const MAX_RESPONSE: usize = 64 * 1024;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Response {
|
||||
pub status: u16,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// `GET path` with an optional bearer token. Errors are plain strings that never contain the token.
|
||||
pub async fn get(
|
||||
address: SocketAddr,
|
||||
path: &str,
|
||||
bearer: Option<&str>,
|
||||
limit: Duration,
|
||||
) -> Result<Response, String> {
|
||||
if !address.ip().is_loopback() {
|
||||
return Err("readiness probes talk to loopback addresses only".into());
|
||||
}
|
||||
if !path.starts_with('/') || path.bytes().any(|b| b <= b' ' || b == 0x7f) {
|
||||
return Err("invalid request path".into());
|
||||
}
|
||||
let exchange = async {
|
||||
let mut stream = TcpStream::connect(address)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut request = format!(
|
||||
"GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\nAccept: application/json\r\n"
|
||||
);
|
||||
if let Some(token) = bearer {
|
||||
request.push_str(&format!("Authorization: Bearer {token}\r\n"));
|
||||
}
|
||||
request.push_str("\r\n");
|
||||
stream
|
||||
.write_all(request.as_bytes())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut raw = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
let count = stream.read(&mut chunk).await.map_err(|e| e.to_string())?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
raw.extend_from_slice(&chunk[..count]);
|
||||
if raw.len() > MAX_RESPONSE {
|
||||
return Err("response exceeds 64 KiB".to_owned());
|
||||
}
|
||||
}
|
||||
parse_response(&raw)
|
||||
};
|
||||
timeout(limit, exchange)
|
||||
.await
|
||||
.map_err(|_| "request timed out".to_owned())?
|
||||
}
|
||||
|
||||
pub fn parse_response(raw: &[u8]) -> Result<Response, String> {
|
||||
let text = String::from_utf8_lossy(raw);
|
||||
let (head, body) = text
|
||||
.split_once("\r\n\r\n")
|
||||
.ok_or("malformed HTTP response")?;
|
||||
let status_line = head.lines().next().ok_or("empty HTTP response")?;
|
||||
let mut parts = status_line.split_whitespace();
|
||||
let version = parts.next().unwrap_or("");
|
||||
if !version.starts_with("HTTP/1.") {
|
||||
return Err("not an HTTP/1.x response".into());
|
||||
}
|
||||
let status: u16 = parts
|
||||
.next()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or("malformed status line")?;
|
||||
let chunked = head.lines().any(|l| {
|
||||
l.to_ascii_lowercase().starts_with("transfer-encoding:")
|
||||
&& l.to_ascii_lowercase().contains("chunked")
|
||||
});
|
||||
let body = if chunked {
|
||||
dechunk(body)
|
||||
} else {
|
||||
body.to_owned()
|
||||
};
|
||||
Ok(Response { status, body })
|
||||
}
|
||||
|
||||
fn dechunk(body: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = body;
|
||||
while let Some((size_line, after)) = rest.split_once("\r\n") {
|
||||
let Ok(size) = usize::from_str_radix(size_line.split(';').next().unwrap_or("").trim(), 16)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if size == 0 || after.len() < size {
|
||||
break;
|
||||
}
|
||||
out.push_str(&after[..size]);
|
||||
rest = after[size..].trim_start_matches("\r\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[test]
|
||||
fn parses_plain_and_chunked_bodies() {
|
||||
let plain = parse_response(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").unwrap();
|
||||
assert_eq!(
|
||||
plain,
|
||||
Response {
|
||||
status: 200,
|
||||
body: "{}".into()
|
||||
}
|
||||
);
|
||||
let chunked = parse_response(b"HTTP/1.1 503 Service Unavailable\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n4\r\n abc\r\n0\r\n\r\n").unwrap();
|
||||
assert_eq!((chunked.status, chunked.body.as_str()), (503, "hello abc"));
|
||||
assert!(parse_response(b"garbage").is_err());
|
||||
assert!(parse_response(b"SMTP/1.0 200\r\n\r\n").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gets_json_from_a_local_listener_and_sends_the_bearer_header() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = vec![0u8; 2048];
|
||||
let count = stream.read(&mut buffer).await.unwrap();
|
||||
let request = String::from_utf8_lossy(&buffer[..count]).into_owned();
|
||||
let body = r#"{"ready":true}"#;
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
request
|
||||
});
|
||||
let response = get(address, "/ready", Some("tok-123"), Duration::from_secs(5))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(response.status, response.body.as_str()),
|
||||
(200, r#"{"ready":true}"#)
|
||||
);
|
||||
let request = server.await.unwrap();
|
||||
assert!(
|
||||
request.starts_with("GET /ready HTTP/1.1\r\n")
|
||||
&& request.contains("Authorization: Bearer tok-123\r\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_remote_addresses_bad_paths_and_reports_refused_connections() {
|
||||
let remote: SocketAddr = "10.0.0.1:80".parse().unwrap();
|
||||
assert!(
|
||||
get(remote, "/", None, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("loopback")
|
||||
);
|
||||
let local: SocketAddr = "127.0.0.1:9".parse().unwrap();
|
||||
assert!(
|
||||
get(local, "/a b", None, Duration::from_secs(1))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
assert!(
|
||||
get(
|
||||
closed,
|
||||
"/",
|
||||
Some("secret-token-value"),
|
||||
Duration::from_secs(2)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Where everything lives: install prefix, private state, model volume.
|
||||
//!
|
||||
//! ```text
|
||||
//! PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec}
|
||||
//! PREFIX/lib/cublas/ CUDA 12 cuBLAS (only when the host has none)
|
||||
//! STATE/leleka.json run configuration (no secrets) 0600
|
||||
//! STATE/runtime.env tokens + LD_LIBRARY_PATH 0600
|
||||
//! STATE/api-key bearer key of the public API 0600
|
||||
//! STATE/daemon.json strata.json profile.json generated configs
|
||||
//! STATE/logs/*.log STATE/run/status.json STATE/stamps/*.json STATE/mtp-staging/
|
||||
//! ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(+.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/
|
||||
//! ```
|
||||
use crate::profile::{ARCHIVE_BYTES, SHARD_BYTES};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const BINARIES: [&str; 6] = [
|
||||
"leleka",
|
||||
"strata-next",
|
||||
"leleka-inference",
|
||||
"leleka-daemon",
|
||||
"leleka-cli",
|
||||
"leleka-seal-exec",
|
||||
];
|
||||
pub const SHARD_NAMES: [&str; 2] = [
|
||||
"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
|
||||
"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
|
||||
];
|
||||
pub const KAR_NAME: &str = "qwen-iq3-s-l2-v4.kar";
|
||||
pub const MTP_FILES: [&str; 4] = ["dense.bin", "dense.txt", "draft_vocab.bin", "experts.bin"];
|
||||
pub const MANIFEST: &str = "qwen-iq3-s";
|
||||
pub const MODEL_ID: &str = "qwen-iq3";
|
||||
pub const MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1";
|
||||
/// Digest of the pinned IQ3_S shard pair (`crates/leleka-runtime/src/backend.rs` `MODEL_DIGEST`).
|
||||
pub const MODEL_DIGEST: &str =
|
||||
"sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Dirs {
|
||||
pub prefix: PathBuf,
|
||||
pub state: PathBuf,
|
||||
pub assets: PathBuf,
|
||||
}
|
||||
|
||||
impl Dirs {
|
||||
/// Defaults: root gets `/opt/leleka`, `/var/lib/leleka`; a user gets XDG-style directories under `$HOME`.
|
||||
/// Environment overrides: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`.
|
||||
pub fn defaults(root: bool, home: Option<&Path>, env: &dyn Fn(&str) -> Option<String>) -> Dirs {
|
||||
let pick = |name: &str, fallback: PathBuf| env(name).map(PathBuf::from).unwrap_or(fallback);
|
||||
if root {
|
||||
Dirs {
|
||||
prefix: pick("LELEKA_PREFIX", "/opt/leleka".into()),
|
||||
state: pick("LELEKA_STATE", "/var/lib/leleka/state".into()),
|
||||
assets: pick("LELEKA_ASSETS", "/var/lib/leleka/assets".into()),
|
||||
}
|
||||
} else {
|
||||
let home = home.map(Path::to_path_buf).unwrap_or_else(|| "/tmp".into());
|
||||
Dirs {
|
||||
prefix: pick("LELEKA_PREFIX", home.join(".local/share/leleka")),
|
||||
state: pick("LELEKA_STATE", home.join(".local/state/leleka")),
|
||||
assets: pick("LELEKA_ASSETS", home.join(".local/share/leleka/assets")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paths(&self) -> Paths {
|
||||
Paths { dirs: self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Paths {
|
||||
pub dirs: Dirs,
|
||||
}
|
||||
|
||||
impl Paths {
|
||||
pub fn bin_dir(&self) -> PathBuf {
|
||||
self.dirs.prefix.join("bin")
|
||||
}
|
||||
pub fn bin(&self, name: &str) -> PathBuf {
|
||||
self.bin_dir().join(name)
|
||||
}
|
||||
pub fn cublas_dir(&self) -> PathBuf {
|
||||
self.dirs.prefix.join("lib/cublas")
|
||||
}
|
||||
pub fn run_config(&self) -> PathBuf {
|
||||
self.dirs.state.join("leleka.json")
|
||||
}
|
||||
pub fn env_file(&self) -> PathBuf {
|
||||
self.dirs.state.join("runtime.env")
|
||||
}
|
||||
pub fn api_key(&self) -> PathBuf {
|
||||
self.dirs.state.join("api-key")
|
||||
}
|
||||
pub fn daemon_config(&self) -> PathBuf {
|
||||
self.dirs.state.join("daemon.json")
|
||||
}
|
||||
pub fn strata_config(&self) -> PathBuf {
|
||||
self.dirs.state.join("strata.json")
|
||||
}
|
||||
pub fn profile_file(&self) -> PathBuf {
|
||||
self.dirs.state.join("profile.json")
|
||||
}
|
||||
pub fn logs(&self) -> PathBuf {
|
||||
self.dirs.state.join("logs")
|
||||
}
|
||||
pub fn run_dir(&self) -> PathBuf {
|
||||
self.dirs.state.join("run")
|
||||
}
|
||||
pub fn status_file(&self) -> PathBuf {
|
||||
self.run_dir().join("status.json")
|
||||
}
|
||||
pub fn stamps(&self) -> PathBuf {
|
||||
self.dirs.state.join("stamps")
|
||||
}
|
||||
pub fn mtp_staging(&self) -> PathBuf {
|
||||
self.dirs.state.join("mtp-staging")
|
||||
}
|
||||
pub fn shard(&self, index: usize) -> PathBuf {
|
||||
self.dirs.assets.join("model").join(SHARD_NAMES[index])
|
||||
}
|
||||
pub fn model_dir(&self) -> PathBuf {
|
||||
self.dirs.assets.join("model")
|
||||
}
|
||||
pub fn kar(&self) -> PathBuf {
|
||||
self.dirs.assets.join(KAR_NAME)
|
||||
}
|
||||
pub fn kar_provenance(&self) -> PathBuf {
|
||||
self.dirs.assets.join(format!("{KAR_NAME}.provenance.json"))
|
||||
}
|
||||
pub fn mtp_pack(&self) -> PathBuf {
|
||||
self.dirs.assets.join("data/mtp-rt")
|
||||
}
|
||||
pub fn tokenizer_root(&self) -> PathBuf {
|
||||
self.dirs.assets.join("tokenizer-assets")
|
||||
}
|
||||
pub fn tokenizer_dir(&self) -> PathBuf {
|
||||
self.tokenizer_root().join("tokenizer")
|
||||
}
|
||||
pub fn unit_name(&self) -> &'static str {
|
||||
"leleka.service"
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes still missing on the model volume, from the current sizes of the pinned files. A file with the wrong size
|
||||
/// counts as missing (fetch resumes or restarts it; the archive step refuses a wrong archive).
|
||||
pub fn missing_asset_bytes(paths: &Paths) -> (u64, u64) {
|
||||
let size = |path: PathBuf| {
|
||||
std::fs::metadata(path)
|
||||
.ok()
|
||||
.filter(|m| m.is_file())
|
||||
.map(|m| m.len())
|
||||
};
|
||||
let mut shards = 0u64;
|
||||
for (index, expected) in SHARD_BYTES.iter().enumerate() {
|
||||
let have = size(paths.shard(index)).unwrap_or(0);
|
||||
let part = size(
|
||||
paths
|
||||
.model_dir()
|
||||
.join(format!("{}.part", SHARD_NAMES[index])),
|
||||
)
|
||||
.unwrap_or(0);
|
||||
if have != *expected {
|
||||
shards += expected.saturating_sub(part.max(have.min(*expected)));
|
||||
}
|
||||
}
|
||||
let kar = if size(paths.kar()) == Some(ARCHIVE_BYTES) {
|
||||
0
|
||||
} else {
|
||||
// Sections, the final archive and slack: the guard in `ensure-sharded-streamed` is the exact bound.
|
||||
ARCHIVE_BYTES + ARCHIVE_BYTES / 5
|
||||
};
|
||||
(shards, kar)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn defaults_follow_the_user() {
|
||||
let none = |_: &str| None;
|
||||
let root = Dirs::defaults(true, None, &none);
|
||||
assert_eq!(root.prefix, PathBuf::from("/opt/leleka"));
|
||||
let user = Dirs::defaults(false, Some(Path::new("/home/para")), &none);
|
||||
assert_eq!(user.state, PathBuf::from("/home/para/.local/state/leleka"));
|
||||
let overridden = Dirs::defaults(false, Some(Path::new("/home/para")), &|name| {
|
||||
(name == "LELEKA_ASSETS").then(|| "/data/leleka".to_owned())
|
||||
});
|
||||
assert_eq!(overridden.assets, PathBuf::from("/data/leleka"));
|
||||
assert_eq!(
|
||||
overridden.prefix,
|
||||
PathBuf::from("/home/para/.local/share/leleka")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_derived_from_the_three_roots() {
|
||||
let dirs = Dirs {
|
||||
prefix: "/opt/leleka".into(),
|
||||
state: "/var/lib/leleka/state".into(),
|
||||
assets: "/data".into(),
|
||||
};
|
||||
let paths = dirs.paths();
|
||||
assert_eq!(
|
||||
paths.bin("leleka-inference"),
|
||||
PathBuf::from("/opt/leleka/bin/leleka-inference")
|
||||
);
|
||||
assert_eq!(
|
||||
paths.kar_provenance(),
|
||||
PathBuf::from("/data/qwen-iq3-s-l2-v4.kar.provenance.json")
|
||||
);
|
||||
assert_eq!(
|
||||
paths.tokenizer_dir(),
|
||||
PathBuf::from("/data/tokenizer-assets/tokenizer")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_bytes_of_an_empty_volume_are_the_whole_model() {
|
||||
let dir = std::env::temp_dir().join(format!("leleka-layout-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let paths = Dirs {
|
||||
prefix: dir.clone(),
|
||||
state: dir.clone(),
|
||||
assets: dir.join("assets"),
|
||||
}
|
||||
.paths();
|
||||
let (shards, kar) = missing_asset_bytes(&paths);
|
||||
assert_eq!(shards, SHARD_BYTES[0] + SHARD_BYTES[1]);
|
||||
assert!(kar > ARCHIVE_BYTES);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command.
|
||||
//!
|
||||
//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the
|
||||
//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness;
|
||||
//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`.
|
||||
pub mod app;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod facts;
|
||||
pub mod http;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
pub mod plan;
|
||||
pub mod preflight;
|
||||
pub mod profile;
|
||||
pub mod sealed;
|
||||
pub mod steps;
|
||||
pub mod supervisor;
|
||||
pub mod units;
|
||||
@@ -0,0 +1,6 @@
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let code = leleka_deploy::app::main_with(args).await;
|
||||
std::process::exit(code);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! `MANIFEST.json` of a release tarball (written by `scripts/package-release.sh`): what was built, from which
|
||||
//! commit, with which features, and the SHA-256 of every binary. `up` uses it to verify the binaries it installs
|
||||
//! and to know whether the sm_86 companion PTX are inside.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub schema_version: u32,
|
||||
pub version: String,
|
||||
pub git_commit: String,
|
||||
/// Cargo features the runtime binaries were built with (`sm86` among them for a two-architecture build).
|
||||
#[serde(default)]
|
||||
pub features: Vec<String>,
|
||||
/// Binary name -> lower-case hex SHA-256.
|
||||
#[serde(default)]
|
||||
pub binaries: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
pub fn has_sm86(&self) -> bool {
|
||||
self.features.iter().any(|f| f == "sm86")
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Manifest, String> {
|
||||
let manifest: Manifest =
|
||||
serde_json::from_str(text).map_err(|e| format!("invalid MANIFEST.json: {e}"))?;
|
||||
if manifest.schema_version != 1 {
|
||||
return Err(format!(
|
||||
"MANIFEST.json schema_version {} is not supported",
|
||||
manifest.schema_version
|
||||
));
|
||||
}
|
||||
for (name, digest) in &manifest.binaries {
|
||||
if name.contains('/')
|
||||
|| digest.len() != 64
|
||||
|| !digest.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(format!(
|
||||
"MANIFEST.json entry {name:?} is not a name and a SHA-256"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// Look for `MANIFEST.json` next to `bin_dir` (`PREFIX/MANIFEST.json`) or inside it.
|
||||
pub fn find(bin_dir: &Path) -> Option<Result<Manifest, String>> {
|
||||
[
|
||||
bin_dir.parent().map(|p| p.join("MANIFEST.json")),
|
||||
Some(bin_dir.join("MANIFEST.json")),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|path| path.is_file())
|
||||
.map(|path| {
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
|
||||
Manifest::parse(&text)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_features_and_digests() {
|
||||
let digest = "a".repeat(64);
|
||||
let text = format!(
|
||||
r#"{{"schema_version":1,"version":"0.1.0","git_commit":"abc","features":["sm86"],"binaries":{{"leleka":"{digest}"}},"extra":1}}"#
|
||||
);
|
||||
let manifest = Manifest::parse(&text).unwrap();
|
||||
assert!(manifest.has_sm86());
|
||||
assert_eq!(manifest.binaries["leleka"], digest);
|
||||
assert!(Manifest::parse(r#"{"schema_version":2,"version":"","git_commit":""}"#).is_err());
|
||||
assert!(
|
||||
Manifest::parse(
|
||||
r#"{"schema_version":1,"version":"","git_commit":"","binaries":{"a/b":"00"}}"#
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
!Manifest::parse(r#"{"schema_version":1,"version":"","git_commit":""}"#)
|
||||
.unwrap()
|
||||
.has_sm86()
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,344 @@
|
||||
//! Memory profiles: which GPU class gets which budget, context ceiling, KAR source and RAM floor.
|
||||
//!
|
||||
//! The built-in profiles are the JSON files in `deploy/rust-runtime/profiles/`, embedded at build time so the binary
|
||||
//! needs no data directory. `--profile FILE` replaces them with an operator file of the same shape. A profile only
|
||||
//! selects documented switches of `leleka-inference`; it never changes the model, the quantization or the backend
|
||||
//! mode, so choosing one is not a quality decision.
|
||||
use crate::facts::Gpu;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
/// Bytes of the pinned level-2 KAR archive (`InheritedKarArchive` admits exactly this length).
|
||||
pub const ARCHIVE_BYTES: u64 = 55_295_529_472;
|
||||
/// Bytes of the two pinned IQ3_S GGUF shards.
|
||||
pub const SHARD_BYTES: [u64; 2] = [54_817_524_224, 28_800_138_432];
|
||||
|
||||
pub const BUILTIN: [(&str, &str); 2] = [
|
||||
(
|
||||
"rtx5090-32g",
|
||||
include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g.json"),
|
||||
),
|
||||
(
|
||||
"rtx3080-16g",
|
||||
include_str!("../../../deploy/rust-runtime/profiles/rtx3080-16g.json"),
|
||||
),
|
||||
];
|
||||
|
||||
const PREFILL_CAPACITIES: [u32; 8] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192];
|
||||
|
||||
/// How the engine receives the KAR archive.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum KarSource {
|
||||
/// A sealed memfd made by the supervisor: the whole archive lives in RAM (shmem) while the service runs.
|
||||
Memfd,
|
||||
/// An ordinary read-only file (`--kar-archive-file`): only the pages that are read pass through the file cache.
|
||||
File,
|
||||
}
|
||||
|
||||
impl KarSource {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
KarSource::Memfd => "memfd",
|
||||
KarSource::File => "file",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the routed experts are admitted (`leleka-inference --expert-source`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ExpertSource {
|
||||
/// A page-locked RAM copy of the routed experts (about 50 GB): the server form.
|
||||
Resident,
|
||||
/// Read-only mappings of shard 0, nothing copied: the low-RAM form.
|
||||
Mapped,
|
||||
}
|
||||
|
||||
impl ExpertSource {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ExpertSource::Resident => "resident",
|
||||
ExpertSource::Mapped => "mapped",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Automatic selection window (`sm` is compute capability times ten; `sm_max` and `vram_mib_max` are exclusive).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Selector {
|
||||
pub sm_min: u32,
|
||||
pub sm_max: u32,
|
||||
pub vram_mib_min: u64,
|
||||
pub vram_mib_max: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Profile {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub select: Selector,
|
||||
pub gpu_budget_bytes: u64,
|
||||
pub context_tokens: u32,
|
||||
#[serde(default)]
|
||||
pub prefill_capacity: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub kv: Option<String>,
|
||||
#[serde(default)]
|
||||
pub kv_resident: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub prompt_cache: Option<u32>,
|
||||
pub kar_source: KarSource,
|
||||
pub expert_source: ExpertSource,
|
||||
pub min_driver_major: u32,
|
||||
pub min_vram_total_mib: u64,
|
||||
/// Free VRAM required at start. Defaults to the budget; a profile whose budget is an upper bound that the
|
||||
/// engine does not fully reach (the laptop: 15 GiB budget, 14.2 GiB measured peak) names the measured need.
|
||||
#[serde(default)]
|
||||
pub min_vram_free_mib: Option<u64>,
|
||||
pub min_ram_total_bytes: u64,
|
||||
pub min_ram_available_bytes: u64,
|
||||
/// Advice only: the `memory=` value for `.wslconfig` when WSL2 gives the VM too little.
|
||||
#[serde(default)]
|
||||
pub wsl_memory_gib: Option<u32>,
|
||||
/// Path relative to the assets directory of an optional ranked expert profile (VRAM expert tier).
|
||||
#[serde(default)]
|
||||
pub expert_profile: Option<String>,
|
||||
#[serde(default)]
|
||||
pub expert_profile_sha256: Option<String>,
|
||||
/// Extra `LELEKA_ORIGINAL_SERVE_*` switches for the engine process.
|
||||
#[serde(default)]
|
||||
pub engine_env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn builtin(name: &str) -> Option<Profile> {
|
||||
BUILTIN
|
||||
.iter()
|
||||
.find(|(candidate, _)| *candidate == name)
|
||||
.map(|(_, text)| {
|
||||
let profile: Profile =
|
||||
serde_json::from_str(text).expect("built-in profile JSON is valid");
|
||||
profile
|
||||
})
|
||||
}
|
||||
|
||||
pub fn builtins() -> Vec<Profile> {
|
||||
BUILTIN
|
||||
.iter()
|
||||
.map(|(name, _)| Profile::builtin(name).expect("built-in"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn from_file(path: &Path) -> Result<Profile, String> {
|
||||
let bytes = std::fs::read(path)
|
||||
.map_err(|error| format!("cannot read profile {}: {error}", path.display()))?;
|
||||
if bytes.len() > 64 * 1024 {
|
||||
return Err("profile file exceeds 64 KiB".into());
|
||||
}
|
||||
let profile: Profile = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| format!("invalid profile {}: {error}", path.display()))?;
|
||||
profile.validate()?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.name.is_empty()
|
||||
|| self.name.len() > 64
|
||||
|| !self
|
||||
.name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
|
||||
{
|
||||
return Err("profile name must be 1..64 characters of [A-Za-z0-9._-]".into());
|
||||
}
|
||||
if self.gpu_budget_bytes < (1 << 30) || self.gpu_budget_bytes > (1 << 40) {
|
||||
return Err("gpu_budget_bytes must be between 1 GiB and 1 TiB".into());
|
||||
}
|
||||
if !(1..=262_144).contains(&self.context_tokens) {
|
||||
return Err("context_tokens must be 1..=262144 for the Original serve path".into());
|
||||
}
|
||||
if let Some(capacity) = self.prefill_capacity
|
||||
&& !PREFILL_CAPACITIES.contains(&capacity)
|
||||
{
|
||||
return Err(format!(
|
||||
"prefill_capacity must be one of {PREFILL_CAPACITIES:?}"
|
||||
));
|
||||
}
|
||||
if let Some(kv) = &self.kv
|
||||
&& kv != "int8"
|
||||
{
|
||||
return Err("kv must be int8 (the engine refuses other formats)".into());
|
||||
}
|
||||
if let Some(digest) = &self.expert_profile_sha256
|
||||
&& (digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
{
|
||||
return Err("expert_profile_sha256 must be 64 hex digits".into());
|
||||
}
|
||||
if let Some(path) = &self.expert_profile
|
||||
&& (path.is_empty()
|
||||
|| path.starts_with('/')
|
||||
|| path.split('/').any(|part| part == ".." || part.is_empty()))
|
||||
{
|
||||
return Err(
|
||||
"expert_profile must be a relative path inside the assets directory".into(),
|
||||
);
|
||||
}
|
||||
for (key, value) in &self.engine_env {
|
||||
if !key.starts_with("LELEKA_ORIGINAL_SERVE_")
|
||||
|| !key
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
|
||||
{
|
||||
return Err(format!(
|
||||
"engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_* name"
|
||||
));
|
||||
}
|
||||
if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) {
|
||||
return Err(format!(
|
||||
"engine_env value of {key} is empty or not printable"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True when the compute capability and VRAM of `gpu` fall inside the selection window.
|
||||
pub fn matches(&self, gpu: &Gpu) -> bool {
|
||||
let Some(sm) = gpu.sm else { return false };
|
||||
(self.select.sm_min..self.select.sm_max).contains(&sm)
|
||||
&& (self.select.vram_mib_min..self.select.vram_mib_max).contains(&gpu.vram_total_mib)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve `--profile`: `auto` (or nothing), a built-in name, or a path to a JSON file.
|
||||
pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result<Profile, String> {
|
||||
let spec = spec.unwrap_or("auto");
|
||||
if spec != "auto" {
|
||||
if let Some(profile) = Profile::builtin(spec) {
|
||||
return Ok(profile);
|
||||
}
|
||||
if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") {
|
||||
return Profile::from_file(Path::new(spec));
|
||||
}
|
||||
let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect();
|
||||
return Err(format!(
|
||||
"unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)",
|
||||
names.join(", ")
|
||||
));
|
||||
}
|
||||
let gpu = gpu.ok_or(
|
||||
"no NVIDIA GPU was detected, so no profile can be selected automatically; pass --profile NAME|FILE",
|
||||
)?;
|
||||
let matches: Vec<Profile> = Profile::builtins()
|
||||
.into_iter()
|
||||
.filter(|profile| profile.matches(gpu))
|
||||
.collect();
|
||||
match matches.len() {
|
||||
1 => Ok(matches.into_iter().next().expect("one")),
|
||||
0 => Err(format!(
|
||||
"no built-in profile fits {} (sm_{}, {} MiB); built-in: {}; write a profile file from `leleka profiles show NAME` and pass --profile FILE",
|
||||
gpu.name,
|
||||
gpu.sm.map_or("?".into(), |sm| sm.to_string()),
|
||||
gpu.vram_total_mib,
|
||||
BUILTIN
|
||||
.iter()
|
||||
.map(|(name, _)| *name)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)),
|
||||
_ => Err("more than one built-in profile matches; pass --profile NAME".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn gpu(name: &str, sm: u32, mib: u64) -> Gpu {
|
||||
Gpu {
|
||||
index: 0,
|
||||
name: name.into(),
|
||||
driver: "595.99.02".into(),
|
||||
vram_total_mib: mib,
|
||||
vram_free_mib: mib,
|
||||
sm: Some(sm),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn built_in_profiles_parse_and_validate() {
|
||||
for profile in Profile::builtins() {
|
||||
profile.validate().unwrap();
|
||||
}
|
||||
assert_eq!(Profile::builtins().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_selection_picks_the_server_and_the_laptop_profile() {
|
||||
let server = resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap();
|
||||
assert_eq!(server.name, "rtx5090-32g");
|
||||
assert_eq!(server.kar_source, KarSource::Memfd);
|
||||
let laptop = resolve(
|
||||
Some("auto"),
|
||||
Some(&gpu("NVIDIA GeForce RTX 3080 Laptop GPU", 86, 16384)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(laptop.name, "rtx3080-16g");
|
||||
assert_eq!(laptop.kar_source, KarSource::File);
|
||||
assert_eq!(laptop.context_tokens, 8192);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_gpu_and_missing_gpu_give_actionable_errors() {
|
||||
let error = resolve(None, Some(&gpu("NVIDIA GeForce RTX 4090", 89, 24564))).unwrap_err();
|
||||
assert!(error.contains("--profile FILE"), "{error}");
|
||||
assert!(resolve(None, None).unwrap_err().contains("--profile"));
|
||||
assert!(
|
||||
resolve(Some("nope"), None)
|
||||
.unwrap_err()
|
||||
.contains("rtx5090-32g")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_name_overrides_the_detected_gpu() {
|
||||
let forced = resolve(
|
||||
Some("rtx3080-16g"),
|
||||
Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(forced.name, "rtx3080-16g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_rejects_unsafe_values() {
|
||||
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
|
||||
profile
|
||||
.engine_env
|
||||
.insert("LD_PRELOAD".into(), "/tmp/x.so".into());
|
||||
assert!(profile.validate().unwrap_err().contains("LD_PRELOAD"));
|
||||
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
|
||||
profile.context_tokens = 524_288;
|
||||
assert!(profile.validate().is_err());
|
||||
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
|
||||
profile.prefill_capacity = Some(1000);
|
||||
assert!(profile.validate().is_err());
|
||||
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
||||
profile.expert_profile = Some("../x".into());
|
||||
assert!(profile.validate().is_err());
|
||||
profile.expert_profile = Some("/etc/passwd".into());
|
||||
assert!(profile.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_fields_in_a_profile_file_are_refused() {
|
||||
let text = BUILTIN[0]
|
||||
.1
|
||||
.replace("\"engine_env\": {}", "\"engine_env\": {}, \"typo\": 1");
|
||||
assert!(serde_json::from_str::<Profile>(&text).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! The sealed KAR archive, made by the service itself (no helper process, no Python).
|
||||
//!
|
||||
//! `leleka run` copies the archive once into an irrevocably sealed `memfd` and keeps it for its whole life, so an
|
||||
//! engine restart does not copy 55 GB again. The engine refuses anything but a regular, unlinked file of the
|
||||
//! pinned length with `WRITE | GROW | SHRINK | SEAL` seals (`InheritedKarArchive::open`). The descriptor is
|
||||
//! `CLOEXEC` in the supervisor and reaches only the engine: the supervisor hands a duplicate to `leleka
|
||||
//! exec-inherit` as standard input, and that shim moves it to a descriptor number >= 3 without close-on-exec and
|
||||
//! `exec`s the engine, which reopens it through `/proc/self/fd/N`.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::*;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn seal_file(
|
||||
_path: &std::path::Path,
|
||||
_expect_bytes: Option<u64>,
|
||||
_progress: &mut dyn FnMut(u64, u64),
|
||||
) -> Result<std::fs::File, String> {
|
||||
Err("sealed memfd archives require Linux".into())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> {
|
||||
Err("inherited descriptors require Linux".into())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn open_inherited(_fd: u32) -> Result<std::fs::File, String> {
|
||||
Err("inherited descriptors require Linux".into())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn exec_inherit(_args: &[String]) -> Result<std::convert::Infallible, String> {
|
||||
Err("exec-inherit requires Linux".into())
|
||||
}
|
||||
|
||||
pub const PLACEHOLDER: &str = "{FD}";
|
||||
|
||||
/// Replace every `{FD}` in `args`.
|
||||
pub fn substitute(args: &[String], number: i32) -> Vec<String> {
|
||||
args.iter()
|
||||
.map(|arg| arg.replace(PLACEHOLDER, &number.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux {
|
||||
use super::substitute;
|
||||
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
os::{
|
||||
fd::{AsFd, IntoRawFd},
|
||||
unix::process::CommandExt,
|
||||
},
|
||||
path::Path,
|
||||
process::Command,
|
||||
};
|
||||
|
||||
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
|
||||
SealFlags::WRITE.bits()
|
||||
| SealFlags::GROW.bits()
|
||||
| SealFlags::SHRINK.bits()
|
||||
| SealFlags::SEAL.bits(),
|
||||
);
|
||||
const CHUNK: usize = 16 << 20;
|
||||
|
||||
/// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets
|
||||
/// (copied, total) about every 4 GiB.
|
||||
pub fn seal_file(
|
||||
path: &Path,
|
||||
expect_bytes: Option<u64>,
|
||||
progress: &mut dyn FnMut(u64, u64),
|
||||
) -> Result<File, String> {
|
||||
let mut source =
|
||||
File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
let metadata = source
|
||||
.metadata()
|
||||
.map_err(|e| format!("cannot inspect the archive: {e}"))?;
|
||||
if !metadata.is_file() {
|
||||
return Err("the archive must be a regular file".into());
|
||||
}
|
||||
if let Some(expected) = expect_bytes
|
||||
&& metadata.len() != expected
|
||||
{
|
||||
return Err(format!(
|
||||
"the archive has {} bytes, expected {expected}",
|
||||
metadata.len()
|
||||
));
|
||||
}
|
||||
let fd = memfd_create(
|
||||
"leleka-sealed-archive",
|
||||
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
|
||||
)
|
||||
.map_err(|e| format!("memfd_create failed: {e}"))?;
|
||||
let mut memory = File::from(fd);
|
||||
let mut buffer = vec![0u8; CHUNK];
|
||||
let total = metadata.len();
|
||||
let (mut copied, mut reported) = (0u64, 0u64);
|
||||
loop {
|
||||
let count = source
|
||||
.read(&mut buffer)
|
||||
.map_err(|e| format!("read failed: {e}"))?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
memory
|
||||
.write_all(&buffer[..count])
|
||||
.map_err(|e| format!("write to memfd failed (out of memory?): {e}"))?;
|
||||
copied += count as u64;
|
||||
if copied - reported >= 4 << 30 {
|
||||
reported = copied;
|
||||
progress(copied, total);
|
||||
}
|
||||
}
|
||||
if copied != total {
|
||||
return Err("the archive changed while it was being copied".into());
|
||||
}
|
||||
fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
|
||||
if !fcntl_get_seals(&memory)
|
||||
.map_err(|e| format!("cannot read seals: {e}"))?
|
||||
.contains(SEALS)
|
||||
{
|
||||
return Err("the kernel did not apply every seal".into());
|
||||
}
|
||||
progress(total, total);
|
||||
Ok(memory)
|
||||
}
|
||||
|
||||
/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an
|
||||
/// independent read-only description. The original number stays open and untouched.
|
||||
pub fn open_inherited(fd: u32) -> Result<File, String> {
|
||||
if !(3..=1_048_576).contains(&fd) {
|
||||
return Err("an inherited descriptor must be 3 or higher".into());
|
||||
}
|
||||
File::open(format!("/proc/self/fd/{fd}"))
|
||||
.map_err(|e| format!("descriptor {fd} is not open in this process: {e}"))
|
||||
}
|
||||
|
||||
/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked
|
||||
/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start.
|
||||
pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let file = open_inherited(fd)?;
|
||||
let meta = file
|
||||
.metadata()
|
||||
.map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?;
|
||||
if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes {
|
||||
return Err(format!(
|
||||
"descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)",
|
||||
meta.len(),
|
||||
meta.nlink()
|
||||
));
|
||||
}
|
||||
if !fcntl_get_seals(&file)
|
||||
.map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))?
|
||||
.contains(SEALS)
|
||||
{
|
||||
return Err(format!(
|
||||
"descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor
|
||||
/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`.
|
||||
pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
|
||||
let command = match args.split_first() {
|
||||
Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest,
|
||||
_ => return Err(
|
||||
"usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)"
|
||||
.into(),
|
||||
),
|
||||
};
|
||||
let stdin = std::io::stdin();
|
||||
let moved = rustix::io::dup(stdin.as_fd())
|
||||
.map_err(|e| format!("cannot duplicate standard input: {e}"))?;
|
||||
let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?;
|
||||
rustix::stdio::dup2_stdin(&devnull)
|
||||
.map_err(|e| format!("cannot replace standard input: {e}"))?;
|
||||
let number = moved.into_raw_fd();
|
||||
if number < 3 {
|
||||
return Err("the sealed descriptor landed on a standard stream".into());
|
||||
}
|
||||
let arguments = substitute(&command[1..], number);
|
||||
let error = Command::new(&command[0]).args(arguments).exec();
|
||||
Err(format!("cannot execute {:?}: {error}", command[0]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
#[test]
|
||||
fn seal_is_exact_sealed_unlinked_and_cloexec() {
|
||||
let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id()));
|
||||
let payload: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
|
||||
std::fs::write(&path, &payload).unwrap();
|
||||
let mut calls = Vec::new();
|
||||
let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| {
|
||||
calls.push((a, b))
|
||||
})
|
||||
.unwrap();
|
||||
let meta = sealed.metadata().unwrap();
|
||||
assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
||||
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
||||
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
|
||||
assert!(
|
||||
rustix::io::fcntl_getfd(&sealed)
|
||||
.unwrap()
|
||||
.contains(rustix::io::FdFlags::CLOEXEC)
|
||||
);
|
||||
assert_eq!(
|
||||
calls.last(),
|
||||
Some(&(payload.len() as u64, payload.len() as u64))
|
||||
);
|
||||
// A descriptor reopened through /proc keeps the properties the engine checks.
|
||||
let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32;
|
||||
let reopened = open_inherited(number).unwrap();
|
||||
let meta = reopened.metadata().unwrap();
|
||||
assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
||||
assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err());
|
||||
assert!(open_inherited(1).is_err());
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_inherit_needs_a_command() {
|
||||
assert!(exec_inherit(&[]).is_err());
|
||||
assert!(exec_inherit(&["--".into()]).is_err());
|
||||
assert!(exec_inherit(&["cmd".into()]).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn placeholder_substitution() {
|
||||
let args = vec![
|
||||
"--kar-archive-fd".to_owned(),
|
||||
"{FD}".to_owned(),
|
||||
"x{FD}y".to_owned(),
|
||||
];
|
||||
assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,199 @@
|
||||
//! systemd unit for the supervisor (`leleka run`). One unit runs the whole service; the supervisor owns the
|
||||
//! engine, gateway and API children, restarts the engine without copying the archive again, and drains on
|
||||
//! SIGTERM/SIGINT.
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UnitScope {
|
||||
/// `/etc/systemd/system`, started at boot, `User=` the owner of the state directory.
|
||||
System,
|
||||
/// `~/.config/systemd/user`; needs `loginctl enable-linger USER` to start without a login session.
|
||||
User,
|
||||
}
|
||||
|
||||
fn quote(path: &Path) -> Result<String, String> {
|
||||
let text = path.to_str().ok_or("path is not UTF-8")?;
|
||||
if !text.starts_with('/')
|
||||
|| text
|
||||
.chars()
|
||||
.any(|c| c.is_control() || c == '"' || c == '\\' || c == '%' || c == '$')
|
||||
{
|
||||
return Err(format!(
|
||||
"path {text:?} cannot be used in a unit file (must be absolute without quotes, %, $ or control characters)"
|
||||
));
|
||||
}
|
||||
Ok(if text.contains(' ') {
|
||||
format!("\"{text}\"")
|
||||
} else {
|
||||
text.to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Render the unit. `user` is only used for the system scope.
|
||||
pub fn render(
|
||||
scope: UnitScope,
|
||||
prefix: &Path,
|
||||
state: &Path,
|
||||
user: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let bin = quote(&prefix.join("bin/leleka"))?;
|
||||
let config = quote(&state.join("leleka.json"))?;
|
||||
let env_file = quote(&state.join("runtime.env"))?;
|
||||
let mut unit = String::new();
|
||||
unit.push_str("# Generated by `leleka up`; edit the run configuration, not this file.\n");
|
||||
unit.push_str("[Unit]\n");
|
||||
unit.push_str("Description=Leleka runtime (engine, gateway and API on loopback)\n");
|
||||
unit.push_str("Documentation=https://github.com/paveldhq/strata-next (docs/deploy.md)\n");
|
||||
unit.push_str("After=network.target\n");
|
||||
unit.push_str("StartLimitIntervalSec=1800\nStartLimitBurst=3\n\n");
|
||||
unit.push_str("[Service]\n");
|
||||
unit.push_str("Type=exec\n");
|
||||
if scope == UnitScope::System {
|
||||
let user = user.ok_or("a system unit needs a service user")?;
|
||||
if user.is_empty()
|
||||
|| !user
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
|
||||
{
|
||||
return Err("service user must be [A-Za-z0-9_.-]+".into());
|
||||
}
|
||||
unit.push_str(&format!("User={user}\n"));
|
||||
}
|
||||
unit.push_str(&format!("EnvironmentFile={env_file}\n"));
|
||||
unit.push_str("UMask=0077\nNoNewPrivileges=yes\n");
|
||||
// Pinned host memory (cudaHostAlloc/Register) is counted against RLIMIT_MEMLOCK on some drivers.
|
||||
unit.push_str("LimitMEMLOCK=infinity\n");
|
||||
unit.push_str(&format!("ExecStart={bin} run --config {config}\n"));
|
||||
// A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error.
|
||||
unit.push_str("Restart=on-failure\nRestartSec=30\nRestartPreventExitStatus=2\n");
|
||||
// The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine.
|
||||
unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=120\nKillMode=mixed\n\n");
|
||||
unit.push_str("[Install]\n");
|
||||
unit.push_str(match scope {
|
||||
UnitScope::System => "WantedBy=multi-user.target\n",
|
||||
UnitScope::User => "WantedBy=default.target\n",
|
||||
});
|
||||
Ok(unit)
|
||||
}
|
||||
|
||||
pub fn unit_path(
|
||||
scope: UnitScope,
|
||||
home: Option<&Path>,
|
||||
name: &str,
|
||||
) -> Result<std::path::PathBuf, String> {
|
||||
match scope {
|
||||
UnitScope::System => Ok(Path::new("/etc/systemd/system").join(name)),
|
||||
UnitScope::User => {
|
||||
let home = home.ok_or("HOME is not set")?;
|
||||
Ok(home.join(".config/systemd/user").join(name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn system_unit_is_complete_and_bounded() {
|
||||
let unit = render(
|
||||
UnitScope::System,
|
||||
Path::new("/opt/leleka"),
|
||||
Path::new("/var/lib/leleka/state"),
|
||||
Some("leleka"),
|
||||
)
|
||||
.unwrap();
|
||||
for needle in [
|
||||
"User=leleka",
|
||||
"EnvironmentFile=/var/lib/leleka/state/runtime.env",
|
||||
"ExecStart=/opt/leleka/bin/leleka run --config /var/lib/leleka/state/leleka.json",
|
||||
"Restart=on-failure",
|
||||
"RestartPreventExitStatus=2",
|
||||
"StartLimitBurst=3",
|
||||
"LimitMEMLOCK=infinity",
|
||||
"KillSignal=SIGTERM",
|
||||
"WantedBy=multi-user.target",
|
||||
] {
|
||||
assert!(unit.contains(needle), "missing {needle}\n{unit}");
|
||||
}
|
||||
assert!(!unit.contains("Password") && !unit.contains("TOKEN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_unit_has_no_user_line_and_targets_default() {
|
||||
let unit = render(
|
||||
UnitScope::User,
|
||||
Path::new("/home/p/.local/share/leleka"),
|
||||
Path::new("/home/p/.local/state/leleka"),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!unit.contains("User=") && unit.contains("WantedBy=default.target"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dangerous_paths_and_users_are_refused() {
|
||||
assert!(
|
||||
render(
|
||||
UnitScope::System,
|
||||
Path::new("/opt/le%leka"),
|
||||
Path::new("/s"),
|
||||
Some("u")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
render(
|
||||
UnitScope::System,
|
||||
Path::new("/opt/leleka"),
|
||||
Path::new("relative"),
|
||||
Some("u")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
render(
|
||||
UnitScope::System,
|
||||
Path::new("/opt/leleka"),
|
||||
Path::new("/s"),
|
||||
Some("a b")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
render(
|
||||
UnitScope::System,
|
||||
Path::new("/opt/leleka"),
|
||||
Path::new("/s"),
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let spaced = render(
|
||||
UnitScope::User,
|
||||
Path::new("/opt/my leleka"),
|
||||
Path::new("/s"),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(spaced.contains("\"/opt/my leleka/bin/leleka\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_locations() {
|
||||
assert_eq!(
|
||||
unit_path(UnitScope::System, None, "leleka.service").unwrap(),
|
||||
Path::new("/etc/systemd/system/leleka.service")
|
||||
);
|
||||
assert_eq!(
|
||||
unit_path(
|
||||
UnitScope::User,
|
||||
Some(Path::new("/home/p")),
|
||||
"leleka.service"
|
||||
)
|
||||
.unwrap(),
|
||||
Path::new("/home/p/.config/systemd/user/leleka.service")
|
||||
);
|
||||
assert!(unit_path(UnitScope::User, None, "x").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,889 @@
|
||||
//! 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"));
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Static checks of the packaging recipes (no container engine needed): the OCI recipe keeps the model and
|
||||
//! secrets out of the image, runs non-root with a health check, and the install script is valid POSIX sh.
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn repo() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
||||
}
|
||||
|
||||
fn read(relative: &str) -> String {
|
||||
std::fs::read_to_string(repo().join(relative)).unwrap_or_else(|e| panic!("{relative}: {e}"))
|
||||
}
|
||||
|
||||
/// The instruction lines of a Containerfile (comments and blank lines removed, continuations joined).
|
||||
fn instructions(text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current = String::new();
|
||||
for line in text.lines() {
|
||||
let line = line.trim_end();
|
||||
if line.trim_start().starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(stripped) = line.strip_suffix('\\') {
|
||||
current.push_str(stripped.trim_start());
|
||||
current.push(' ');
|
||||
} else {
|
||||
current.push_str(line.trim_start());
|
||||
out.push(std::mem::take(&mut current));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_oci_recipe_is_non_root_checked_and_model_free() {
|
||||
let text = read("deploy/Containerfile.rust-runtime");
|
||||
let lines = instructions(&text);
|
||||
let find = |prefix: &str| {
|
||||
lines
|
||||
.iter()
|
||||
.filter(|l| l.starts_with(prefix))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Non-root, and the last USER wins.
|
||||
assert_eq!(
|
||||
find("USER ").last().map(String::as_str),
|
||||
Some("USER 10001:10001")
|
||||
);
|
||||
// A health check that does not need a GPU probe.
|
||||
let health = find("HEALTHCHECK").join(" ");
|
||||
assert!(
|
||||
health.contains("/opt/leleka/bin/leleka") && health.contains("status"),
|
||||
"{health}"
|
||||
);
|
||||
// The model volume is external: declared, never copied.
|
||||
assert!(find("VOLUME").join(" ").contains("/models"));
|
||||
for copy in find("COPY").iter().chain(find("ADD").iter()) {
|
||||
let lower = copy.to_ascii_lowercase();
|
||||
for forbidden in [
|
||||
".gguf",
|
||||
".kar",
|
||||
"mtp-rt",
|
||||
"api-key",
|
||||
"runtime.env",
|
||||
"token",
|
||||
"secret",
|
||||
] {
|
||||
assert!(
|
||||
!lower.contains(forbidden),
|
||||
"{copy} would bake {forbidden} into the image"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Only the binaries, the cuBLAS libraries and the manifests are copied in.
|
||||
let copies: Vec<String> = find("COPY");
|
||||
assert!(copies.iter().any(|c| c.contains("bin/ /opt/leleka/bin/")));
|
||||
assert!(copies.iter().any(|c| c.contains("--from=cublas")));
|
||||
// The cuBLAS download is checksum-pinned.
|
||||
assert!(
|
||||
find("ADD")
|
||||
.iter()
|
||||
.any(|a| a.contains("--checksum=sha256:${CUBLAS_SHA256}"))
|
||||
);
|
||||
assert!(text.contains("546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"));
|
||||
// No secret-looking environment, no ssh keys, no package-manager network step in the runtime stage.
|
||||
for env in find("ENV") {
|
||||
assert!(
|
||||
!env.to_ascii_uppercase().contains("TOKEN")
|
||||
&& !env.to_ascii_uppercase().contains("KEY="),
|
||||
"{env}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
find("ENTRYPOINT"),
|
||||
vec![r#"ENTRYPOINT ["/opt/leleka/bin/leleka"]"#.to_string()]
|
||||
);
|
||||
assert!(find("CMD").join(" ").contains("--foreground"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cublas_pin_matches_the_tool_and_the_documentation() {
|
||||
let recipe = read("deploy/Containerfile.rust-runtime");
|
||||
let plan = read("crates/deploy/src/plan.rs");
|
||||
for pinned in [
|
||||
"546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057",
|
||||
"libcublas-linux-x86_64-12.9.1.4-archive.tar.xz",
|
||||
] {
|
||||
assert!(
|
||||
recipe.contains(pinned) && plan.contains(pinned),
|
||||
"{pinned} differs between the recipe and plan.rs"
|
||||
);
|
||||
assert!(read("docs/rust-runtime-run.md").contains(pinned));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_script_is_valid_sh_and_verifies_before_it_runs() {
|
||||
let script = repo().join("deploy/rust-runtime/install.sh");
|
||||
let status = std::process::Command::new("sh")
|
||||
.arg("-n")
|
||||
.arg(&script)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
let text = read("deploy/rust-runtime/install.sh");
|
||||
let verify = text
|
||||
.find("sha256sum --quiet -c SHA256SUMS")
|
||||
.expect("verifies the release");
|
||||
let run = text
|
||||
.find("exec ./bin/leleka up")
|
||||
.expect("hands over to leleka up");
|
||||
assert!(
|
||||
verify < run,
|
||||
"the checksum check must come before the hand-over"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systemd_unit_templates_do_not_carry_secrets() {
|
||||
for template in [
|
||||
"leleka-daemon.service",
|
||||
"leleka-inference.service",
|
||||
"runtime.env.example",
|
||||
] {
|
||||
let text = read(&format!("deploy/rust-runtime/{template}"));
|
||||
assert!(
|
||||
!text
|
||||
.lines()
|
||||
.any(|l| l.trim_start().starts_with("Environment=") && l.contains("TOKEN")),
|
||||
"{template}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
pub(crate) mod original_prompt;
|
||||
#[path = "backend_original_serve.rs"]
|
||||
mod original_serve;
|
||||
pub use original_serve::{OriginalServeChoice, OriginalServeMode, OriginalServeOptions};
|
||||
pub use original_serve::{ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions};
|
||||
use crate::experimental::{self as experimental_modes, ExperimentalConfig};
|
||||
use crate::model_binding::kar_expert_source::KarExpertSource;
|
||||
pub use crate::model_binding::kar_expert_source::{
|
||||
@@ -1268,11 +1268,15 @@ fn serve_load(
|
||||
};
|
||||
// Only this fresh unpublished selected binding can gain the raw RAM bank.
|
||||
// Complete GGUF/KAR/MTP admission already finished; no sessions or Ready exist.
|
||||
if optimized.is_some() {
|
||||
// The Original serve stack reads the same bank (CPU window tier, prompt arena); without it the stack's
|
||||
// arena fails with InputRead at Load. The operator picks the RAM copy (server) or the mappings (laptop).
|
||||
if optimized.is_some() || original.is_some() {
|
||||
(if streamed_spill {
|
||||
binding.adopt_resident_expert_capture(expert_capture.ok_or_else(|| {
|
||||
load_failure(LoadPhase::SelectedBinding, invalid("streamed expert capture absent"))
|
||||
})?)
|
||||
} else if original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped) {
|
||||
binding.load_mapped_expert_source()
|
||||
} else {
|
||||
binding.load_resident_expert_source()
|
||||
}).map_err(|error| {
|
||||
|
||||
@@ -39,6 +39,32 @@ impl OriginalServeMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the routed experts come from for the Original path. The window CPU tier and the prompt arena read the
|
||||
/// bank of the selected binding, so exactly one form must be admitted before the stack opens.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum ExpertSource {
|
||||
/// A RAM copy of the routed experts of shard 0 (about 50 GB, page-locked): the server form, as the serve smoke does.
|
||||
#[default]
|
||||
Resident,
|
||||
/// Read-only shared mappings of shard 0, nothing copied: the low-RAM (laptop) form, `docs/laptop-profile.md`.
|
||||
Mapped,
|
||||
}
|
||||
impl ExpertSource {
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text {
|
||||
"resident" => Some(Self::Resident),
|
||||
"mapped" => Some(Self::Mapped),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Resident => "resident",
|
||||
Self::Mapped => "mapped",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Operator choices of the Original path. Nothing here enters an RPC.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OriginalServeOptions {
|
||||
@@ -63,6 +89,8 @@ pub struct OriginalServeOptions {
|
||||
pub prompt_cache_root: usize,
|
||||
/// `--turn-token ID`: the token that opens a chat turn (`<|im_start|>`); `None` = no turn checkpoints.
|
||||
pub turn_token: Option<u32>,
|
||||
/// `--expert-source resident|mapped`: how the routed-expert bank is admitted before the stack opens.
|
||||
pub expert_source: ExpertSource,
|
||||
}
|
||||
impl Default for OriginalServeOptions {
|
||||
fn default() -> Self {
|
||||
@@ -77,6 +105,7 @@ impl Default for OriginalServeOptions {
|
||||
prompt_cache_every: 16_384,
|
||||
prompt_cache_root: 2048,
|
||||
turn_token: Some(crate::qwen_forward::original_serve_stack::TURN_TOKEN),
|
||||
expert_source: ExpertSource::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# OCI image of the Rust runtime (engine + gateway + API + `leleka`): binaries and CUDA 12 cuBLAS only.
|
||||
#
|
||||
# NOT in the image, by design:
|
||||
# * the model (shards, KAR archive, MTP pack, tokenizer) - mount a volume at /models; never baked, never in Git;
|
||||
# * the NVIDIA driver and libcuda.so.1 - injected by the NVIDIA Container Toolkit (docker run --gpus all);
|
||||
# * secrets - the tokens and the API key are generated into the /state volume on the first start;
|
||||
# * the sealed PTX is embedded in the binaries (sm_120, and the sm_86 companions when built with `sm86`).
|
||||
#
|
||||
# Build context = an unpacked release tarball (it holds bin/ and MANIFEST.json), see docs/deploy.md:
|
||||
# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
|
||||
# docker build -f /path/to/deploy/Containerfile.rust-runtime -t leleka-runtime:VERSION .
|
||||
#
|
||||
# Base: Ubuntu 24.04 (glibc 2.39), the oldest glibc the release is built against. Pin the digest for a release:
|
||||
# docker buildx imagetools inspect ubuntu:24.04 -> --build-arg BASE=ubuntu:24.04@sha256:...
|
||||
ARG BASE=ubuntu:24.04
|
||||
|
||||
# --- stage 1: the pinned NVIDIA cuBLAS 12.9.1.4 redistributable, checksum-verified by BuildKit ---------------
|
||||
FROM ${BASE} AS cublas
|
||||
ARG CUBLAS_URL=https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz
|
||||
ARG CUBLAS_SHA256=546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057
|
||||
ADD --checksum=sha256:${CUBLAS_SHA256} ${CUBLAS_URL} /cublas.tar.xz
|
||||
RUN mkdir /out \
|
||||
&& tar -xJf /cublas.tar.xz -C /out --strip-components=1 --wildcards '*/lib/libcublas.so.12*' '*/lib/libcublasLt.so.12*' '*/LICENSE' \
|
||||
&& mv /out/LICENSE /out/lib/LICENSE-cublas.txt
|
||||
|
||||
# --- stage 2: the runtime ---------------------------------------------------------------------------------------
|
||||
FROM ${BASE}
|
||||
ARG VERSION=dev
|
||||
LABEL org.opencontainers.image.title="leleka-runtime" \
|
||||
org.opencontainers.image.description="Leleka runtime: Rust CUDA engine, gateway and API. Model volume mounted externally." \
|
||||
org.opencontainers.image.version="${VERSION}"
|
||||
|
||||
RUN groupadd --gid 10001 leleka \
|
||||
&& useradd --uid 10001 --gid 10001 --no-create-home --home-dir /state --shell /usr/sbin/nologin leleka \
|
||||
&& install -d -m 0755 /opt/leleka/bin /opt/leleka/lib/cublas /usr/share/leleka \
|
||||
&& install -d -m 0700 -o leleka -g leleka /state \
|
||||
&& install -d -m 0755 -o leleka -g leleka /models
|
||||
|
||||
COPY --chmod=0755 bin/ /opt/leleka/bin/
|
||||
COPY --from=cublas --chmod=0644 /out/lib/ /opt/leleka/lib/cublas/
|
||||
# MANIFEST.json sits next to bin/ so that `leleka` sees the build features (sm86) and the binary digests.
|
||||
COPY --chmod=0644 MANIFEST.json PROVENANCE.json SHA256SUMS /opt/leleka/
|
||||
COPY --chmod=0755 install.sh /usr/share/leleka/install.sh
|
||||
|
||||
# `leleka up` finds libcublas.so.12 in PREFIX/lib/cublas on its own and records it in the service environment.
|
||||
# The paths below are the defaults of `leleka` (--prefix / --state-dir / --assets).
|
||||
ENV LELEKA_PREFIX=/opt/leleka \
|
||||
LELEKA_STATE=/state \
|
||||
LELEKA_ASSETS=/models \
|
||||
HOME=/state \
|
||||
NVIDIA_VISIBLE_DEVICES=all \
|
||||
NVIDIA_DRIVER_CAPABILITIES=compute,utility
|
||||
|
||||
USER 10001:10001
|
||||
WORKDIR /state
|
||||
VOLUME ["/models", "/state"]
|
||||
EXPOSE 8081
|
||||
|
||||
# Ready = the API answers /ready with the key kept in /state. The first start downloads, verifies and converts
|
||||
# the model (hours), so the start period is long; a restart with a populated volume is minutes.
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=4h --retries=3 \
|
||||
CMD ["/opt/leleka/bin/leleka", "status"]
|
||||
|
||||
# SIGTERM -> `leleka` drains the API, then stops the gateway and the engine.
|
||||
STOPSIGNAL SIGTERM
|
||||
ENTRYPOINT ["/opt/leleka/bin/leleka"]
|
||||
CMD ["up", "--foreground", "--no-install-cublas", "--api-bind", "0.0.0.0", "--timeout-s", "86400"]
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# One command on a fresh Linux CUDA machine (or WSL2): verify this release, then hand over to `leleka up`.
|
||||
#
|
||||
# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
|
||||
# sudo ./install.sh --assets /data/leleka # systemd service, starts at boot
|
||||
# ./install.sh --assets ~/leleka --foreground # WSL2 without systemd, or a terminal
|
||||
# ./install.sh --dry-run # print the plan, change nothing
|
||||
#
|
||||
# Every option is passed to `leleka up` (see `./bin/leleka --help`). Nothing here needs Python.
|
||||
set -eu
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
cd "$here"
|
||||
|
||||
case "$(uname -s)/$(uname -m)" in
|
||||
Linux/x86_64) ;;
|
||||
*) echo "install.sh: this release is for Linux x86_64 (WSL2 included), not $(uname -s)/$(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
[ -x ./bin/leleka ] || { echo "install.sh: ./bin/leleka is missing; run this script from the unpacked release directory" >&2; exit 1; }
|
||||
|
||||
if [ -f SHA256SUMS ]; then
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
echo "install.sh: verifying the release files against SHA256SUMS ..." >&2
|
||||
sha256sum --quiet -c SHA256SUMS || {
|
||||
echo "install.sh: a file does not match SHA256SUMS; download the release again" >&2
|
||||
exit 1
|
||||
}
|
||||
else
|
||||
echo "install.sh: sha256sum not found, skipping the integrity check" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
exec ./bin/leleka up "$@"
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "rtx3080-16g",
|
||||
"description": "RTX 3080 Laptop class (sm_86, 16 GB VRAM, 24-48 GB RAM, typically WSL2). The KAR archive stays an ordinary read-only file (no 55 GB memfd), routed experts are served from the memory-mapped shards, context is capped at 8192. Experimental (docs/laptop-profile.md): measured on one laptop, slower than the server profile, no quality claim.",
|
||||
"select": {"sm_min": 80, "sm_max": 120, "vram_mib_min": 14000, "vram_mib_max": 24000},
|
||||
"gpu_budget_bytes": 16106127360,
|
||||
"context_tokens": 8192,
|
||||
"kar_source": "file",
|
||||
"expert_source": "mapped",
|
||||
"min_driver_major": 595,
|
||||
"min_vram_total_mib": 14000,
|
||||
"min_vram_free_mib": 14500,
|
||||
"min_ram_total_bytes": 23622320128,
|
||||
"min_ram_available_bytes": 10737418240,
|
||||
"wsl_memory_gib": 32,
|
||||
"expert_profile": "data/expert-profile.bin",
|
||||
"expert_profile_sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf",
|
||||
"engine_env": {}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "rtx5090-32g",
|
||||
"description": "RTX 5090 class server (sm_120, 32 GB VRAM, >= 100 GiB RAM). The 55 GB level-2 KAR archive is copied once into a sealed memfd and the 50 GB routed-expert bank is a page-locked RAM copy (the bring-up smoke form). Values are the documented bring-up configuration (docs/rust-runtime-run.md), not a tuned or quality-gated profile.",
|
||||
"select": {"sm_min": 120, "sm_max": 130, "vram_mib_min": 30000, "vram_mib_max": 1000000},
|
||||
"gpu_budget_bytes": 25769803776,
|
||||
"context_tokens": 262144,
|
||||
"kar_source": "memfd",
|
||||
"expert_source": "resident",
|
||||
"min_driver_major": 595,
|
||||
"min_vram_total_mib": 30000,
|
||||
"min_ram_total_bytes": 107374182400,
|
||||
"min_ram_available_bytes": 113000000000,
|
||||
"engine_env": {}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ const PROMPT_CACHE_FLAG: &str = "--prompt-cache";
|
||||
const PROMPT_CACHE_EVERY_FLAG: &str = "--prompt-cache-every";
|
||||
const PROMPT_CACHE_ROOT_FLAG: &str = "--prompt-cache-root";
|
||||
const TURN_TOKEN_FLAG: &str = "--turn-token";
|
||||
const EXPERT_SOURCE_FLAG: &str = "--expert-source";
|
||||
const EXECUTION_FLAGS: [&str; 7] = [
|
||||
ADAPTIVE_SLOTS_FLAG,
|
||||
RESIDENT_OWNERS_FLAG,
|
||||
@@ -50,7 +51,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.as_slice() == ["--help"] {
|
||||
println!(
|
||||
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)]"
|
||||
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -126,10 +127,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?,
|
||||
context_tokens: context.parse().map_err(|_| "invalid_context_bound")?,
|
||||
kar_ple_source: sources.kar,
|
||||
kar_ple_inherited: sources
|
||||
.inherited
|
||||
.map(|(fd, provenance)| InheritedKarArchive::open(fd, provenance))
|
||||
.transpose()?,
|
||||
kar_ple_inherited: match (sources.inherited, sources.kar_file) {
|
||||
(Some((fd, provenance)), None) => Some(InheritedKarArchive::open(fd, provenance)?),
|
||||
// Low-RAM form (docs/laptop-profile.md): an ordinary read-only file instead of a 55 GB sealed memfd.
|
||||
(None, Some((file, provenance))) => Some(InheritedKarArchive::open_read_only_file(&file, provenance)?),
|
||||
_ => None,
|
||||
},
|
||||
mtp_source: sources.mtp,
|
||||
// The routed-expert KAR source has no operator flag in this binary yet.
|
||||
kar_expert_source: None,
|
||||
@@ -348,6 +351,8 @@ struct OperatorSources {
|
||||
kar: OperatorSource,
|
||||
mtp: OperatorSource,
|
||||
inherited: Option<(u32, PathBuf)>,
|
||||
/// `--kar-archive-file PATH --kar-provenance PATH`: the archive as a read-only regular file.
|
||||
kar_file: Option<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &'static str> {
|
||||
@@ -355,9 +360,19 @@ fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &
|
||||
return Err("invalid_operator_source_pairs");
|
||||
}
|
||||
let mut inherited = None;
|
||||
let mut kar_file = None;
|
||||
let mut ordinary = Vec::with_capacity(args.len());
|
||||
for pair in args.as_chunks::<4>().0 {
|
||||
if pair[0] == "--kar-archive-fd" {
|
||||
if pair[0] == "--kar-archive-file" {
|
||||
if kar_file.is_some()
|
||||
|| pair[2] != "--kar-provenance"
|
||||
|| pair[1].is_empty()
|
||||
|| pair[3].is_empty()
|
||||
{
|
||||
return Err("invalid_kar_archive_file_arguments");
|
||||
}
|
||||
kar_file = Some((PathBuf::from(&pair[1]), PathBuf::from(&pair[3])));
|
||||
} else if pair[0] == "--kar-archive-fd" {
|
||||
if inherited.is_some()
|
||||
|| pair[2] != "--kar-provenance"
|
||||
|| pair[1].is_empty()
|
||||
@@ -378,13 +393,14 @@ fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &
|
||||
}
|
||||
}
|
||||
let (kar, mtp) = operator_sources(&ordinary)?;
|
||||
if kar.is_some() && inherited.is_some() {
|
||||
if (kar.is_some() as u8) + (inherited.is_some() as u8) + (kar_file.is_some() as u8) > 1 {
|
||||
return Err("conflicting_kar_sources");
|
||||
}
|
||||
Ok(OperatorSources {
|
||||
kar,
|
||||
mtp,
|
||||
inherited,
|
||||
kar_file,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -498,6 +514,26 @@ mod queued_owner_operator_tests {
|
||||
mod inherited_source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn read_only_file_form_is_exclusive_with_the_fd_and_the_staged_forms() {
|
||||
let file = ["--kar-archive-file", "/assets/a.kar", "--kar-provenance", "/assets/a.json"].map(String::from);
|
||||
let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from);
|
||||
let parsed = operator_sources_with_inherited(&file.iter().chain(&mtp).cloned().collect::<Vec<_>>()).unwrap();
|
||||
assert_eq!(parsed.kar_file, Some(("/assets/a.kar".into(), "/assets/a.json".into())));
|
||||
assert_eq!((parsed.inherited, parsed.kar), (None, None));
|
||||
let fd = ["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from);
|
||||
let staged = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
|
||||
for other in [&fd, &staged, &file] {
|
||||
assert!(operator_sources_with_inherited(&file.iter().chain(other).cloned().collect::<Vec<_>>()).is_err());
|
||||
}
|
||||
let mut invalid = file.clone();
|
||||
invalid[2] = "--kar-staging".into();
|
||||
assert!(operator_sources_with_inherited(&invalid).is_err());
|
||||
let mut invalid = file.clone();
|
||||
invalid[1].clear();
|
||||
assert!(operator_sources_with_inherited(&invalid).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() {
|
||||
let inherited =
|
||||
@@ -507,6 +543,7 @@ mod inherited_source_tests {
|
||||
kar: None,
|
||||
mtp: Some(("pack".into(), "private".into())),
|
||||
inherited: Some((9, "proof.json".into())),
|
||||
kar_file: None,
|
||||
};
|
||||
for args in [
|
||||
inherited.iter().chain(&mtp).cloned().collect::<Vec<_>>(),
|
||||
@@ -551,6 +588,7 @@ mod inherited_source_tests {
|
||||
kar: None,
|
||||
mtp: None,
|
||||
inherited: None,
|
||||
kar_file: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -951,6 +989,7 @@ fn operator_original_serve(
|
||||
let (mut capacity, mut directory, mut floor) = (false, false, false);
|
||||
let (mut kv, mut kv_resident) = (false, false);
|
||||
let (mut cache, mut every, mut root, mut turn) = (false, false, false, false);
|
||||
let mut expert_source = false;
|
||||
let mut ordinary = Vec::with_capacity(args.len());
|
||||
let mut offset = 0usize;
|
||||
while offset < args.len() {
|
||||
@@ -1035,6 +1074,13 @@ fn operator_original_serve(
|
||||
Some(u32::try_from(id).map_err(|_| "invalid_turn_token")?)
|
||||
};
|
||||
offset += 2;
|
||||
} else if flag == EXPERT_SOURCE_FLAG {
|
||||
if std::mem::replace(&mut expert_source, true) {
|
||||
return Err("duplicate_expert_source");
|
||||
}
|
||||
options.expert_source =
|
||||
leleka_runtime::backend::ExpertSource::parse(value()?).ok_or("invalid_expert_source")?;
|
||||
offset += 2;
|
||||
} else if flag == PUBLIC_EVALUATION_OUTPUT_FLAG {
|
||||
let end = offset
|
||||
.checked_add(2)
|
||||
@@ -1070,6 +1116,31 @@ mod original_serve_operator_tests {
|
||||
items.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expert_source_is_resident_by_default_and_mapped_on_request() {
|
||||
let (_, options, rest) = operator_original_serve(&args(&[])).unwrap();
|
||||
assert_eq!(options.expert_source, leleka_runtime::backend::ExpertSource::Resident);
|
||||
assert!(rest.is_empty());
|
||||
let (_, options, rest) = operator_original_serve(&args(&[
|
||||
"--expert-source",
|
||||
"mapped",
|
||||
"--kar-archive-file",
|
||||
"/a.kar",
|
||||
"--kar-provenance",
|
||||
"/a.json",
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(options.expert_source, leleka_runtime::backend::ExpertSource::Mapped);
|
||||
assert_eq!(rest, args(&["--kar-archive-file", "/a.kar", "--kar-provenance", "/a.json"]));
|
||||
for bad in [
|
||||
args(&["--expert-source"]),
|
||||
args(&["--expert-source", "copy"]),
|
||||
args(&["--expert-source", "mapped", "--expert-source", "resident"]),
|
||||
] {
|
||||
assert!(operator_original_serve(&bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_four_options_are_consumed_and_everything_else_passes_through_unchanged() {
|
||||
let input = args(&[
|
||||
|
||||
@@ -12,6 +12,11 @@ to this branch. The run recipe is [`rust-runtime-run.md`](rust-runtime-run.md).
|
||||
> artefact (a `flock` kept alive past `drop` by a child another test forked meanwhile); the reopen in those tests now waits, and 12 of 12
|
||||
> parallel runs of the `strata-desktop-core` lib suite passed afterwards (the mechanism itself was not isolated).
|
||||
|
||||
> Update 2026-10-17, branch `claude/deploy`: the packaging half of finding 4 and tasks 3-4 of section 7 are addressed in software by
|
||||
> [`deploy.md`](deploy.md) (`leleka up`: preflight incl. driver/cuBLAS/`/proc`/RAM/disk, asset fetch+verify+archive with stamps, native sealed-memfd supervisor,
|
||||
> auto-load and readiness, systemd unit, OCI recipe, release tarball with provenance). Still open there: the MTP pack has no automated producer, no clean-VM run on
|
||||
> Ubuntu 24.04/26.04, the image was not built here (see `deploy.md` section 10), and SIGTERM handling of the daemon/engine is worked around by the supervisor (it sends SIGINT).
|
||||
|
||||
1. **Two serving stacks exist and the full API is wired to the wrong one.** `strata-next` (`control-plane/`) has the Responses /
|
||||
Chat / Messages surface, text.format, custom tools, reasoning, drain, history, MCP hub, but it drives an *engine process over
|
||||
the Original stdio wire protocol* (`READY`/`GEN <token ids>`/`T <id>`/`DONE`, `control-plane/src/wire.rs`). The Rust engine
|
||||
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
# One-command deployment: `leleka up`
|
||||
|
||||
Status 2026-10-17, branch `claude/deploy` (base `claude/port-gpu-bringup` @ `5e0bd84`). This page describes the deployment
|
||||
tool `leleka` (crate `crates/deploy`, no Python at run time), what it does, every flag, and what was and was not run to
|
||||
check it. Results are in [section 10](#10-what-was-run-and-what-was-not); nothing here is a performance or model-quality
|
||||
claim. Background: [`rust-runtime-run.md`](rust-runtime-run.md) (the processes), [`model-assets.md`](model-assets.md) (the model
|
||||
commands `leleka` drives), [`laptop-profile.md`](laptop-profile.md), [`sm86-assets.md`](sm86-assets.md),
|
||||
[`delivery-gap-audit.md`](delivery-gap-audit.md) section 5 (the packaging gaps this closes in part).
|
||||
|
||||
## 1. Quickstart
|
||||
|
||||
Server (Linux x86_64, NVIDIA driver >= 595, systemd), as root, from the unpacked release:
|
||||
|
||||
```sh
|
||||
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
|
||||
sudo ./install.sh --assets /data/leleka # preflight, fetch+verify, KAR archive, install, start, wait for ready
|
||||
```
|
||||
|
||||
WSL2 laptop (RTX 3080 16 GB), as your user, in a terminal (WSL2 usually has no systemd):
|
||||
|
||||
```sh
|
||||
./install.sh --assets ~/leleka --foreground # keep the terminal open; Ctrl-C drains and stops
|
||||
```
|
||||
|
||||
Both do the same thing, idempotently, and print the endpoint, model digest, GPU, the VRAM/RAM budget that was chosen, and the
|
||||
log directory when the service answers `/ready`. Look first with `--dry-run`: it prints the preflight and the plan and changes nothing.
|
||||
|
||||
```sh
|
||||
./bin/leleka up --dry-run --assets /data/leleka
|
||||
```
|
||||
|
||||
This is charter goal G2 (`PROJECT_CHARTER.md` section 6): one command, GPU and memory plan chosen automatically, external model volume, readiness only after the model is loaded, orderly stop and restart of the worker, no Python at run time.
|
||||
Its acceptance test (a clean Linux GPU node, driver installed, one command, no re-download after a restart) has **not** been run; section 10 lists what was.
|
||||
|
||||
Container: [section 7](#7-container-image). Build your own release: [section 8](#8-build-a-release-tarball).
|
||||
|
||||
## 2. What `up` does
|
||||
|
||||
| # | step | what happens | idempotency |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed |
|
||||
| 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` |
|
||||
| 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) |
|
||||
| 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found |
|
||||
| 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `strata-next api-key init` | never rotated; only missing/invalid ones are created |
|
||||
| 6 | model | `strata-next model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` |
|
||||
| 7 | KAR archive | `strata-next model ensure-sharded-streamed qwen-iq3-s --levels 2` (level 2, the pinned 55,295,529,472-byte archive + provenance) | stamped; also checks the length the engine admits |
|
||||
| 8 | MTP pack | `ASSETS/data/mtp-rt` must exist; `--mtp-pack` imports it from a directory or tarball | skipped when present |
|
||||
| 9 | tokenizer | `model extract-tokenizer` from shard 1 | skipped when present |
|
||||
| 10 | config | `leleka.json`, `daemon.json`, `strata.json`, `profile.json`, `runtime.env` | rewritten only when the content changes |
|
||||
| 11 | service | systemd unit (system or user), `daemon-reload`, `enable`; none in foreground mode | rewritten only when the content changes; a changed unit restarts a running service |
|
||||
| 12 | start / ready | start the unit (or run the supervisor in this terminal), poll `/ready` with the key, print the summary | an already ready service is left alone |
|
||||
|
||||
The archive step runs `ensure-sharded-streamed`, which fetches and verifies the shards itself, so on a first run step 6 is folded into
|
||||
step 7 (the plan says so). The strict verification of an *existing* archive re-derives the 708 GB virtual F32 stream and is slow; a
|
||||
machine that already holds the archive can pass `--trust-archive`: the archive is accepted when it has the pinned length and a
|
||||
provenance file, and the engine checks its SHA-256 and every CRC against the pinned digest at each load anyway.
|
||||
|
||||
A failed run is resumable: fix the cause and run the same command; finished steps are skipped (downloads continue from `.part`).
|
||||
|
||||
## 3. The processes and files
|
||||
|
||||
```text
|
||||
leleka run (supervisor, the systemd ExecStart or your terminal)
|
||||
|- seals the KAR archive into a memfd ONCE (memfd profile) -- or hands the engine a read-only file (file profile)
|
||||
|- leleka-daemon gateway for the typed lifecycle, 127.0.0.1:18080
|
||||
|- leleka-inference engine, gRPC 127.0.0.1:18766 (started through `leleka exec-inherit`, which passes the sealed fd)
|
||||
|- leleka-cli load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 -> wait for model_ready (the engine verifies shards + archive here)
|
||||
`- strata-next serve public API (Responses, Chat, Messages, tools, ...), 127.0.0.1:8081, bearer key
|
||||
```
|
||||
|
||||
```text
|
||||
PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} PREFIX/lib/cublas/
|
||||
STATE/{leleka.json,daemon.json,strata.json,profile.json,runtime.env,api-key} STATE/{logs,run/status.json,stamps,mtp-staging}
|
||||
ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/
|
||||
```
|
||||
|
||||
Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/assets`; a user gets `~/.local/share/leleka`,
|
||||
`~/.local/state/leleka`, `~/.local/share/leleka/assets`. Environment: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`.
|
||||
**Put `--assets` on the big volume**: about 140 GB (shards 83.6 GB + archive 55.3 GB); the first run needs that plus slack.
|
||||
|
||||
### The sealed KAR archive is made by the service
|
||||
|
||||
The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator
|
||||
tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a
|
||||
sealed memfd once (about 10 s for 55 GB from a warm cache, minutes cold), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate
|
||||
to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does
|
||||
**not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs.
|
||||
`--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded.
|
||||
|
||||
The **file profile** (laptop) cannot afford 55 GB of shmem. `leleka-inference` gained `--kar-archive-file PATH --kar-provenance PATH`
|
||||
(`InheritedKarArchive::open_read_only_file`, the form `docs/laptop-profile.md` measured in a bench): the archive stays an ordinary file;
|
||||
it must be regular, single-link, owned by the service user and without write bits (`up` sets mode 0400). It is weaker than the seal (immutability rests on
|
||||
the file system) and is selected only by that profile. The full SHA-256 and all CRCs are still checked at load.
|
||||
|
||||
## 4. Memory profiles
|
||||
|
||||
`--profile auto` (default) picks by the GPU `nvidia-smi` reports; `--profile NAME` or `--profile FILE.json` overrides it, and
|
||||
`--gpu-budget-gib` / `--context-tokens` override single values. `leleka profiles` lists them, `leleka profiles show NAME` prints one to copy and edit.
|
||||
The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profiles/) and are embedded in the binary.
|
||||
|
||||
| profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 24 GiB | 262,144 | sealed memfd (55.3 GB of RAM) | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 113 GB (58 GB when `--kar-fd` supplies the archive) | the documented bring-up configuration |
|
||||
| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | optional VRAM expert tier when `ASSETS/data/expert-profile.bin` has the pinned SHA-256 `8f59b4aa...388975baf` |
|
||||
|
||||
Both profiles run `--backend-mode original` and the level-2 archive; the routed-expert bank must be admitted before the Original stack opens, which `leleka-inference` now does from `--expert-source resident|mapped` (see section 10, finding 1). They select documented switches only (budget, context, archive form, the
|
||||
`LELEKA_ORIGINAL_SERVE_*` environment); they are **not** tuned, not quality-gated and carry no speed claim. A GPU that fits neither
|
||||
(a 24 GB 4090, say) gets an error that names the way out: write a profile file. Fields: see `crates/deploy/src/profile.rs`
|
||||
(`gpu_budget_bytes`, `context_tokens`, `prefill_capacity`, `kv`, `kv_resident`, `prompt_cache`, `kar_source`, `min_*`, `engine_env`
|
||||
restricted to `LELEKA_ORIGINAL_SERVE_*`); unknown fields are refused.
|
||||
|
||||
One binary serves both architectures: the sealed sm_120 PTX is used as is on Blackwell, and the build with `--features sm86`
|
||||
(every release) swaps in the sm_86 companion PTX on 8.6 <= cc < 12.0 cards ([`sm86-assets.md`](sm86-assets.md)). Preflight reads `MANIFEST.json` and refuses a
|
||||
binary built without `sm86` on such a card. All PTX is embedded in the binaries (the release also ships the files and a `SHA256SUMS` for audit).
|
||||
|
||||
## 5. Flags
|
||||
|
||||
`leleka up [OPTIONS]` (also accepted by `preflight`, `status`, `down`):
|
||||
|
||||
| flag | meaning |
|
||||
| --- | --- |
|
||||
| `--dry-run` | print preflight and plan (and the exact engine command); change nothing; exit 1 if a check fails or a step is blocked |
|
||||
| `--json` | machine-readable plan / summary on stdout (logs stay on stderr) |
|
||||
| `--profile auto\|NAME\|FILE` | memory profile |
|
||||
| `--gpu N` | CUDA device ordinal (default 0) |
|
||||
| `--assets DIR` `--state-dir DIR` `--prefix DIR` | the three roots (section 3) |
|
||||
| `--bin-src DIR` | where the six binaries come from (default: the directory of `leleka`, i.e. the release `bin/`) |
|
||||
| `--mode auto\|system\|user\|foreground\|none`, `--foreground` | `auto`: root with systemd -> system unit; a user with a systemd user session -> user unit; otherwise foreground. `none` prepares and starts nothing |
|
||||
| `--service-user NAME` | system unit only: the account the service runs as (default `leleka`, created with `useradd --system`; state and assets are chowned to it) |
|
||||
| `--api-port` `--engine-port` `--daemon-port` | ports (defaults 8081, 18766, 18080) |
|
||||
| `--api-bind IP` | API listen address, default `127.0.0.1`; `0.0.0.0` only inside a container whose port is published to the host's loopback or tunnelled (the bearer key is the only protection, no TLS). The engine and gateway are always loopback |
|
||||
| `--gpu-budget-gib N` `--context-tokens N` | override one profile value |
|
||||
| `--no-fetch` | never download or build; require verified files to exist |
|
||||
| `--reverify` | ignore the stamps and hash everything again |
|
||||
| `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) |
|
||||
| `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) |
|
||||
| `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it |
|
||||
| `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) |
|
||||
| `--timeout-s N` | wait this long for `/ready` (default 3600) |
|
||||
|
||||
Other commands: `leleka preflight` (checks only, exit 1 on FAIL), `leleka status` (cheap: no GPU probe; exit 0 only when ready; this is the container health check),
|
||||
`leleka down` (stop the systemd unit), `leleka run --config STATE/leleka.json [--kar-fd N]` (the supervisor), `leleka profiles [show NAME]`.
|
||||
`HF_TOKEN` in the environment is used only by `model fetch`, is sent only to `https://huggingface.co`, is removed from every child the supervisor starts, and is never printed or written.
|
||||
|
||||
## 6. Operating it
|
||||
|
||||
* systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has
|
||||
`Restart=on-failure` with `RestartSec=30`, at most 3 starts in 30 minutes, and no restart after exit code 2 (configuration), because every start re-reads 55 GB.
|
||||
* The supervisor restarts a dead engine up to twice (counter reset after 10 ready minutes) with the same sealed descriptor and loads the model again; the API process stays up and
|
||||
answers not-ready meanwhile. A dead gateway (3) or API (5) is restarted too. Then it exits 1 and systemd decides.
|
||||
* `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace.
|
||||
* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log` (rotated once past 64 MiB at start). Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed).
|
||||
* Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`.
|
||||
Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md).
|
||||
|
||||
## 7. Container image
|
||||
|
||||
[`deploy/Containerfile.rust-runtime`](../deploy/Containerfile.rust-runtime): Ubuntu 24.04 (glibc 2.39, the floor of the binaries) + the six binaries + cuBLAS 12.9.1.4
|
||||
(downloaded by BuildKit with `ADD --checksum`, only `libcublas.so.12*` and `libcublasLt.so.12*` kept) + the manifest/provenance. The sealed PTX is inside the binaries; `ldd` shows only libc, libm
|
||||
and libgcc_s, and the engine `dlopen`s `libcuda.so.1` (injected by the NVIDIA Container Toolkit) and `libcublas.so.12`. Not in the image, by design: the model, the driver, any secret. Non-root (uid 10001), volumes `/models` and `/state`,
|
||||
`HEALTHCHECK` = `leleka status`.
|
||||
|
||||
```sh
|
||||
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
|
||||
docker build -f /path/to/repo/deploy/Containerfile.rust-runtime --build-arg VERSION=VERSION -t leleka-runtime:VERSION .
|
||||
# pin the base for a release: docker buildx imagetools inspect ubuntu:24.04 then --build-arg BASE=ubuntu:24.04@sha256:...
|
||||
|
||||
docker run -d --name leleka --gpus all --restart unless-stopped \
|
||||
-v /data/leleka-models:/models -v leleka-state:/state -p 127.0.0.1:8081:8081 \
|
||||
leleka-runtime:VERSION # default command: up --foreground --no-install-cublas --api-bind 0.0.0.0
|
||||
docker logs -f leleka # first start: hours (download, verification, archive build); later starts: minutes
|
||||
docker exec leleka cat /state/api-key
|
||||
```
|
||||
|
||||
The memfd profile needs the host to give the container ~60 GB of RAM (no `--memory` below that; memfd is shmem charged to the container, not limited by `--shm-size`). Docker's default seccomp
|
||||
profile allows `memfd_create`. Build is not run in CI; see section 10 for what was checked.
|
||||
|
||||
## 8. Build a release tarball
|
||||
|
||||
On Linux/WSL, from a tree with the toolchain pinned by `rust-toolchain.toml` (no CUDA toolkit is needed; the PTX is checked in):
|
||||
|
||||
```sh
|
||||
cargo build --release --locked -p strata-desktop-core --features sm86 \
|
||||
--bin leleka-inference --bin leleka-daemon --bin leleka-cli --bin leleka-seal-exec
|
||||
cargo build --release --locked -p strata-control --bin strata-next
|
||||
cargo build --release --locked -p leleka-deploy --bin leleka
|
||||
|
||||
# provenance is made where git exists (an exported tree has no .git); the tree must be clean or --allow-dirty marks it
|
||||
python3 scripts/package-release.py provenance --repo . --out provenance.json
|
||||
python3 scripts/package-release.py package --repo . --target-dir target --provenance provenance.json --out dist
|
||||
```
|
||||
|
||||
`dist/leleka-VERSION-COMMIT12-linux-x86_64.tar.xz` (+ `.sha256`) contains `bin/` (six binaries), `share/leleka/ptx/{sm_120,sm_86}` (the sealed PTX and `SHA256SUMS`), `share/leleka/{profiles,templates,docs}`,
|
||||
`MANIFEST.json` (version, commit, `features`, SHA-256 of every binary, rustc/glibc of the builder), `PROVENANCE.json`, `SHA256SUMS` for every file, and `install.sh`. `--no-ptx` omits the PTX files (they are embedded anyway);
|
||||
`--with-cublas DIR` bundles cuBLAS (NVIDIA's redistribution terms apply).
|
||||
`PROVENANCE.json` records the git commit, whether the tree was dirty (and a digest of the diff), the `Cargo.lock` digest, and for `engine/strata`: the upstream URL and commit from [`upstream.md`](upstream.md),
|
||||
the subtree tree id, the import commit, every later commit touching the subtree, and the diff since import (shortstat + digest). The diff against the upstream tree itself is computed only when the upstream commit is present
|
||||
in the repository (`git fetch strata-upstream`); otherwise the record says so. `engine/strata` is not modified by this work.
|
||||
|
||||
## 9. Troubleshooting
|
||||
|
||||
| message (preflight / run) | cause and fix |
|
||||
| --- | --- |
|
||||
| `NVIDIA GPU: nvidia-smi was not found` | no driver. Linux: install the NVIDIA driver >= 595. WSL2: install the Windows driver (never a Linux driver inside WSL), `wsl --shutdown`, retry |
|
||||
| `driver version: 580.x is older than 595` | the sealed PTX needs ISA 9.2 (CUDA 13.2): update the driver |
|
||||
| `GPU memory: N MiB free but the engine needs M MiB` | another process holds VRAM (`nvidia-smi`); stop it or lower `--gpu-budget-gib` |
|
||||
| `architecture: ... built WITHOUT the sm86 feature` | an RTX 30-series card needs a release made with `--features sm86` |
|
||||
| `memory: ... available is below ...` | the sealed archive copy needs the whole 55 GB in RAM. Free memory, or use the file profile if the GPU fits it. On WSL2 put `[wsl2] memory=32GB swap=8GB` in `%UserProfile%\.wslconfig` and `wsl --shutdown` |
|
||||
| `WSL2 file system: ... is on a Windows/network mount` | `/mnt/c` is 9p: far too slow for mapped reads. Use a path on the WSL ext4 disk |
|
||||
| `cuBLAS 12: libcublas.so.12 ... not found` | let `up` download the pinned 12.9.1.4 (needs curl or wget, tar, xz), or `--cublas-dir DIR`, or `apt install libcublas12` |
|
||||
| `disk space: assets ...: N GiB free, M needed` | nothing was downloaded yet; point `--assets` at a larger volume |
|
||||
| `loopback ports: already in use` | another listener; `--api-port` / `--engine-port` / `--daemon-port` |
|
||||
| `permission denied` on `/dev/nvidia*` in the system unit | the device nodes are not world-accessible: add the service user to the `video` (or `render`) group and restart the unit |
|
||||
| `systemd: not running` | WSL2 without systemd or a container: `--foreground`, or enable systemd in `/etc/wsl.conf` |
|
||||
| `step mtp-pack is blocked` | the MTP pack has no automated producer yet; copy `data/mtp-rt` from a machine that has it (`--mtp-pack` takes a directory or tarball) |
|
||||
| `... has N bytes but the engine only admits the pinned 55295529472-byte level-2 archive` | the archive was built with another level or policy; the engine would refuse it. Rebuild with `--levels 2` |
|
||||
| `step model failed: ... 401/403` | the repository needs a token: `export HF_TOKEN=...` (sent only to huggingface.co) |
|
||||
| `load-mtp was refused` | read `STATE/logs/engine.log` (the engine prints a fixed code, never a path or a secret) |
|
||||
| `the model was not ready within 1800 s` | the engine verifies 84 GB of shards and 55 GB of archive at load; a cold disk can need longer: raise `load_timeout_s` in `STATE/leleka.json` |
|
||||
| a stale `Another supervisor is running for ...` | `leleka down` (systemd) or stop the other process; `STATE/run/status.json` names its pid |
|
||||
|
||||
## 10. What was run and what was not
|
||||
|
||||
All of this is bring-up evidence, not a performance or quality result: no paired A/B, one request, no token statistics beyond what is quoted.
|
||||
|
||||
### Findings that the real run produced
|
||||
|
||||
1. **The production `Load` of the Original path could not succeed.** `leleka-inference ... --backend-mode original` never admitted a routed-expert bank
|
||||
(the serve smokes call `load_resident_expert_source()` themselves; `backend.rs` did that only for the `--experimental-optimized-*` modes), so the first real `load-mtp`
|
||||
through the daemon failed in `OriginalServeStack::open` with `MoeWeightCache::new_original_prompt_arena: InputRead` (`leleka-load phase=OriginalStack class=BackendUnavailable` in
|
||||
`engine.log`) and the engine process stayed up. Fixed here: `OriginalServeOptions.expert_source` and `--expert-source resident|mapped` (default `resident`, the smoke form);
|
||||
`backend.rs` admits the chosen bank before the driver, as it does for the optimized modes. The profile files select `resident` (server) and `mapped` (laptop).
|
||||
2. **The supervisor waited out the load timeout for a refused load.** The engine does not exit on a failed load; `leleka` now reads the operation record
|
||||
(`leleka-cli operation`, state FAILED/INDETERMINATE) and stops with the last lines of `engine.log`.
|
||||
3. `leleka-inference` had no way to take the archive as a read-only file (only the 55 GB sealed memfd); `--kar-archive-file` is new and was exercised on the laptop.
|
||||
|
||||
### Real runs
|
||||
|
||||
| where | what | result |
|
||||
| --- | --- | --- |
|
||||
| WSL2 laptop, RTX 3080 Laptop 16 GB, driver 617.42, Ubuntu 24.04 with systemd, RAM 40 GB (`.wslconfig`) | `leleka up` from the unpacked release (commit `e03d97d`, 30.7 MB tarball, sm86 build), user unit, real shards and archive (copied to the WSL ext4 disk), profile `rtx3080-16g` chosen by `auto` | preflight 13 ok / 1 warning (cuBLAS missing); cuBLAS 12.9.1.4 unpacked from the pinned archive (SHA-256 checked; **the download itself was not exercised**: the archive was placed in `PREFIX/lib` beforehand); fetch + verify of the real shards about 3 min (hash reuse, no download); tokens, configs, tokenizer, `systemctl --user enable/start`; **model loaded in 198 s, `/ready` 200**; one `POST /v1/responses` (59 input tokens, 16 output tokens, 21.4 s wall, stopped by `max_output_tokens`, text is the model's reasoning preamble) |
|
||||
| same | peak during that request | VRAM 13,971 MiB; engine RSS 26.4 GB (anon 2.6, file-backed 19.9, shmem 4.0); the engine log shows 3,133 VRAM expert slots (the expert tier was on because `expert-profile.bin` had the pinned digest) |
|
||||
| same | idempotence | a second `up` against the running service: 0.27 s, same systemd `MainPID`, every step `done`; `leleka down`: 1.9 s, no process left, VRAM back to 0 |
|
||||
| same | engine killed with `kill -9` | phase `engine_restarting`, `/ready` false, the engine restarted and reloaded: ready again 293 s after the kill (load 286 s), restart counter 1, gateway and API processes unchanged, one request served afterwards |
|
||||
| RTX 5090 server (Ubuntu 26.04, driver 595.99.02, 121 GB RAM) | `leleka up --dry-run` with the real assets and the real preflight | 12 checks ok; the plan names the exact engine command; nothing created. The real-model jobs `930-deploy-prepare.sh` and `931-deploy-serve.sh` are in the holder queue (they inherit the holder's sealed descriptor with `--kar-fd`); see "Server job" below for their state |
|
||||
|
||||
### Tests (no GPU, no model)
|
||||
|
||||
* `cargo test -p leleka-deploy --features test-fakes` (71 unit, 11 end-to-end, 4 recipe tests, all passing in WSL): unit tests (profiles, facts parsers, preflight on synthetic hosts - server, laptop under default WSL2 memory, old driver, busy GPU,
|
||||
no cuBLAS, full disk, `/mnt/c`, no systemd -, plan, units, CLI, sealed memfd, stamps, HTTP), `tests/e2e.rs` against a test double of the five programs
|
||||
(supervisor lifecycle with an inherited sealed descriptor and with a read-only file: ready, SIGKILL of the engine -> restart with API/gateway unchanged -> SIGTERM drain with every child gone;
|
||||
an engine that cannot start; a refused load fails fast; weak tokens are exit code 2; `up` is idempotent, resumable after a deleted archive, never rotates secrets, `--trust-archive`, wrong-size archive refused;
|
||||
`--dry-run` creates nothing; a failing preflight changes nothing), `tests/recipe.rs` (the Containerfile is non-root, has a health check, copies no model or secret; the cuBLAS pin agrees in three places; `install.sh` verifies before it runs).
|
||||
`cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` are clean.
|
||||
* `cargo test -p strata-desktop-core --bin leleka-inference` (14 argument-parsing tests, including `--kar-archive-file` and `--expert-source`).
|
||||
* Linux only for the process tests; the portable parts also run on Windows (`cargo test -p leleka-deploy`), where the POSIX-path tests are not meaningful.
|
||||
|
||||
### Not done / open
|
||||
|
||||
* **No container image was built.** Docker Desktop on this laptop does not start: its backend aborts on stale `AF_UNIX` socket files (`%LOCALAPPDATA%\Docker
un\dockerInference`,
|
||||
`userAnalyticsOtlpHttp.sock`, dated 2025-06) that Windows refuses to delete without elevation (`Error 1920`). The recipe is checked statically (`tests/recipe.rs`) and by simulation: the `COPY` layout
|
||||
rebuilt under `/opt/leleka` in WSL, `env -i`, the container's environment variables: `ldd` resolves every library from the base alone (libc, libm, libgcc_s), `libcublas.so.12` is found in
|
||||
`PREFIX/lib/cublas`, `leleka status` answers in 2 ms; the content is 167 MB of binaries + 815 MB of cuBLAS = 982 MB before the Ubuntu base layer (no image digest exists).
|
||||
Build it on a machine with a working engine (section 7) and record the digest and size.
|
||||
* The **system-scope** unit (`useradd`, chown of state and assets, `/etc/systemd/system`) and the `curl` branch of the cuBLAS download have unit tests / renders but were not run for real.
|
||||
* No clean Ubuntu 24.04 / 26.04 VM was installed from nothing; the first-ever archive build (`ensure-sharded-streamed` creating 55 GB) was not repeated.
|
||||
* The MTP pack has no producer in the repository (`mtp_pack`); `up` needs it in `ASSETS/data/mtp-rt` or via `--mtp-pack`.
|
||||
* Not measured: the load time of the server profile under the supervisor, the RAM peak of 55 GB memfd + 50 GB bank, anything about throughput.
|
||||
* Native Windows is not a target. TLS and remote access are not part of this: use an SSH tunnel.
|
||||
|
||||
### Server job (RTX 5090)
|
||||
|
||||
Two holder jobs are queued on `rnr5090` (`~/work/gpu-runs/holder2/jobs/`), written to run after each other and to inherit the holder's sealed descriptor, so nothing is copied or downloaded:
|
||||
|
||||
* `930-deploy-prepare.sh`: `up --dry-run`, then `up --mode none --kar-fd $LELEKA_STRA169_KAR_FD --trust-archive` against `~/leleka-gates/assets` (real `model fetch`/`verify` of the existing shards by hash reuse,
|
||||
tokens, configs, tokenizer extraction into `assets/tokenizer-assets`), then a second dry-run and a second `up` to show that nothing is redone.
|
||||
* `931-deploy-serve.sh`: `up --foreground --kar-fd ...` with the real model (typed load, `/ready`), one request through the API, an unauthenticated request (must be refused), SIGTERM, the logs and a check that no process is left.
|
||||
|
||||
The release is unpacked at `~/work/deploy-run/rel`, state is `~/work/deploy-run/state`. At the time of writing the holder was busy with earlier queue entries (the holder takes a snapshot of the job list per pass, so entries added later run in the next pass), so
|
||||
**these two jobs had not run**; read `930-deploy-prepare.log` and `931-deploy-serve.log` next to the scripts. The strict re-verification of the existing archive (`ensure-sharded-streamed` without `--trust-archive`) was deliberately not queued:
|
||||
it re-derives the 708 GB virtual F32 stream (the analysis tool was stopped after 13 minutes at the same step, `build-validation.md`).
|
||||
@@ -5,6 +5,10 @@ against the model assets, and what was and was not executed to check it. **No mo
|
||||
was involved in any check on this page**; it makes no performance or quality claim. The model-facing steps (`load-mtp`, a
|
||||
real `/v1/responses`) belong to the GPU bring-up and are written down here from the code, not from a run.
|
||||
|
||||
> **One command instead of the manual steps below:** `leleka up` ([`deploy.md`](deploy.md)) preflights the host, fetches and verifies the
|
||||
> model, builds the archive, installs, creates the sealed KAR descriptor itself (no `kar_holder.py`), loads the model and waits for readiness.
|
||||
> This page stays the reference for what each process does.
|
||||
|
||||
## Processes
|
||||
|
||||
```text
|
||||
|
||||
Executable
+285
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble the Leleka release tarball (offline build tooling; production serving has no Python dependency).
|
||||
|
||||
Inputs: a release build of the seven binaries (`cargo build --release --locked ...`, see docs/deploy.md), the
|
||||
repository tree (for templates, sealed PTX and docs) and a provenance record. Output, in --out:
|
||||
|
||||
leleka-VERSION-COMMIT12-linux-x86_64.tar.xz bin/ share/ MANIFEST.json PROVENANCE.json SHA256SUMS install.sh
|
||||
leleka-VERSION-COMMIT12-linux-x86_64.tar.xz.sha256
|
||||
|
||||
The provenance record names the git commit, whether the tree was clean, and the local changes to the imported
|
||||
Strata source relative to the upstream commit in docs/upstream.md. Builds happen in WSL/Linux from an exported tree
|
||||
(no .git there), so the record is produced where git exists:
|
||||
|
||||
python3 scripts/package-release.py provenance --repo . --out provenance.json
|
||||
python3 scripts/package-release.py package --repo . --target-dir ~/target --provenance provenance.json --out dist
|
||||
|
||||
`package` alone also works inside a git checkout (it computes the provenance itself). Nothing here downloads
|
||||
anything; cuBLAS is not bundled (the NVIDIA redistributable is fetched by `leleka up`, or add --with-cublas DIR).
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
RUNTIME_BINARIES = ['leleka', 'strata-next', 'leleka-inference', 'leleka-daemon', 'leleka-cli', 'leleka-seal-exec']
|
||||
TEMPLATES = [
|
||||
'deploy/rust-runtime/leleka-daemon.service',
|
||||
'deploy/rust-runtime/leleka-inference.service',
|
||||
'deploy/rust-runtime/runtime.env.example',
|
||||
]
|
||||
UPSTREAM_DOC = 'docs/upstream.md'
|
||||
SUBTREE = 'engine/strata'
|
||||
|
||||
|
||||
def run(args, cwd=None, check=True):
|
||||
result = subprocess.run([str(a) for a in args], cwd=cwd, capture_output=True, text=True)
|
||||
if check and result.returncode != 0:
|
||||
raise RuntimeError(f'{" ".join(map(str, args))} failed: {result.stderr.strip()}')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with open(path, 'rb') as source:
|
||||
for chunk in iter(lambda: source.read(1 << 20), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def upstream_record(repo):
|
||||
text = (repo / UPSTREAM_DOC).read_text(encoding='utf-8')
|
||||
url = re.search(r'Upstream repository URL \| (\S+)', text)
|
||||
sha = re.search(r'Upstream commit SHA \| `([0-9a-f]{40})`', text)
|
||||
if not url or not sha:
|
||||
raise RuntimeError(f'{UPSTREAM_DOC} does not name the upstream repository and commit')
|
||||
return url.group(1), sha.group(1)
|
||||
|
||||
|
||||
def provenance(repo, allow_dirty=False):
|
||||
"""Git commit, cleanliness, and the local changes to engine/strata relative to the recorded upstream commit."""
|
||||
url, upstream_sha = upstream_record(repo)
|
||||
commit = run(['git', '-C', repo, 'rev-parse', 'HEAD'])
|
||||
status = run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=normal'])
|
||||
dirty_files = [line for line in status.splitlines() if line]
|
||||
# Windows checkouts report CRLF-only differences as modified; hash what git would actually record.
|
||||
diff_digest = hashlib.sha256(run(['git', '-C', repo, 'diff', 'HEAD', '--binary'], check=False).encode()).hexdigest() if dirty_files else None
|
||||
if dirty_files and not allow_dirty:
|
||||
raise RuntimeError(f'the tree has {len(dirty_files)} uncommitted change(s); commit them or pass --allow-dirty (the release is then marked dirty)')
|
||||
# Import commit(s): the first commit that touched the subtree.
|
||||
history = run(['git', '-C', repo, 'log', '--format=%H %s', '--reverse', '--', SUBTREE]).splitlines()
|
||||
import_commit = history[0].split(' ', 1)[0] if history else None
|
||||
subtree_tree = run(['git', '-C', repo, 'rev-parse', f'HEAD:{SUBTREE}'])
|
||||
record = {
|
||||
'schema_version': 1,
|
||||
'git_commit': commit,
|
||||
'git_describe': run(['git', '-C', repo, 'describe', '--always', '--dirty', '--abbrev=12'], check=False),
|
||||
'git_branch': run(['git', '-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], check=False),
|
||||
'dirty': bool(dirty_files),
|
||||
'dirty_file_count': len(dirty_files),
|
||||
'dirty_diff_sha256': diff_digest,
|
||||
'cargo_lock_sha256': sha256(repo / 'Cargo.lock'),
|
||||
'strata': {
|
||||
'upstream_url': url,
|
||||
'upstream_commit': upstream_sha,
|
||||
'subtree_path': SUBTREE,
|
||||
'subtree_tree_at_head': subtree_tree,
|
||||
'import_commit': import_commit,
|
||||
'commits_touching_subtree': len(history),
|
||||
'local_patch_commits': [line.split(' ', 1) for line in history[1:]][:200],
|
||||
},
|
||||
}
|
||||
# Local changes since the import (the committed ones), and against the upstream tree when it is present.
|
||||
if import_commit:
|
||||
stat = run(['git', '-C', repo, 'diff', '--shortstat', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False)
|
||||
diff = run(['git', '-C', repo, 'diff', '--binary', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False)
|
||||
record['strata']['diff_since_import'] = {
|
||||
'shortstat': stat or 'no change',
|
||||
'diff_sha256': hashlib.sha256(diff.encode()).hexdigest(),
|
||||
}
|
||||
have_upstream = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', f'{upstream_sha}^{{commit}}'], capture_output=True).returncode == 0
|
||||
if have_upstream:
|
||||
upstream_tree = run(['git', '-C', repo, 'rev-parse', f'{upstream_sha}^{{tree}}'])
|
||||
record['strata']['diff_vs_upstream'] = {
|
||||
'upstream_tree': upstream_tree,
|
||||
'shortstat': run(['git', '-C', repo, 'diff', '--shortstat', upstream_tree, f'HEAD:{SUBTREE}'], check=False) or 'identical',
|
||||
}
|
||||
else:
|
||||
record['strata']['diff_vs_upstream'] = {
|
||||
'available': False,
|
||||
'why': f'the upstream commit {upstream_sha} is not in this repository (fetch the strata-upstream remote to compare)',
|
||||
}
|
||||
return record
|
||||
|
||||
|
||||
def version_of(repo):
|
||||
text = (repo / 'crates/deploy/Cargo.toml').read_text(encoding='utf-8')
|
||||
return re.search(r'^version = "([^"]+)"', text, re.M).group(1)
|
||||
|
||||
|
||||
def tool_version(*args):
|
||||
return run(args, check=False).splitlines()[0] if run(args, check=False) else None
|
||||
|
||||
|
||||
def add_tree(tar, source_dir, arc_prefix, epoch):
|
||||
for path in sorted(source_dir.rglob('*')):
|
||||
if path.is_file():
|
||||
add_file(tar, path, f'{arc_prefix}/{path.relative_to(source_dir).as_posix()}', epoch, executable=os.access(path, os.X_OK))
|
||||
|
||||
|
||||
def add_file(tar, path, name, epoch, executable=False, data=None):
|
||||
info = tarfile.TarInfo(name)
|
||||
payload = data if data is not None else path.read_bytes()
|
||||
info.size = len(payload)
|
||||
info.mtime = epoch
|
||||
info.mode = 0o755 if executable else 0o644
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = 'root'
|
||||
tar.addfile(info, io.BytesIO(payload))
|
||||
|
||||
|
||||
def package(args):
|
||||
repo = Path(args.repo).resolve()
|
||||
target = Path(args.target_dir).expanduser().resolve() / 'release'
|
||||
out = Path(args.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
if args.provenance:
|
||||
record = json.loads(Path(args.provenance).read_text(encoding='utf-8'))
|
||||
else:
|
||||
record = provenance(repo, args.allow_dirty)
|
||||
if record.get('dirty') and not args.allow_dirty:
|
||||
raise RuntimeError('the provenance record says the tree was dirty; pass --allow-dirty to package it anyway (the manifest keeps the mark)')
|
||||
commit = record['git_commit']
|
||||
version = args.version or version_of(repo)
|
||||
features = sorted(set(args.feature or ['sm86']))
|
||||
name = f'leleka-{version}-{commit[:12]}-linux-x86_64'
|
||||
epoch = int(os.environ.get('SOURCE_DATE_EPOCH', datetime.datetime.now(datetime.timezone.utc).timestamp()))
|
||||
|
||||
members = {} # archive path -> (bytes, executable)
|
||||
binaries = {}
|
||||
for binary in RUNTIME_BINARIES:
|
||||
path = target / binary
|
||||
if not path.is_file():
|
||||
raise RuntimeError(f'{path} is missing; build it first (docs/deploy.md, "Build a release")')
|
||||
data = path.read_bytes()
|
||||
members[f'bin/{binary}'] = (data, True)
|
||||
binaries[binary] = hashlib.sha256(data).hexdigest()
|
||||
for template in TEMPLATES:
|
||||
members[f'share/leleka/templates/{Path(template).name}'] = ((repo / template).read_bytes(), False)
|
||||
for profile in sorted((repo / 'deploy/rust-runtime/profiles').glob('*.json')):
|
||||
members[f'share/leleka/profiles/{profile.name}'] = (profile.read_bytes(), False)
|
||||
for doc in ['docs/deploy.md', 'docs/upstream.md', 'docs/rust-runtime-run.md', 'docs/laptop-profile.md', 'docs/sm86-assets.md']:
|
||||
if (repo / doc).is_file():
|
||||
members[f'share/leleka/docs/{Path(doc).name}'] = ((repo / doc).read_bytes(), False)
|
||||
members['install.sh'] = ((repo / 'deploy/rust-runtime/install.sh').read_bytes(), True)
|
||||
|
||||
ptx_lines = []
|
||||
if not args.no_ptx:
|
||||
sets = {'sm_120': [p for p in (repo / 'crates/cuda-driver').rglob('*.ptx') if 'ptx-sm86' not in p.parts],
|
||||
'sm_86': sorted((repo / 'crates/cuda-driver/ptx-sm86').glob('*.ptx'))}
|
||||
for arch, files in sets.items():
|
||||
for path in sorted(files):
|
||||
data = path.read_bytes()
|
||||
members[f'share/leleka/ptx/{arch}/{path.name}'] = (data, False)
|
||||
ptx_lines.append(f'{hashlib.sha256(data).hexdigest()} {arch}/{path.name}')
|
||||
if (repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').is_file():
|
||||
members['share/leleka/ptx/sm_86-MANIFEST.json'] = ((repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').read_bytes(), False)
|
||||
members['share/leleka/ptx/SHA256SUMS'] = (('\n'.join(ptx_lines) + '\n').encode(), False)
|
||||
|
||||
if args.with_cublas:
|
||||
for path in sorted(Path(args.with_cublas).glob('libcublas*.so*')):
|
||||
members[f'lib/cublas/{path.name}'] = (path.read_bytes(), False)
|
||||
|
||||
manifest = {
|
||||
'schema_version': 1,
|
||||
'name': 'leleka',
|
||||
'version': version,
|
||||
'git_commit': commit,
|
||||
'dirty': bool(record.get('dirty')),
|
||||
'features': features,
|
||||
'binaries': binaries,
|
||||
'built_with': {
|
||||
'rustc': tool_version('rustc', '--version'),
|
||||
'cargo': tool_version('cargo', '--version'),
|
||||
'host': tool_version('uname', '-sr'),
|
||||
'glibc': tool_version('ldd', '--version'),
|
||||
},
|
||||
'runtime_requirements': {
|
||||
'os': 'linux x86_64, glibc',
|
||||
'nvidia_driver_min': 595,
|
||||
'cublas': 'libcublas.so.12 and libcublasLt.so.12 (CUDA 12; pinned redistributable 12.9.1.4 is fetched by `leleka up`)' if not args.with_cublas else 'bundled in lib/cublas (CUDA 12.9.1.4 redistributable, NVIDIA license applies)',
|
||||
'gpu_architectures': ['sm_120'] + (['sm_86..sm_119 (companion PTX, feature sm86)'] if 'sm86' in features else []),
|
||||
},
|
||||
'ptx_included': not args.no_ptx,
|
||||
'created_utc': datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
|
||||
}
|
||||
members['MANIFEST.json'] = ((json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode(), False)
|
||||
members['PROVENANCE.json'] = ((json.dumps(record, indent=2, sort_keys=True) + '\n').encode(), False)
|
||||
sums = ''.join(f'{hashlib.sha256(data).hexdigest()} {path}\n' for path, (data, _) in sorted(members.items()))
|
||||
members['SHA256SUMS'] = (sums.encode(), False)
|
||||
|
||||
tarball = out / f'{name}.tar'
|
||||
with tarfile.open(tarball, 'w', format=tarfile.PAX_FORMAT) as tar:
|
||||
for path, (data, executable) in sorted(members.items()):
|
||||
add_file(tar, None, f'{name}/{path}', epoch, executable, data)
|
||||
compressed = out / f'{name}.tar.xz'
|
||||
import lzma
|
||||
with open(tarball, 'rb') as source, lzma.open(compressed, 'wb', preset=6) as target_file:
|
||||
shutil.copyfileobj(source, target_file)
|
||||
tarball.unlink()
|
||||
digest = sha256(compressed)
|
||||
(out / f'{name}.tar.xz.sha256').write_text(f'{digest} {compressed.name}\n', encoding='ascii')
|
||||
|
||||
# Verify what was written: the member list matches SHA256SUMS byte for byte.
|
||||
with tarfile.open(compressed, 'r:xz') as tar:
|
||||
names = {m.name for m in tar.getmembers() if m.isfile()}
|
||||
sums_member = tar.extractfile(f'{name}/SHA256SUMS').read().decode()
|
||||
for line in sums_member.splitlines():
|
||||
expected, rel = line.split(' ', 1)
|
||||
actual = hashlib.sha256(tar.extractfile(f'{name}/{rel}').read()).hexdigest()
|
||||
if actual != expected:
|
||||
raise RuntimeError(f'verification failed for {rel}')
|
||||
assert names == {f'{name}/{p}' for p in members}
|
||||
print(json.dumps({'tarball': str(compressed), 'sha256': digest, 'bytes': compressed.stat().st_size, 'files': len(members), 'git_commit': commit, 'dirty': manifest['dirty'], 'features': features}, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = parser.add_subparsers(dest='command', required=True)
|
||||
prov = sub.add_parser('provenance', help='write the provenance record of a git checkout')
|
||||
prov.add_argument('--repo', default='.')
|
||||
prov.add_argument('--out', required=True)
|
||||
prov.add_argument('--allow-dirty', action='store_true')
|
||||
pack = sub.add_parser('package', help='assemble the tarball')
|
||||
pack.add_argument('--repo', default='.')
|
||||
pack.add_argument('--target-dir', required=True, help='cargo target dir that holds release/<binaries>')
|
||||
pack.add_argument('--out', default='dist')
|
||||
pack.add_argument('--provenance', help='record made by the `provenance` command (needed when the tree has no .git)')
|
||||
pack.add_argument('--version')
|
||||
pack.add_argument('--feature', action='append', help='Cargo feature the runtime binaries were built with (repeatable; default: sm86)')
|
||||
pack.add_argument('--allow-dirty', action='store_true')
|
||||
pack.add_argument('--no-ptx', action='store_true', help='omit the sealed PTX files (they are embedded in the binaries anyway)')
|
||||
pack.add_argument('--with-cublas', help='directory with libcublas.so.12* / libcublasLt.so.12* to bundle')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'provenance':
|
||||
record = provenance(Path(args.repo).resolve(), args.allow_dirty)
|
||||
Path(args.out).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n', encoding='utf-8')
|
||||
print(f'wrote {args.out}: {record["git_commit"]} dirty={record["dirty"]}')
|
||||
else:
|
||||
package(args)
|
||||
except (RuntimeError, OSError) as error:
|
||||
print(f'package-release: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user