Files
leleka/crates/deploy/src/supervisor.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

1864 lines
73 KiB
Rust

//! `leleka run`: the foreground supervisor that systemd (or a terminal) starts.
//!
//! Order: seal the archive (once) -> gateway -> engine -> wait for the engine port -> typed `load-mtp` through
//! `leleka-cli` -> wait for `model_ready` -> public API -> wait for `/ready` -> supervise. An engine that dies is
//! restarted with the same sealed descriptor (no second 55 GB copy) and loaded again, up to a bound; the API
//! process stays up and reports not-ready meanwhile. SIGTERM/SIGINT drain the API first, then stop the gateway
//! and the engine (both handle SIGINT only), and escalate to SIGKILL after the grace period.
use crate::{
config::{GATEWAY_TOKEN_ENV, KarArg, RUNTIME_TOKEN_ENV, RunConfig},
facts::parse_env_file,
http,
layout::Paths,
logs,
profile::{ARCHIVE_BYTES, KarSource, MemfdExtents, PinSource, archive_sha256, extents_sha256},
reconfigure, sealed, watchdog,
};
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
use serde::Serialize;
use std::{
collections::BTreeMap,
fs::File,
io::Write,
net::SocketAddr,
path::{Path, PathBuf},
process::Stdio,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{
process::{Child, Command},
sync::watch,
time::{sleep, timeout},
};
const LOG_ROTATE_BYTES: u64 = 64 << 20;
/// Set by `--hidden` (the Windows logon task): the children get no console window.
pub static HIDDEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Windows: the long-lived children (engine, gateway, API) get their own process group, so that Ctrl-C typed in the
/// supervisor's terminal reaches only the supervisor, which then stops them in order with Ctrl-Break (`interrupt`). No-op elsewhere.
pub fn own_group(command: &mut Command) {
#[cfg(windows)]
command.creation_flags(0x0000_0200);
#[cfg(not(windows))]
let _ = command;
}
#[derive(Clone, Debug)]
pub struct Options {
pub config: PathBuf,
/// A sealed archive descriptor inherited from a holder process (tests, operator tooling). The supervisor
/// reopens it and does not copy the archive itself.
pub kar_fd: Option<u32>,
}
#[derive(Debug)]
pub struct Failure {
pub code: i32,
pub message: String,
}
fn fail<T>(code: i32, message: impl Into<String>) -> Result<T, Flow> {
Err(Flow::Fatal(Failure {
code,
message: message.into(),
}))
}
#[derive(Debug)]
enum Flow {
/// A stop signal arrived while waiting.
Stopped,
Fatal(Failure),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
Starting,
Sealing,
StartingGateway,
StartingEngine,
Loading,
StartingApi,
Ready,
EngineRestarting,
Draining,
Stopped,
Failed,
}
#[derive(Serialize)]
struct StatusDoc<'a> {
schema_version: u32,
phase: Phase,
ready: bool,
message: &'a str,
updated_unix: u64,
supervisor_pid: u32,
engine_pid: Option<u32>,
gateway_pid: Option<u32>,
api_pid: Option<u32>,
engine_restarts: u32,
endpoint: &'a str,
model: &'a str,
model_digest: &'a str,
profile: &'a str,
kar_source: &'a str,
memfd_extents: &'a str,
/// When this supervisor started (service uptime = now - this).
started_unix: u64,
/// Engine restarts since the service started (crashes, hangs, failed restarts), whatever the in-a-row counter says.
restarts_total: u32,
last_restart_unix: Option<u64>,
last_restart_reason: Option<&'a str>,
/// The hang detector's last judgement ("healthy", or what looks wrong).
health: &'a str,
/// Bytes in the log directory (rotation keeps it bounded).
log_bytes: u64,
}
/// Seconds since the epoch.
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// `YYYY-MM-DDTHH:MM:SSZ` without a date library (days-from-civil, Howard Hinnant).
pub fn format_utc(unix: u64) -> String {
let days = (unix / 86_400) as i64;
let secs = unix % 86_400;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if month <= 2 { year + 1 } else { year };
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
secs / 3600,
secs % 3600 / 60,
secs % 60
)
}
/// Move a log that grew past the limit to `NAME.1` (one generation is kept).
pub fn rotate_log(path: &Path, limit: u64) -> std::io::Result<bool> {
match std::fs::metadata(path) {
Ok(meta) if meta.len() > limit => {
let mut old = path.as_os_str().to_owned();
old.push(".1");
std::fs::rename(path, PathBuf::from(old))?;
Ok(true)
}
_ => Ok(false),
}
}
fn open_log(path: &Path) -> std::io::Result<File> {
rotate_log(path, LOG_ROTATE_BYTES)?;
private_append(path)
}
fn private_append(path: &Path) -> std::io::Result<File> {
let mut options = std::fs::OpenOptions::new();
options.create(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)
}
/// Write `contents` atomically with mode 0600.
pub fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
let mut tmp = path.as_os_str().to_owned();
tmp.push(format!(".tmp{}", std::process::id()));
let tmp = PathBuf::from(tmp);
{
let mut options = std::fs::OpenOptions::new();
options.create(true).truncate(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&tmp)?;
file.write_all(contents.as_bytes())?;
file.sync_all()?;
}
std::fs::rename(tmp, path)
}
struct Log {
file: std::sync::Mutex<File>,
}
impl Log {
/// A free-text note of the supervisor (the text is the message of a `msg` event).
fn line(&self, message: &str) {
self.event(leleka_obs::Level::Info, "msg", &[("msg", message.into())]);
}
/// One structured event: JSON in `leleka.log`, and on standard error (the journal, or the terminal as key=value text).
/// Lifecycle events are rare by nature, so they are not sampled.
fn event(&self, level: leleka_obs::Level, ev: &str, fields: &[leleka_obs::Field<'_>]) {
let now = leleka_obs::now_ms();
let file_format = leleka_obs::Settings {
min_level: leleka_obs::Level::Debug,
format: leleka_obs::Format::Json,
debug: false,
legacy: false,
};
let file_line =
leleka_obs::format_line(&file_format, now, level, "supervisor", ev, fields, 0) + "\n";
if level >= leleka_obs::settings().min_level {
let shown = leleka_obs::format_line(
leleka_obs::settings(),
now,
level,
"supervisor",
ev,
fields,
0,
) + "\n";
let _ = std::io::stderr().write_all(shown.as_bytes());
}
if let Ok(mut file) = self.file.lock() {
let _ = file.write_all(file_line.as_bytes());
}
}
}
/// `model_ready` of the runtime `id` in `leleka-cli status` output; `connected` is the second value.
pub fn parse_runtime_status(text: &str, id: &str) -> Option<(bool, bool)> {
let value: serde_json::Value = serde_json::from_str(text).ok()?;
let runtime = value
.get("runtimes")?
.as_array()?
.iter()
.find(|r| r.get("id").and_then(|v| v.as_str()) == Some(id))?;
Some((
runtime
.get("connected")
.and_then(|v| v.as_bool())
.unwrap_or(false),
runtime
.get("model_ready")
.and_then(|v| v.as_bool())
.unwrap_or(false),
))
}
/// `runtime.proto` `OperationResult.State`.
const OPERATION_FAILED: i64 = 3;
const OPERATION_INDETERMINATE: i64 = 4;
/// The operation id and epoch that `leleka-cli load-mtp` prints before it sends the command.
pub fn parse_operation(text: &str) -> Option<(String, String)> {
text.lines().find_map(|line| {
let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
Some((
value.get("operation_id")?.as_str()?.to_owned(),
value.get("epoch")?.as_str()?.to_owned(),
))
})
}
/// `state` of the pretty JSON that `leleka-cli operation` prints (the numeric `OperationResult.State`).
pub fn parse_operation_state(text: &str) -> Option<i64> {
let value: serde_json::Value = serde_json::from_str(text.trim()).ok()?;
value.get("state")?.as_i64()
}
/// The last `lines` lines of a text file (empty when it cannot be read; only the last 256 KiB are looked at).
pub fn tail_of(path: &Path, lines: usize) -> String {
use std::io::{Read, Seek, SeekFrom};
let Ok(mut file) = File::open(path) else {
return String::new();
};
let len = file.metadata().map_or(0, |m| m.len());
let from = len.saturating_sub(256 << 10);
let mut bytes = Vec::new();
if file.seek(SeekFrom::Start(from)).is_err() || file.read_to_end(&mut bytes).is_err() {
return String::new();
}
let text = String::from_utf8_lossy(&bytes);
let all: Vec<&str> = text.lines().collect();
all[all.len().saturating_sub(lines)..]
.iter()
.map(|l| l.chars().take(240).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
}
/// Token rule of the runtime: 32..4096 printable ASCII bytes.
pub fn valid_token(token: &str) -> bool {
(32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b))
}
struct Supervisor {
config: RunConfig,
paths: Paths,
env: BTreeMap<String, String>,
api_key: String,
log: Log,
status_path: PathBuf,
shutdown: watch::Receiver<bool>,
archive: Option<File>,
/// Identity of the file the sealed archive was copied from (device, inode, size, mtime, ctime), when stable.
source_identity: Option<FileIdentity>,
/// The sealed archive is known to match its pinned digest (stamp of its source file, or a previous engine of
/// this supervisor verified this very memfd): the engine is told not to hash it again.
archive_attested: bool,
/// `memfd_extents: ple_only`: the pinned SHA-256 of the archive's extents. The memfd holds only those bytes (or all of them, when it
/// came from a holder) and the engine verifies it against this digest instead of the archive's SHA-256; no stamp or attestation
/// of the whole archive applies to it.
archive_sparse_pin: Option<[u8; 32]>,
stamps: VerifyStamps,
api_addr: SocketAddr,
engine_addr: SocketAddr,
daemon_addr: SocketAddr,
engine_restarts: u32,
pids: [Option<u32>; 3],
phase: Phase,
message: String,
beats: u32,
started_unix: u64,
restarts_total: u32,
last_restart: Option<(u64, String)>,
health_note: String,
}
pub async fn run(options: Options) -> i32 {
match run_inner(options).await {
Ok(()) => 0,
Err(failure) => {
eprintln!("leleka: {}", failure.message);
failure.code
}
}
}
async fn run_inner(options: Options) -> Result<(), Failure> {
let config =
RunConfig::read(&options.config).map_err(|message| Failure { code: 2, message })?;
let paths = config.paths();
let stamps_dir = paths.engine_stamps();
for dir in [
paths.logs(),
paths.run_dir(),
paths.mtp_staging(),
stamps_dir.clone(),
] {
std::fs::create_dir_all(&dir).map_err(|e| Failure {
code: 2,
message: format!("cannot create {}: {e}", dir.display()),
})?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for private in [paths.mtp_staging(), stamps_dir.clone()] {
let _ = std::fs::set_permissions(private, std::fs::Permissions::from_mode(0o700));
}
}
let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| Failure {
code: 2,
message: format!(
"cannot read {}: {e}; run `leleka up`",
paths.env_file().display()
),
})?;
let env = parse_env_file(&env_text);
let (runtime_token, gateway_token) = (env.get(RUNTIME_TOKEN_ENV), env.get(GATEWAY_TOKEN_ENV));
match (runtime_token, gateway_token) {
(Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => {}
_ => {
return Err(Failure {
code: 2,
message: format!(
"{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} values of 32..4096 printable ASCII bytes",
paths.env_file().display()
),
});
}
}
let api_key = std::fs::read_to_string(paths.api_key())
.map_err(|e| Failure {
code: 2,
message: format!("cannot read {}: {e}", paths.api_key().display()),
})?
.trim_end_matches(['\r', '\n'])
.to_owned();
for name in [
"leleka",
"strata-next",
"leleka-inference",
"leleka-daemon",
"leleka-cli",
] {
if !paths.bin(name).is_file() {
return Err(Failure {
code: 2,
message: format!("{} is missing; run `leleka up`", paths.bin(name).display()),
});
}
}
let parse = |label: &str, text: &str| -> Result<SocketAddr, Failure> {
text.parse().map_err(|_| Failure {
code: 2,
message: format!("ports.{label} is not an ip:port"),
})
};
let (api_addr, engine_addr, daemon_addr) = (
crate::config::probe_address(&config.ports.api).ok_or(Failure {
code: 2,
message: "ports.api is not an ip:port".into(),
})?,
parse("engine", &config.ports.engine)?,
parse("daemon", &config.ports.daemon)?,
);
// No log line of this process or of its children may ever contain the key or a token.
leleka_obs::register_secret(&api_key);
for value in env.values() {
leleka_obs::register_secret(value);
}
let log_file = open_log(&paths.logs().join("leleka.log")).map_err(|e| Failure {
code: 2,
message: format!("cannot open the log: {e}"),
})?;
let (stop_tx, stop_rx) = watch::channel(false);
spawn_signal_task(stop_tx, paths.run_dir());
let mut supervisor = Supervisor {
status_path: paths.status_file(),
config,
paths,
env,
api_key,
log: Log {
file: std::sync::Mutex::new(log_file),
},
shutdown: stop_rx,
archive: None,
source_identity: None,
archive_attested: false,
archive_sparse_pin: None,
stamps: VerifyStamps::new(stamps_dir, false),
api_addr,
engine_addr,
daemon_addr,
engine_restarts: 0,
pids: [None; 3],
phase: Phase::Starting,
message: String::new(),
beats: 0,
started_unix: unix_now(),
restarts_total: 0,
last_restart: None,
health_note: "starting".into(),
};
supervisor.set_phase(Phase::Starting, "starting");
let outcome = supervisor.drive(options.kar_fd).await;
let result = match outcome {
Ok(()) | Err(Flow::Stopped) => Ok(()),
Err(Flow::Fatal(failure)) => {
supervisor.log.event(
leleka_obs::Level::Error,
"fatal",
&[
("code", failure.code.into()),
("msg", format!("fatal: {}", failure.message).as_str().into()),
],
);
supervisor.set_phase(Phase::Failed, &failure.message);
Err(failure)
}
};
if result.is_ok() {
supervisor.set_phase(Phase::Stopped, "stopped");
}
result
}
#[cfg(windows)]
fn leleka_libc_shim_dll_dirs_env() -> &'static str {
"LELEKA_DLL_DIRS"
}
/// The file `leleka down` creates on Windows (there is no signal to send to a supervisor in another console).
pub const STOP_REQUEST_FILE: &str = "stop.request";
fn spawn_signal_task(stop: watch::Sender<bool>, run_dir: PathBuf) {
// Windows: Ctrl-C / Ctrl-Break / console close in this terminal, or `leleka down` from another one (a stop file).
#[cfg(windows)]
{
let request = run_dir.join(STOP_REQUEST_FILE);
let _ = std::fs::remove_file(&request);
tokio::spawn(async move {
let mut ctrl_break = tokio::signal::windows::ctrl_break().ok();
let mut ctrl_close = tokio::signal::windows::ctrl_close().ok();
loop {
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = async { match ctrl_break.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break,
_ = async { match ctrl_close.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break,
_ = tokio::time::sleep(Duration::from_millis(500)) => {
if request.exists() {
let _ = std::fs::remove_file(&request);
break;
}
}
}
}
let _ = stop.send(true);
});
}
#[cfg(not(windows))]
let _ = run_dir;
#[cfg(unix)]
tokio::spawn(async move {
use tokio::signal::unix::{SignalKind, signal};
let (Ok(mut term), Ok(mut int)) = (
signal(SignalKind::terminate()),
signal(SignalKind::interrupt()),
) else {
return;
};
tokio::select! {
_ = term.recv() => {}
_ = int.recv() => {}
}
let _ = stop.send(true);
});
#[cfg(not(any(unix, windows)))]
drop(stop);
}
impl Supervisor {
fn set_phase(&mut self, phase: Phase, message: &str) {
self.phase = phase;
self.message = message.to_owned();
self.write_status();
}
/// Rewrite the status file as it is, so that its `updated_unix` shows that the supervisor is alive (`leleka status` calls a
/// status that is minutes old stale).
fn heartbeat(&mut self) {
self.write_status();
}
fn write_status(&self) {
let (phase, message) = (self.phase, self.message.as_str());
let endpoint = format!("http://{}", self.api_addr);
let doc = StatusDoc {
schema_version: 1,
phase,
ready: phase == Phase::Ready,
message,
updated_unix: unix_now(),
supervisor_pid: std::process::id(),
engine_pid: self.pids[0],
gateway_pid: self.pids[1],
api_pid: self.pids[2],
engine_restarts: self.engine_restarts,
endpoint: &endpoint,
model: &self.config.model_id,
model_digest: &self.config.model_digest,
profile: &self.config.profile.name,
kar_source: self.config.profile.kar_source.as_str(),
memfd_extents: self.config.profile.memfd_extents.as_str(),
started_unix: self.started_unix,
restarts_total: self.restarts_total,
last_restart_unix: self.last_restart.as_ref().map(|(at, _)| *at),
last_restart_reason: self.last_restart.as_ref().map(|(_, why)| why.as_str()),
health: &self.health_note,
log_bytes: logs::total_bytes(&self.paths.logs()),
};
if let Ok(text) = serde_json::to_string_pretty(&doc) {
let _ = write_private(&self.status_path, &(text + "\n"));
}
}
fn stopping(&self) -> bool {
*self.shutdown.borrow()
}
/// Sleep unless a stop arrives first. False: stop requested.
async fn pause(&mut self, duration: Duration) -> bool {
tokio::select! {
_ = sleep(duration) => !self.stopping(),
_ = self.shutdown.changed() => false,
}
}
fn child_env(&self, command: &mut Command, extra: &BTreeMap<String, String>) {
command.env_remove("HF_TOKEN");
// Observability (docs in `leleka --help`): the API writes one record per request to its own rotated file, every process logs
// JSON lines (their standard error is a file), and the API can read the supervisor's restart counters for /metrics.
command.env("LELEKA_REQUEST_LOG", self.paths.logs().join("requests.log"));
command.env("LELEKA_STATUS_FILE", &self.status_path);
command.env("LELEKA_PROFILE", &self.config.profile.name);
command.env("LELEKA_LOG_FORMAT", "json");
for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] {
if let Some(value) = self.env.get(key) {
command.env(key, value);
}
}
#[cfg(windows)]
if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH").filter(|p| !p.is_empty()) {
// The loader flags of the engine search the application directory and System32 plus the directories named
// here (`leleka-libc-shim` registers them), so the cuBLAS DLLs can stay where the operator keeps them.
command.env(leleka_libc_shim_dll_dirs_env(), extra_path);
let existing = std::env::var("PATH").unwrap_or_default();
command.env("PATH", format!("{extra_path};{existing}"));
}
#[cfg(not(windows))]
if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH") {
let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default();
let joined = if existing.is_empty() {
extra_path.clone()
} else {
format!("{extra_path}:{existing}")
};
command.env("LD_LIBRARY_PATH", joined);
}
for (key, value) in extra {
command.env(key, value);
}
}
fn spawn(
&self,
name: &str,
program: &Path,
args: &[String],
extra: &BTreeMap<String, String>,
stdin: Option<File>,
) -> Result<Child, Flow> {
let log = private_append(&self.paths.logs().join(format!("{name}.log")))
.and_then(|f| f.try_clone().map(|g| (f, g)))
.map_err(|e| format!("cannot open the {name} log: {e}"));
let (out, err) = match log {
Ok(pair) => pair,
Err(message) => return fail(1, message),
};
let mut command = Command::new(program);
own_group(&mut command);
command
.args(args)
.stdout(Stdio::from(out))
.stderr(Stdio::from(err))
.kill_on_drop(true);
command.stdin(match stdin {
Some(file) => Stdio::from(file),
None => Stdio::null(),
});
self.child_env(&mut command, extra);
match command.spawn() {
Ok(child) => Ok(child),
Err(error) => fail(
1,
format!("cannot start {name} ({}): {error}", program.display()),
),
}
}
/// Are both shards stamped as verified in their present state? (Then an engine start hashes neither.)
fn shard_stamps_current(&self) -> bool {
(0..2).all(|index| {
let digest = {
let mut out = [0u8; 32];
hex::decode_to_slice(crate::profile::SHARD_SHA256_HEX[index], &mut out)
.is_ok()
.then_some(out)
};
let identity = std::fs::File::open(self.paths.shard(index))
.and_then(|f| f.metadata())
.ok()
.and_then(|m| FileIdentity::of(&m));
matches!((digest, identity), (Some(d), Some(id)) if self.stamps.trusts("gguf", &d, &id))
})
}
/// While the supervisor fills the sealed memfd (reading 55 GB), a CPU-only `leleka-inference --verify-only`
/// hashes the two shards and records their stamps, so the engine that starts right after finds them verified.
/// The two reads overlap instead of following each other. Same verification, same refusals: a shard that does
/// not match its pin fails the start here, and a shard that changes before the engine opens it is hashed again
/// by the engine because the stamp no longer matches.
fn spawn_shard_preverify(&self) -> Option<Child> {
if !self.config.verify_stamps || self.shard_stamps_current() {
return None;
}
let program = self.paths.bin("leleka-inference");
let args = self.config.verify_args(false);
match self.spawn("preverify", &program, &args, &BTreeMap::new(), None) {
Ok(child) => {
self.log.line(
"hashing the shards while the archive is copied (stamps are not current)",
);
Some(child)
}
Err(_) => None,
}
}
/// The pin of the extents when the profile asks for a sparse memfd (`None` for the full copy); refuses to start without one.
fn sparse_pin(&self) -> Result<Option<[u8; 32]>, Flow> {
if self.config.profile.memfd_extents != MemfdExtents::PleOnly {
return Ok(None);
}
match extents_sha256(&|key| std::env::var(key).ok()) {
Ok((pin, source)) => {
self.log.line(&format!(
"memfd_extents=ple_only: only the byte ranges the serve path reads are in the sealed memfd; the engine verifies them against the extents digest {}{}",
pin.iter().map(|b| format!("{b:02x}")).collect::<String>(),
match source {
PinSource::Compiled => " (pinned in the binary)",
PinSource::Operator => " (supplied by LELEKA_KAR_EXTENTS_SHA256, not pinned in the binary)",
}
));
Ok(Some(pin))
}
Err(message) => fail(1, message),
}
}
/// The page-aligned ranges of the archive file the serve path reads, from its header and directory (about a megabyte of reads).
fn serve_extents(kar: &Path) -> Result<Vec<leleka_model_format::kar::Extent>, Flow> {
match sealed::archive_serve_extents(kar, ARCHIVE_BYTES) {
Ok(extents) => Ok(extents),
Err(message) => fail(1, message),
}
}
async fn drive(&mut self, kar_fd: Option<u32>) -> Result<(), Flow> {
// 1. the archive
self.archive = match (kar_fd, self.config.profile.kar_source) {
(Some(fd), KarSource::None) => {
return fail(
2,
format!(
"descriptor {fd} was inherited but profile {} has kar_source none (no archive is used)",
self.config.profile.name
),
);
}
(None, KarSource::None) => {
self.log.line("kar_source none: no KAR archive; the PLE rows are read from the GGUF shard (qwen4exp-native-mtp-v1)");
None
}
(Some(fd), _) => {
self.log.line(&format!(
"using the sealed archive descriptor {fd} inherited from the parent"
));
self.archive_sparse_pin = self.sparse_pin()?;
Some(
sealed::open_inherited(fd)
.map_err(|message| Flow::Fatal(Failure { code: 2, message }))?,
)
}
(None, KarSource::Memfd) => {
let kar = self.paths.kar();
// `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd.
let sparse = self.sparse_pin()?;
let extents = match sparse {
Some(_) => Some(Self::serve_extents(&kar)?),
None => None,
};
match &extents {
Some(list) => {
self.set_phase(
Phase::Sealing,
"copying the archive extents the serve path reads into a sealed memfd",
);
self.log.line(&format!(
"sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest of the memfd is a hole (once per service life)",
list.len(),
leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0,
ARCHIVE_BYTES as f64 / 1073741824.0,
kar.display()
));
}
None => {
self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd");
self.log.line(&format!(
"sealing {} into RAM (once per service life)",
kar.display()
));
}
}
let started = Instant::now();
let mut preverify = self.spawn_shard_preverify();
// A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine
// skip the hash of the memfd; it applies only if the file is still in the stamped state before
// AND after the copy.
let before = std::fs::File::open(&kar)
.and_then(|f| f.metadata())
.ok()
.and_then(|m| FileIdentity::of(&m));
let stamped = self.config.verify_stamps
&& before
.is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id));
let log = &self.log;
let mut progress = |done: u64, total: u64| {
log.line(&format!(
"sealing archive: {:.1} of {:.1} GiB",
done as f64 / 1073741824.0,
total as f64 / 1073741824.0
));
};
let sealed = match &extents {
Some(list) => {
sealed::seal_extents_report(&kar, Some(ARCHIVE_BYTES), list, &mut progress)
}
None => sealed::seal_file_report(&kar, Some(ARCHIVE_BYTES), &mut progress),
};
if let Some(child) = preverify.as_mut() {
let waited = Instant::now();
match child.wait().await {
Ok(status) if status.success() => self.log.line(&format!(
"shards verified ({:.1}s after the copy ended)",
waited.elapsed().as_secs_f32()
)),
Ok(status) => {
return fail(
1,
format!(
"a shard does not match its pinned digest ({status}); see {}",
self.paths.logs().join("preverify.log").display()
),
);
}
Err(error) => {
return fail(1, format!("shard verification did not finish: {error}"));
}
}
}
match sealed {
Ok((file, identity, read)) => {
self.log.line(&format!(
"sealed memfd ready in {:.1}s (read: {} blocks, {:.0} MB/s)",
started.elapsed().as_secs_f32(),
read.strategy.as_str(),
read.mb_per_s()
));
if sparse.is_some() {
// A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation.
self.archive_sparse_pin = sparse;
self.source_identity = None;
self.archive_attested = false;
} else {
self.source_identity = identity;
self.archive_attested = stamped && identity == before;
}
if self.archive_attested {
self.log.line("the archive file matches its verification stamp: the engine will not hash the copy again");
}
Some(file)
}
Err(message) => return fail(1, format!("cannot seal the archive: {message}")),
}
}
(None, KarSource::File) => None,
};
if self.stopping() {
return Err(Flow::Stopped);
}
// 2. gateway (needed for the typed load)
self.set_phase(Phase::StartingGateway, "starting the gateway");
let daemon_args = vec![
"--config".to_owned(),
self.paths.daemon_config().display().to_string(),
];
let mut gateway = self.spawn(
"gateway",
&self.paths.bin("leleka-daemon"),
&daemon_args,
&BTreeMap::new(),
None,
)?;
self.pids[1] = gateway.id();
let mut engine = match self.start_engine(&mut gateway).await {
Ok(engine) => engine,
Err(flow) => {
self.kill_children(&mut [Some(&mut gateway)]).await;
return Err(flow);
}
};
// 3. public API
self.set_phase(Phase::StartingApi, "starting the API");
let api_args = vec![
"serve".to_owned(),
"--config".to_owned(),
self.paths.strata_config().display().to_string(),
];
let mut api = match self.spawn(
"api",
&self.paths.bin("strata-next"),
&api_args,
&BTreeMap::new(),
None,
) {
Ok(child) => child,
Err(flow) => {
self.kill_children(&mut [Some(&mut engine), Some(&mut gateway)])
.await;
return Err(flow);
}
};
self.pids[2] = api.id();
if let Err(flow) = self.wait_api_ready(&mut api).await {
self.kill_children(&mut [Some(&mut api), Some(&mut engine), Some(&mut gateway)])
.await;
return Err(flow);
}
self.set_phase(Phase::Ready, "ready");
self.log.line(&format!(
"ready: http://{} model {} (profile {}, logs {})",
self.api_addr,
self.config.model_id,
self.config.profile.name,
self.paths.logs().display()
));
let mut ready_since = Instant::now();
// Gateway and API restarts in a row; like the engine's they are forgotten after a stable period, so that a service that
// runs for weeks is not ended by the sixth API crash of the month.
let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32);
let (mut gateway_since, mut api_since) = (Instant::now(), Instant::now());
let stable = Duration::from_secs(self.config.restart.stable_after_s);
// `leleka reconfigure` leaves a request file; look for it once a second.
let mut requests = tokio::time::interval(Duration::from_secs(1));
requests.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut logs_tick = tokio::time::interval(Duration::from_secs(10));
logs_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let health = self.config.health.clone();
let mut health_tick = tokio::time::interval(Duration::from_secs(health.interval_s.max(1)));
health_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut watchdog = watchdog::Watchdog::new(watchdog::Limits {
fail: Duration::from_secs(health.fail_s),
max_request: Duration::from_secs(health.max_request_s),
});
// 4. supervise
let result: Result<(), Flow> = loop {
tokio::select! {
_ = self.shutdown.changed() => break Ok(()),
_ = requests.tick() => {
let Some(taken) = reconfigure::take_request(&self.paths) else { continue };
match taken {
Err(message) => {
self.log.line(&format!("reconfigure: {message}"));
self.answer("", reconfigure::State::Refused, message, false);
}
Ok(request) => match self.reconfigure(request, &mut engine, &mut gateway, &mut api).await {
Ok(()) => {
ready_since = Instant::now();
watchdog.reset();
}
Err(Flow::Stopped) => break Ok(()),
Err(flow) => break Err(flow),
},
}
}
status = engine.wait() => {
let text = status.map_or_else(|e| e.to_string(), |s| s.to_string());
self.log.event(
leleka_obs::Level::Warn,
"engine_exit",
&[("status", text.as_str().into()), ("restarts_total", self.restarts_total.into()), ("msg", "the API reports not-ready until the engine is back".into())],
);
match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, format!("the engine process exited ({text})")).await {
Ok(()) => watchdog.reset(),
Err(Flow::Stopped) => break Ok(()),
Err(flow) => break Err(flow),
}
}
_ = logs_tick.tick() => {
self.enforce_logs();
self.beats += 1;
if self.beats.is_multiple_of(3) {
self.heartbeat();
}
}
_ = health_tick.tick(), if self.config.health.enabled => {
let sample = self.sample_health().await;
match watchdog.observe(Instant::now(), &sample) {
watchdog::Verdict::Healthy => self.note_health("healthy"),
watchdog::Verdict::Suspect(why) => {
if self.health_note != why {
self.log.event(leleka_obs::Level::Warn, "health", &[("finding", why.as_str().into())]);
}
self.note_health(&why);
}
watchdog::Verdict::RestartApi(why) => {
self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "api".into()), ("reason", why.as_str().into())]);
self.restarts_total += 1;
self.last_restart = Some((unix_now(), why));
api_since = Instant::now();
match self.restart_api(&mut api).await {
Ok(()) => watchdog.reset(),
Err(Flow::Stopped) => break Ok(()),
Err(flow) => break Err(flow),
}
}
watchdog::Verdict::RestartEngine(why) => {
self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "engine".into()), ("reason", why.as_str().into())]);
if let Err(flow) = self.hard_kill(&mut engine).await {
break Err(flow);
}
match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, why).await {
Ok(()) => watchdog.reset(),
Err(Flow::Stopped) => break Ok(()),
Err(flow) => break Err(flow),
}
}
}
}
status = gateway.wait() => {
let text = status.map_or_else(|e| e.to_string(), |s| s.to_string());
if gateway_since.elapsed() >= stable {
gateway_restarts = 0;
}
gateway_restarts += 1;
self.log.event(
leleka_obs::Level::Warn,
"gateway_exit",
&[("status", text.as_str().into()), ("restart", gateway_restarts.into()), ("of", 3u32.into())],
);
if gateway_restarts > 3 {
break fail(1, "the gateway keeps dying");
}
if !self.pause(Duration::from_secs(2)).await {
break Ok(());
}
gateway = self.spawn("gateway", &self.paths.bin("leleka-daemon"), &daemon_args, &BTreeMap::new(), None)?;
self.pids[1] = gateway.id();
gateway_since = Instant::now();
}
status = api.wait() => {
let text = status.map_or_else(|e| e.to_string(), |s| s.to_string());
if api_since.elapsed() >= stable {
api_restarts = 0;
}
api_restarts += 1;
self.log.event(
leleka_obs::Level::Warn,
"api_exit",
&[("status", text.as_str().into()), ("restart", api_restarts.into()), ("of", 5u32.into())],
);
if api_restarts > 5 {
break fail(1, "the API keeps dying");
}
if !self.pause(Duration::from_secs(2)).await {
break Ok(());
}
api = self.spawn("api", &self.paths.bin("strata-next"), &api_args, &BTreeMap::new(), None)?;
self.pids[2] = api.id();
api_since = Instant::now();
}
}
};
// 5. drain: API first so streams end with a terminal event, then the gateway and the engine.
self.set_phase(Phase::Draining, "draining");
self.log.line("stopping: API, gateway, engine");
self.kill_children(&mut [Some(&mut api), Some(&mut gateway), Some(&mut engine)])
.await;
self.pids = [None; 3];
result
}
/// Engine process -> port -> gateway connected -> typed load -> model_ready.
async fn start_engine(&mut self, gateway: &mut Child) -> Result<Child, Flow> {
self.set_phase(Phase::StartingEngine, "starting the engine");
// The expert tier is re-checked at every start: a missing or changed table is logged loudly and the engine is
// not handed the switches that name it (`expert_profile::start_environment`).
let (env, tier) =
crate::expert_profile::start_environment(&self.config, &self.paths.dirs.assets);
self.log.line(&tier.line());
let inference = self.paths.bin("leleka-inference");
let (kar_arg, stdin) = match &self.archive {
Some(file) => (
KarArg::Fd,
Some(file.try_clone().map_err(|e| {
Flow::Fatal(Failure {
code: 1,
message: format!("cannot duplicate the sealed descriptor: {e}"),
})
})?),
),
None if self.config.profile.kar_source == KarSource::None => (KarArg::None, None),
None => (KarArg::File, None),
};
let mut engine_args = self.config.engine_args(kar_arg);
if let Some(pin) = self.archive_sparse_pin
&& stdin.is_some()
{
engine_args.push("--kar-sparse-extents-sha256".into());
engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect());
} else if self.archive_attested && stdin.is_some() {
engine_args.push("--kar-attested-by-stamp".into());
}
let mut engine = if stdin.is_some() {
let mut args = vec![
"exec-inherit".to_owned(),
"--".to_owned(),
inference.display().to_string(),
];
args.extend(engine_args);
self.spawn("engine", &self.paths.bin("leleka"), &args, &env, stdin)?
} else {
self.spawn("engine", &inference, &engine_args, &env, None)?
};
self.pids[0] = engine.id();
self.log.line(&format!(
"engine started (pid {:?}); the log is {}",
engine.id(),
self.paths.logs().join("engine.log").display()
));
let result = self.load_model(&mut engine, gateway).await;
if let Err(flow) = result {
self.kill_children(&mut [Some(&mut engine)]).await;
self.pids[0] = None;
return Err(flow);
}
// The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the
// life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file
// in a stable state, record that state so the next start of the service can skip the hash too.
if self.config.verify_stamps && self.archive.is_some() && self.archive_sparse_pin.is_none()
{
if !self.archive_attested
&& let Some(identity) = self.source_identity
{
match self
.stamps
.record("kar-source", &archive_sha256(), &identity)
{
Ok(()) => self
.log
.line("recorded the verification stamp of the archive file"),
Err(error) => self
.log
.line(&format!("could not record the archive stamp: {error}")),
}
}
self.archive_attested = true;
}
Ok(engine)
}
async fn wait_port(
&mut self,
address: SocketAddr,
watched: &mut Child,
what: &str,
limit: Duration,
) -> Result<(), Flow> {
let started = Instant::now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
}
if let Ok(Some(status)) = watched.try_wait() {
return fail(
1,
format!(
"{what} exited ({status}) before listening on {address}; see {}",
self.paths.logs().display()
),
);
}
if tokio::net::TcpStream::connect(address).await.is_ok() {
return Ok(());
}
if started.elapsed() > limit {
return fail(
1,
format!(
"{what} did not listen on {address} within {}s",
limit.as_secs()
),
);
}
if !self.pause(Duration::from_millis(500)).await {
return Err(Flow::Stopped);
}
}
}
async fn cli(&self, args: &[&str]) -> Result<(bool, String), String> {
let mut command = Command::new(self.paths.bin("leleka-cli"));
command
.arg("--config")
.arg(self.paths.daemon_config())
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
self.child_env(&mut command, &BTreeMap::new());
let output = timeout(Duration::from_secs(60), command.output())
.await
.map_err(|_| "leleka-cli timed out".to_owned())?
.map_err(|e| format!("cannot run leleka-cli: {e}"))?;
Ok((
output.status.success(),
String::from_utf8_lossy(&output.stdout).into_owned(),
))
}
async fn load_model(&mut self, engine: &mut Child, gateway: &mut Child) -> Result<(), Flow> {
let engine_addr = self.engine_addr;
self.wait_port(engine_addr, engine, "the engine", Duration::from_secs(300))
.await?;
let daemon_addr = self.daemon_addr;
self.wait_port(daemon_addr, gateway, "the gateway", Duration::from_secs(60))
.await?;
let id = self.config.model_id.clone();
// The gateway connects to the engine lazily; wait until it reports the runtime connected.
let started = Instant::now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
}
if let Ok(Some(status)) = engine.try_wait() {
return fail(
1,
format!("the engine exited ({status}) before the gateway connected"),
);
}
if let Ok((true, text)) = self.cli(&["status"]).await
&& parse_runtime_status(&text, &id).is_some_and(|(connected, _)| connected)
{
break;
}
if started.elapsed() > Duration::from_secs(120) {
return fail(1, "the gateway did not connect to the engine within 120 s");
}
if !self.pause(Duration::from_secs(2)).await {
return Err(Flow::Stopped);
}
}
self.set_phase(
Phase::Loading,
"loading the model (verifies the shards and the archive)",
);
self.log.line("loading the model: leleka-cli load-mtp (the engine verifies SHA-256 of shards and archive; this takes minutes)");
let operation: Option<(String, String)> =
match self.cli(&["load-mtp", &id, self.config.mtp_profile()]).await {
Ok((true, text)) => parse_operation(&text),
// The CLI never retries an uncertain command; neither do we.
Ok((false, text)) => {
return fail(
1,
format!(
"load-mtp was refused: {}",
text.lines().last().unwrap_or("no output")
),
);
}
Err(message) => return fail(1, message),
};
let started = Instant::now();
let mut last_report = Instant::now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
}
if let Ok(Some(status)) = engine.try_wait() {
return fail(
1,
format!(
"the engine exited ({status}) while loading; see {}",
self.paths.logs().join("engine.log").display()
),
);
}
if let Ok((true, text)) = self.cli(&["status"]).await
&& parse_runtime_status(&text, &id).is_some_and(|(_, ready)| ready)
{
self.log.line(&format!(
"model loaded in {:.0}s",
started.elapsed().as_secs_f32()
));
return Ok(());
}
// The engine process stays up when its load fails; the operation record says so. Do not wait
// out the timeout for a load that has already been refused.
if let Some((operation_id, epoch)) = &operation
&& let Ok((true, text)) = self.cli(&["operation", &id, operation_id, epoch]).await
&& let Some(state) = parse_operation_state(&text)
&& matches!(state, OPERATION_FAILED | OPERATION_INDETERMINATE)
{
return fail(
1,
format!(
"the engine {} the load; the last lines of {}:
{}",
if state == OPERATION_FAILED {
"refused"
} else {
"lost"
},
self.paths.logs().join("engine.log").display(),
tail_of(&self.paths.logs().join("engine.log"), 8)
),
);
}
if started.elapsed() > Duration::from_secs(self.config.load_timeout_s) {
return fail(
1,
format!(
"the model was not ready within {} s; see {}",
self.config.load_timeout_s,
self.paths.logs().join("engine.log").display()
),
);
}
if last_report.elapsed() >= Duration::from_secs(30) {
last_report = Instant::now();
self.log.line(&format!(
"still loading ({:.0}s)",
started.elapsed().as_secs_f32()
));
}
if !self.pause(Duration::from_secs(3)).await {
return Err(Flow::Stopped);
}
}
}
async fn wait_api_ready(&mut self, api: &mut Child) -> Result<(), Flow> {
let started = Instant::now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
}
if let Ok(Some(status)) = api.try_wait() {
return fail(
1,
format!(
"the API exited ({status}); see {}",
self.paths.logs().join("api.log").display()
),
);
}
if let Ok(response) = http::get(
self.api_addr,
"/ready",
Some(&self.api_key),
Duration::from_secs(5),
)
.await
{
if response.status == 200 {
return Ok(());
}
if response.status == 401 || response.status == 403 {
return fail(1, "the API rejected the key in the api-key file");
}
}
if started.elapsed() > Duration::from_secs(180) {
return fail(
1,
"the API was not ready within 180 s after the model loaded",
);
}
if !self.pause(Duration::from_secs(1)).await {
return Err(Flow::Stopped);
}
}
}
/// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one).
fn answer(
&self,
id: &str,
state: reconfigure::State,
message: impl Into<String>,
persisted: bool,
) {
let outcome = reconfigure::Outcome {
id: id.to_owned(),
state,
message: message.into(),
effective: Some(reconfigure::effective(&self.config)),
persisted,
};
if let Err(error) = reconfigure::write_outcome(&self.paths, &outcome) {
self.log
.line(&format!("reconfigure: cannot write the answer: {error}"));
}
}
/// What the host offers now, for the resource planner.
fn host_facts(&self) -> crate::facts::Facts {
crate::facts::probe(&crate::facts::ProbeRequest {
dirs: Vec::new(),
ports: Vec::new(),
binary_dir: None,
binaries: Vec::new(),
extra_library_dirs: Vec::new(),
})
}
/// Stop the API process and start it again (its configuration changed). The port stays the same.
async fn restart_api(&mut self, api: &mut Child) -> Result<(), Flow> {
self.kill_children(&mut [Some(&mut *api)]).await;
let args = vec![
"serve".to_owned(),
"--config".to_owned(),
self.paths.strata_config().display().to_string(),
];
*api = self.spawn(
"api",
&self.paths.bin("strata-next"),
&args,
&BTreeMap::new(),
None,
)?;
self.pids[2] = api.id();
self.wait_api_ready(api).await
}
/// A `leleka reconfigure` request.
///
/// Settings alone were applied to the live engine by the CLI; only the configuration in force is updated (and written when
/// asked). A budget or preset change restarts the engine process, and only that: the sealed archive descriptor this
/// process holds goes to the new engine, the gateway and the API keep their processes and ports. The planner checks the
/// request twice, first without disturbing the service (only what is impossible even with the engine gone is refused), then
/// with the engine stopped and the real free memory of the host. Whatever goes wrong after the stop, the previous settings
/// are started again. `Err` only when no engine can be started at all.
async fn reconfigure(
&mut self,
request: reconfigure::Request,
engine: &mut Child,
gateway: &mut Child,
api: &mut Child,
) -> Result<(), Flow> {
let id = request.id.clone();
self.log.line(&format!(
"reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}",
request.gpu_budget_gib,
request.preset.map(|p| p.as_str()),
serde_json::Value::Object(request.settings.clone()),
request.persist
));
if !request.needs_restart() {
let mut next = self.config.clone();
match reconfigure::record_settings(&mut next, &request.settings) {
Err(why) => self.answer(&id, reconfigure::State::Refused, why, false),
Ok(changed) => {
self.config = next;
let (persisted, note) = if request.persist {
match reconfigure::persist(&self.paths, &self.config) {
Ok(()) => (true, "written to leleka.json".to_owned()),
Err(why) => (false, format!("not persisted: {why}")),
}
} else {
(false, "in force until the service restarts".to_owned())
};
self.answer(
&id,
reconfigure::State::Done,
format!("recorded {changed:?}; {note}"),
persisted,
);
}
}
return Ok(());
}
let resident = self.archive.is_some();
let facts = self.host_facts();
match reconfigure::plan(
&self.config,
&request,
&reconfigure::optimistic(&facts),
resident,
) {
Err(why) => {
self.log.line(&format!(
"reconfigure {id} refused before any change: {why}"
));
self.answer(
&id,
reconfigure::State::Refused,
format!("{why}; nothing was changed"),
false,
);
return Ok(());
}
Ok(planned) if planned.unchanged => {
self.answer(
&id,
reconfigure::State::Done,
"the engine already runs with these settings",
false,
);
return Ok(());
}
Ok(_) => {}
}
self.answer(
&id,
reconfigure::State::Running,
"stopping the engine",
false,
);
self.set_phase(
Phase::EngineRestarting,
"reconfiguring: restarting the engine",
);
self.log.line(
"reconfigure: stopping the engine (the sealed archive stays with the supervisor)",
);
self.kill_children(&mut [Some(&mut *engine)]).await;
self.pids[0] = None;
// The memory of the card returns when the process is gone; give the driver a moment before asking what is free.
let mut verdict = Err(String::new());
for attempt in 0..10 {
if !self.pause(Duration::from_secs(1)).await {
return Err(Flow::Stopped);
}
verdict = reconfigure::plan(&self.config, &request, &self.host_facts(), resident);
let waiting_for_vram = matches!(&verdict, Err(why) if why.starts_with("GPU memory"));
if !waiting_for_vram || attempt == 9 {
break;
}
}
let previous = self.config.clone();
let refusal = match verdict {
Ok(planned) => {
self.config = planned.config;
self.log.line(&format!(
"reconfigure: starting the engine with {}",
reconfigure::effective(&self.config)
));
match self.start_engine(gateway).await {
Ok(child) => {
*engine = child;
let mut persisted = false;
let mut note = "in force until the service restarts".to_owned();
if request.persist {
match reconfigure::persist(&self.paths, &self.config) {
Ok(()) => {
persisted = true;
note = "written to leleka.json".to_owned();
// the API advertises the context of strata.json: follow it
if self.config.profile.context_tokens
!= previous.profile.context_tokens
{
self.restart_api(api).await?;
}
}
Err(why) => note = format!("not persisted: {why}"),
}
}
self.set_phase(Phase::Ready, "ready (engine reconfigured)");
self.log.line("reconfigure: done");
self.answer(
&id,
reconfigure::State::Done,
format!("the engine runs with the new settings; {note}"),
persisted,
);
return Ok(());
}
Err(Flow::Stopped) => return Err(Flow::Stopped),
Err(Flow::Fatal(failure)) => failure.message,
}
}
Err(why) => why,
};
// Refused on the stopped host, or the new engine did not come up: put the previous engine back.
self.config = previous;
self.log.line(&format!(
"reconfigure {id}: {refusal}; restoring the previous settings"
));
let child = match self.start_engine(gateway).await {
Ok(child) => child,
Err(flow) => {
let why = format!("{refusal}; the previous settings could not be restored either");
self.answer(&id, reconfigure::State::Failed, why, false);
return Err(flow);
}
};
*engine = child;
self.set_phase(Phase::Ready, "ready (previous settings restored)");
self.answer(
&id,
reconfigure::State::Refused,
format!("{refusal}; the previous settings are back"),
false,
);
Ok(())
}
/// The engine process is gone (it exited, or `hard_kill` ended it): start it again, waiting longer after each attempt in a
/// row, until it is ready, or give up after `restart.max_engine_restarts` and let the caller end the service (systemd
/// then starts everything afresh). A start that fails (the load is refused, the port is taken) counts as an attempt.
async fn recover_engine(
&mut self,
engine: &mut Child,
gateway: &mut Child,
ready_since: &mut Instant,
reason: String,
) -> Result<(), Flow> {
self.pids[0] = None;
self.restarts_total += 1;
self.last_restart = Some((unix_now(), reason.clone()));
if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) {
self.engine_restarts = 0;
}
loop {
if self.engine_restarts >= self.config.restart.max_engine_restarts {
return fail(
1,
format!(
"the engine failed {} times in a row (last: {reason}); see {}",
self.engine_restarts,
self.paths.logs().join("engine.log").display()
),
);
}
self.engine_restarts += 1;
let wait = self.config.restart.backoff(self.engine_restarts);
self.set_phase(
Phase::EngineRestarting,
&format!(
"restarting the engine (attempt {} of {}, in {} s): {reason}",
self.engine_restarts,
self.config.restart.max_engine_restarts,
wait.as_secs()
),
);
if !self.pause(wait).await {
return Err(Flow::Stopped);
}
match self.start_engine(gateway).await {
Ok(child) => {
*engine = child;
self.set_phase(Phase::Ready, "ready (engine restarted)");
*ready_since = Instant::now();
return Ok(());
}
Err(Flow::Stopped) => return Err(Flow::Stopped),
Err(Flow::Fatal(failure)) => {
self.log.line(&format!(
"the engine did not come back: {}",
failure.message
));
}
}
}
}
/// End a hung engine without ceremony: SIGKILL, and wait for the kernel to reap it (which frees the pinned memory
/// and the VRAM). A process that stays in uninterruptible sleep cannot be removed from here: that ends the service
/// with a message, because only a reboot helps.
async fn hard_kill(&mut self, engine: &mut Child) -> Result<(), Flow> {
let _ = engine.start_kill();
match timeout(Duration::from_secs(60), engine.wait()).await {
Ok(_) => Ok(()),
Err(_) => fail(
1,
"the hung engine does not die after SIGKILL (uninterruptible driver call?); the host needs a reboot",
),
}
}
/// One look at `GET /metrics` (the control plane's own view of the worker and the active request) for the hang detector.
async fn sample_health(&self) -> watchdog::Sample {
match http::get(
self.api_addr,
"/metrics",
Some(&self.api_key),
Duration::from_secs(5),
)
.await
{
Ok(response) if response.status == 200 => watchdog::parse_metrics(&response.body),
Ok(response) => watchdog::Sample::Unreachable(format!("HTTP {}", response.status)),
Err(why) => watchdog::Sample::Unreachable(why),
}
}
fn note_health(&mut self, note: &str) {
if self.health_note != note {
self.health_note = note.to_owned();
self.write_status();
}
}
/// Keep the log directory bounded (`logs.rs`).
fn enforce_logs(&self) {
let policy = logs::Policy {
limit: self
.config
.logs
.limit_mib
.saturating_mul(1 << 20)
.max(1 << 20),
keep: self.config.logs.keep,
};
for (path, outcome) in logs::enforce(&self.paths.logs(), policy) {
match outcome {
Ok(true) => self.log.event(
leleka_obs::Level::Info,
"log_rotated",
&[("file", path.display().to_string().as_str().into())],
),
Ok(false) => {}
Err(error) => self
.log
.line(&format!("cannot rotate {}: {error}", path.display())),
}
}
}
/// SIGINT (graceful for all three programs), then SIGKILL after the grace period.
async fn kill_children(&self, children: &mut [Option<&mut Child>]) {
for child in children.iter_mut().flatten() {
let grace = Duration::from_secs(self.config.shutdown_grace_s + 20);
interrupt(child);
if timeout(grace, child.wait()).await.is_err() {
self.log.line("a child ignored SIGINT; killing it");
let _ = child.start_kill();
let _ = child.wait().await;
}
}
}
}
#[cfg(target_os = "linux")]
fn interrupt(child: &Child) {
if let Some(pid) = child
.id()
.and_then(|pid| i32::try_from(pid).ok())
.and_then(rustix::process::Pid::from_raw)
{
let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT);
}
}
#[cfg(windows)]
fn interrupt(child: &Child) {
// The child leads its own process group (`own_group`), so its pid is the group id Ctrl-Break is aimed at.
if let Some(pid) = child.id() {
let _ = crate::winsys::send_ctrl_break(pid);
}
}
#[cfg(not(any(target_os = "linux", windows)))]
fn interrupt(_child: &Child) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utc_formatting() {
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
assert_eq!(format_utc(1_760_700_000), "2025-10-17T11:20:00Z");
assert_eq!(format_utc(951_782_400), "2000-02-29T00:00:00Z");
}
#[test]
fn status_parsing_matches_the_gateway_document() {
let text = r#"{"schema_version":1,"runtimes":[{"id":"qwen-iq3","connected":true,"epoch":"e","loaded_handle":null,"model_ready":false,"configuration_action_required":false}]}"#;
assert_eq!(parse_runtime_status(text, "qwen-iq3"), Some((true, false)));
assert_eq!(parse_runtime_status(text, "other"), None);
assert_eq!(parse_runtime_status("not json", "qwen-iq3"), None);
let ready = text.replace("\"model_ready\":false", "\"model_ready\":true");
assert_eq!(parse_runtime_status(&ready, "qwen-iq3"), Some((true, true)));
}
#[test]
fn operation_records_are_parsed_from_the_cli_output() {
let load = "{\"operation_id\":\"0f0e\",\"epoch\":\"ab\",\"model\":\"qwen-iq3\"}
{
\"state\": 1
}
";
assert_eq!(parse_operation(load), Some(("0f0e".into(), "ab".into())));
assert_eq!(parse_operation("nothing"), None);
assert_eq!(
parse_operation_state(
"{
\"state\": 3,
\"reason\": \"load_failed\"
}"
),
Some(3)
);
assert_eq!(parse_operation_state("Error: x"), None);
let dir = std::env::temp_dir().join(format!("leleka-tail-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("e.log"),
"a
b
c
d
",
)
.unwrap();
assert_eq!(
tail_of(&dir.join("e.log"), 2),
"c
d"
);
assert_eq!(tail_of(&dir.join("missing.log"), 2), "");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn token_rule() {
assert!(valid_token(&"a".repeat(32)));
assert!(!valid_token(&"a".repeat(31)) && !valid_token(&format!("{} b", "a".repeat(40))));
}
#[test]
fn log_rotation_keeps_one_generation() {
let dir = std::env::temp_dir().join(format!("leleka-rot-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("engine.log");
std::fs::write(&log, vec![b'x'; 100]).unwrap();
assert!(!rotate_log(&log, 1000).unwrap());
assert!(rotate_log(&log, 50).unwrap());
assert!(!log.exists() && dir.join("engine.log.1").exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn private_files_are_written_atomically_with_mode_0600() {
let dir = std::env::temp_dir().join(format!("leleka-priv-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("status.json");
write_private(&file, "one").unwrap();
write_private(&file, "two").unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "two");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
0o600
);
}
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
std::fs::remove_dir_all(dir).unwrap();
}
}