Files
leleka/crates/deploy/src/config.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 98effcdabd deploy: experimental kar_source none and profile rtx5090-32g-gguf-ple (Leleka without the KAR archive, PLE rows from the GGUF shard)
kar_source none passes no --kar-archive-*/--kar-provenance, loads qwen4exp-native-mtp-v1, skips the kar step and the archive checks, rejects --kar-fd.
Engine env of the new profile: LELEKA_PLE_DIRECT=0 (page cache instead of O_DIRECT). Default profiles unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:21:01 +01:00

794 lines
30 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, NATIVE_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 in a row (without a stable period between them) the supervisor performs before it gives up and
/// exits, so that systemd starts the whole service afresh. Failed restarts count too.
pub max_engine_restarts: u32,
/// An engine that stayed ready this long resets the restart counter.
pub stable_after_s: u64,
/// Wait before the first restart; it doubles with every further one in a row, up to `backoff_max_s`.
#[serde(default = "default_backoff_initial_s")]
pub backoff_initial_s: u64,
#[serde(default = "default_backoff_max_s")]
pub backoff_max_s: u64,
}
fn default_backoff_initial_s() -> u64 {
5
}
fn default_backoff_max_s() -> u64 {
300
}
impl RestartPolicy {
/// Seconds to wait before restart number `attempt` (1-based) in a row.
pub fn backoff(&self, attempt: u32) -> std::time::Duration {
let doubled = self
.backoff_initial_s
.saturating_mul(1u64 << attempt.saturating_sub(1).min(20));
std::time::Duration::from_secs(doubled.min(self.backoff_max_s.max(self.backoff_initial_s)))
}
}
/// Health checks of the running engine (`watchdog.rs`): a hung engine is restarted like a crashed one.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HealthPolicy {
pub enabled: bool,
/// Seconds between two checks of `GET /v1/status`.
pub interval_s: u64,
/// The API does not answer for this long: restart the API; its worker has lost the engine for this long: restart the engine.
pub fail_s: u64,
/// A request still active after this long (the API's own deadline is shorter): the engine makes no progress, restart it.
pub max_request_s: u64,
}
impl Default for HealthPolicy {
fn default() -> Self {
HealthPolicy {
enabled: true,
interval_s: 10,
fail_s: 120,
max_request_s: 3900,
}
}
}
/// What a client sees when the engine stops answering: the API cancels the request with an error instead of leaving it open.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequestLimits {
/// No event from the engine for this long during a request (a cold 256k prefill sends none for about two minutes).
pub stall_timeout_s: u64,
/// Longest wall time of one generation.
pub generation_timeout_s: u64,
}
impl Default for RequestLimits {
fn default() -> Self {
RequestLimits {
stall_timeout_s: 600,
generation_timeout_s: 3600,
}
}
}
/// Bounded logs (`logs.rs`): the supervisor copy-truncates a log past `limit_mib` and keeps `keep` older generations.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LogLimits {
pub limit_mib: u64,
pub keep: usize,
}
impl Default for LogLimits {
fn default() -> Self {
LogLimits {
limit_mib: 16,
keep: 3,
}
}
}
#[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,
/// The profile as `up` resolved it before the resource preset changed it (flags applied): what `leleka reconfigure --preset`
/// recomputes the preset from, so that going back to `dedicated` undoes `workstation`. Absent in files written by older builds.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_profile: Option<Profile>,
/// The resource preset `up` applied (the profile and `engine_env` already carry its numbers).
#[serde(default)]
pub preset: crate::resources::Preset,
/// 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,
#[serde(default)]
pub health: HealthPolicy,
#[serde(default)]
pub request_limits: RequestLimits,
#[serde(default)]
pub logs: LogLimits,
/// Do not hash a shard or the archive again when it is unchanged since it last matched its pinned digest
/// (`docs/deploy.md`, "Fast restarts"). `leleka verify` hashes everything and renews the stamps.
#[serde(default = "default_true")]
pub verify_stamps: bool,
/// `false` only after `leleka up --no-expert-tier`: the ranked VRAM expert tier is switched off on purpose. It is written
/// only when `false`, so configurations of builds without the flag stay byte-identical (`expert_profile.rs`).
#[serde(default = "default_true", skip_serializing_if = "is_true")]
pub expert_tier: bool,
}
fn default_true() -> bool {
true
}
fn is_true(value: &bool) -> bool {
*value
}
/// 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,
/// No archive argument at all (`kar_source: none`): the engine reads the PLE rows from the GGUF shard.
None,
}
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,
base_profile: None,
preset: crate::resources::Preset::default(),
engine_env,
load_timeout_s: 1800,
shutdown_grace_s: 10,
restart: RestartPolicy {
max_engine_restarts: 6,
stable_after_s: 600,
backoff_initial_s: default_backoff_initial_s(),
backoff_max_s: default_backoff_max_s(),
},
health: HealthPolicy::default(),
request_limits: RequestLimits::default(),
logs: LogLimits::default(),
verify_stamps: true,
expert_tier: true,
}
}
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(),
]),
KarArg::None => {}
}
if kar != KarArg::None {
args.extend([
"--kar-provenance".into(),
paths.kar_provenance().display().to_string(),
]);
}
args.extend([
"--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(),
// The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine
// drafts over the full 248k-row head, about 0.2 ms more per draft step.
"--mtp-rt-dir".into(),
paths.mtp_pack().display().to_string(),
]);
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()]);
}
if let Some(value) = profile.spec_min_p {
args.extend(["--spec-min-p".into(), value.to_string()]);
}
args.extend(profile.memory.args());
if self.verify_stamps {
args.extend([
"--verify-stamps".into(),
paths.engine_stamps().display().to_string(),
]);
}
args
}
/// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed.
/// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the
/// supervisor-side hash of the archive file is `leleka verify`'s other half).
pub fn verify_args(&self, rehash: bool) -> Vec<String> {
let paths = self.paths();
let mut args = self.engine_args(KarArg::File);
// Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use.
args.truncate(14);
if self.profile.kar_source == KarSource::File {
args.extend([
"--kar-archive-file".into(),
paths.kar().display().to_string(),
"--kar-provenance".into(),
paths.kar_provenance().display().to_string(),
]);
}
args.push("--verify-only".into());
if rehash {
args.push("--verify-rehash".into());
}
args.extend([
"--verify-stamps".into(),
paths.engine_stamps().display().to_string(),
]);
args
}
pub fn kar_arg(&self) -> KarArg {
match self.profile.kar_source {
KarSource::Memfd => KarArg::Fd,
KarSource::File => KarArg::File,
KarSource::None => KarArg::None,
}
}
/// The typed load's profile id: the KAR PLE form, or `kar_source: none`'s native-PLE form (`qwen4exp-native-mtp-v1`).
pub fn mtp_profile(&self) -> &'static str {
if self.profile.kar_source == KarSource::None {
NATIVE_MTP_PROFILE
} else {
MTP_PROFILE
}
}
/// 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": self.mtp_profile()},
"max_context": self.profile.context_tokens,
// A request to an engine that stopped answering ends with an error instead of staying open.
"stall_timeout_s": self.request_limits.stall_timeout_s,
"generation_timeout_s": self.request_limits.generation_timeout_s,
// The control plane refuses a ceiling that is not below the context (the laptop profile has 8192).
"max_output_tokens": 32768u32.min(self.profile.context_tokens.saturating_sub(1).max(1)),
}
})
}
}
/// 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 (`/dev/urandom`; `BCryptGenRandom` on Windows).
#[cfg(not(windows))]
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)
}
#[cfg(windows)]
pub fn random_bytes(n: usize) -> Result<Vec<u8>, String> {
crate::winsys::random_bytes(n)
}
/// 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::*;
/// Command line as one string with `/` separators, so the expectations read the same on Windows.
fn flat(args: &[String]) -> String {
args.join(" ").replace('\\', "/")
}
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 = flat(&args);
// 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 32819404800 --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 --mtp-rt-dir /data/leleka/data/mtp-rt"));
// The engine parser reads the first 14 arguments positionally.
assert_eq!(args[..14].len(), 14);
assert_eq!(args[12], "--context-tokens");
}
#[test]
fn verify_arguments_keep_the_seven_pairs_and_choose_the_archive_by_profile() {
let server = config("rtx5090-32g");
let args = server.verify_args(false);
assert_eq!(&args[..14], &server.engine_args(KarArg::Fd)[..14]);
let text = flat(&args);
assert!(
text.ends_with("--verify-only --verify-stamps /var/lib/leleka/state/stamps/engine"),
"{text}"
);
assert!(
!text.contains("--kar-archive") && !text.contains("--backend-mode"),
"{text}"
);
assert!(
server
.verify_args(true)
.contains(&"--verify-rehash".to_owned())
);
let laptop = flat(&config("rtx3080-16g").verify_args(true));
assert!(
laptop
.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance"),
"{laptop}"
);
}
#[test]
fn stamps_are_in_the_engine_command_unless_switched_off() {
let mut c = config("rtx5090-32g");
assert!(
flat(&c.engine_args(KarArg::Fd))
.contains("--verify-stamps /var/lib/leleka/state/stamps/engine")
);
c.verify_stamps = false;
assert!(
!c.engine_args(KarArg::Fd)
.join(" ")
.contains("--verify-stamps")
);
}
#[test]
fn laptop_uses_the_file_source_the_256k_context_and_the_6144_chunk() {
let config = config("rtx3080-16g");
assert_eq!(config.kar_arg(), KarArg::File);
let text = flat(&config.engine_args(config.kar_arg()));
assert!(
text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance")
);
assert!(text.contains("--gpu-budget 16106127360 --context-tokens 262144"));
assert!(text.contains("--original-prefill-capacity 6144"), "{text}");
assert!(
text.contains("--prefix-cache-tail prompt")
&& text.contains("--prefix-cache-block 6144"),
"{text}"
);
assert!(text.contains("--expert-source mapped"));
assert!(!text.contains("{FD}"));
}
#[test]
fn the_gguf_ple_profile_passes_no_archive_and_loads_the_native_mtp_profile() {
let c = config("rtx5090-32g-gguf-ple");
assert_eq!(c.kar_arg(), KarArg::None);
assert_eq!(c.mtp_profile(), "qwen4exp-native-mtp-v1");
let args = c.engine_args(c.kar_arg());
let text = flat(&args);
assert!(
!text.contains("--kar") && !text.contains("{FD}"),
"{text}"
);
// the seven fixed pairs stay first and the rest follows without a gap
assert_eq!(args[12], "--context-tokens");
assert_eq!(args[14], "--mtp-pack", "{text}");
assert!(text.contains("--backend-mode original --expert-source resident"), "{text}");
assert_eq!(
c.strata_json()["runtime"]["mode"]["profile_id"],
"qwen4exp-native-mtp-v1"
);
let verify = flat(&c.verify_args(true));
assert!(!verify.contains("--kar"), "{verify}");
assert_eq!(
c.engine_environment().get("LELEKA_PLE_DIRECT").map(String::as_str),
Some("0")
);
}
#[test]
fn every_other_profile_keeps_its_archive_arguments_and_profile_id() {
for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx3080-16g"] {
let c = config(name);
assert_eq!(c.mtp_profile(), "qwen4exp-kar-ple-mtp-v1", "{name}");
let text = flat(&c.engine_args(c.kar_arg()));
assert!(
text.contains("--kar-archive-") && text.contains("--kar-provenance"),
"{name}: {text}"
);
assert!(!c.engine_environment().contains_key("LELEKA_PLE_DIRECT"), "{name}");
}
}
fn config_of(profile: &str) -> RunConfig {
config(profile)
}
#[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"]
.as_str()
.unwrap()
.replace('\\', "/"),
"/data/leleka/tokenizer-assets/tokenizer"
);
assert_eq!(strata["runtime"]["max_context"], 262144);
assert_eq!(strata["runtime"]["max_output_tokens"], 32768);
// A context of 8K needs a ceiling below it, or `strata-next check-config` refuses the file (the laptop profile used to have one).
let mut small = config_of("rtx3080-16g");
small.profile.context_tokens = 8192;
assert_eq!(small.strata_json()["runtime"]["max_output_tokens"], 8191);
assert_eq!(
config_of("rtx3080-16g").strata_json()["runtime"]["max_output_tokens"],
32768
);
// 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
);
}
#[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 the_server_profile_switches_reach_the_engine_environment_through_the_saved_config() {
// `up` saves the RunConfig (profile.engine_env inside) as leleka.json; `run` loads it and `start_engine` hands
// `engine_environment()` to the child (`child_env` sets every pair). The 5090 profile's engine_env must arrive.
let saved = serde_json::to_string(&config("rtx5090-32g")).unwrap();
let loaded: RunConfig = serde_json::from_str(&saved).unwrap();
let env = loaded.engine_environment();
for (key, value) in [
("LELEKA_SM120_ATTN_DAILY_MTP", "1"),
("LELEKA_ORIGINAL_SERVE_SEED", "off"),
("LELEKA_CHAIN", "all"),
] {
assert_eq!(env.get(key).map(String::as_str), Some(value), "{key}");
}
assert!(
!config("rtx3080-16g")
.engine_environment()
.contains_key("LELEKA_SM120_ATTN_DAILY_MTP")
);
// an operator's `engine_env` (the `up` resolved one) wins over the profile
let mut operator = loaded;
operator
.engine_env
.insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "0".into());
assert_eq!(
operator.engine_environment()["LELEKA_SM120_ATTN_DAILY_MTP"],
"0"
);
}
#[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");
}
}