466 lines
17 KiB
Rust
466 lines
17 KiB
Rust
//! 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.extend(profile.memory.args());
|
|
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.memory.env();
|
|
env.extend(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": 32768,
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
/// 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");
|
|
}
|
|
}
|