From ef57a6f7011db1839b5fb1c79402959d7e71ff0f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:18:31 +0100 Subject: [PATCH 01/10] telemetry: poll nvidia-smi when NVML cannot be loaded (WSL, containers); GPU temperature and board name; request progress in the document leleka-memory::smi parses nvidia-smi CSV (placeholders, several rows, names with commas) and runs it rate-limited with a kill timeout; the serve stack falls back to it when libnvidia-ml does not load. Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/src/nvml.rs | 28 ++- crates/leleka-memory/src/lib.rs | 1 + crates/leleka-memory/src/smi.rs | 215 ++++++++++++++++++ crates/leleka-memory/src/telemetry.rs | 47 +++- .../src/backend_original_serve.rs | 40 ++-- 5 files changed, 310 insertions(+), 21 deletions(-) create mode 100644 crates/leleka-memory/src/smi.rs diff --git a/crates/cuda-driver/src/nvml.rs b/crates/cuda-driver/src/nvml.rs index ccc98210..f1c3f91c 100644 --- a/crates/cuda-driver/src/nvml.rs +++ b/crates/cuda-driver/src/nvml.rs @@ -1,6 +1,6 @@ //! GPU load for the operator (`leleka status`): utilisation, VRAM, power and clock through NVML, loaded with `dlopen` //! so a host without the library simply reports nothing. Read-only queries; nothing here touches a CUDA context. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct NvmlSample { pub index: u32, pub util_pct: u32, @@ -9,6 +9,8 @@ pub struct NvmlSample { pub vram_total_mib: u64, pub power_w: Option, pub sm_clock_mhz: Option, + pub temp_c: Option, + pub name: Option, } /// A reusable handle to NVML's device `index`; `None` when the library, the symbols or the device are missing. @@ -48,7 +50,10 @@ mod imp { type GetMemory = unsafe extern "C" fn(*mut c_void, *mut MemoryInfo) -> c_int; type GetPower = unsafe extern "C" fn(*mut c_void, *mut c_uint) -> c_int; type GetClock = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int; + type GetTemperature = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int; + type GetName = unsafe extern "C" fn(*mut c_void, *mut std::ffi::c_char, c_uint) -> c_int; const NVML_CLOCK_SM: c_uint = 1; + const NVML_TEMPERATURE_GPU: c_uint = 0; pub(super) struct Handle { library: *mut c_void, @@ -58,6 +63,8 @@ mod imp { memory: GetMemory, power: Option, clock: Option, + temperature: Option, + name: Option, } // SAFETY: NVML's query functions are thread-safe after nvmlInit; the handle is plain data and the library stays loaded. @@ -93,6 +100,8 @@ mod imp { let memory: GetMemory = std::mem::transmute(symbol(library, c"nvmlDeviceGetMemoryInfo")?); let power = symbol(library, c"nvmlDeviceGetPowerUsage").map(|p| std::mem::transmute::<*mut c_void, GetPower>(p)); let clock = symbol(library, c"nvmlDeviceGetClockInfo").map(|p| std::mem::transmute::<*mut c_void, GetClock>(p)); + let temperature = symbol(library, c"nvmlDeviceGetTemperature").map(|p| std::mem::transmute::<*mut c_void, GetTemperature>(p)); + let get_name = symbol(library, c"nvmlDeviceGetName").map(|p| std::mem::transmute::<*mut c_void, GetName>(p)); if init() != 0 { return None; } @@ -100,7 +109,15 @@ mod imp { if get_handle(index, &mut device) != 0 || device.is_null() { return None; } - Some(Handle { library, device, index, utilization, memory, power, clock }) + // The board name does not change: read it once. + let name = get_name.and_then(|f| { + let mut buffer = [0 as std::ffi::c_char; 96]; + // SAFETY: a valid device handle and a buffer of the length passed. + (f(device, buffer.as_mut_ptr(), buffer.len() as c_uint) == 0) + .then(|| std::ffi::CStr::from_ptr(buffer.as_ptr()).to_string_lossy().into_owned()) + .filter(|name| !name.is_empty()) + }); + Some(Handle { library, device, index, utilization, memory, power, clock, temperature, name }) } })(); if built.is_none() { @@ -130,6 +147,11 @@ mod imp { // SAFETY: as above. (unsafe { f(self.device, NVML_CLOCK_SM, &mut mhz) } == 0).then_some(mhz) }); + let temp_c = self.temperature.and_then(|f| { + let mut degrees: c_uint = 0; + // SAFETY: as above. + (unsafe { f(self.device, NVML_TEMPERATURE_GPU, &mut degrees) } == 0).then_some(degrees) + }); Some(NvmlSample { index: self.index, util_pct: utilization.gpu, @@ -138,6 +160,8 @@ mod imp { vram_total_mib: memory.total >> 20, power_w, sm_clock_mhz, + temp_c, + name: self.name.clone(), }) } } diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index 47e929d7..776d9e10 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -15,6 +15,7 @@ pub mod lock; pub mod plan; pub mod pressure; pub mod procfs; +pub mod smi; pub mod telemetry; pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report}; diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs new file mode 100644 index 00000000..d77d5e0d --- /dev/null +++ b/crates/leleka-memory/src/smi.rs @@ -0,0 +1,215 @@ +//! GPU telemetry through `nvidia-smi`, for hosts where NVML (`libnvidia-ml`) cannot be loaded from inside the process: +//! WSL2 (the driver lives on the Windows side and `nvidia-smi` is a shim under `/usr/lib/wsl/lib`), containers that +//! mount the device nodes but not the management library, and drivers whose library the loader does not find. +//! +//! The probe runs `nvidia-smi --query-gpu=... --format=csv,noheader,nounits -i N` at most once per [`MIN_INTERVAL`] +//! (the sampler asks once a second, a process start is cheap but not free) and kills a run that takes longer than +//! [`RUN_LIMIT`]. The parser is a pure function over the CSV text and is unit-tested on real output samples, including +//! the `[N/A]` and `[Not Supported]` placeholders. +use crate::telemetry::GpuSample; +use std::{ + io::Read, + process::{Command, Stdio}, + sync::Mutex, + time::{Duration, Instant}, +}; + +/// The `--query-gpu` fields, in the order [`parse_csv`] reads them. +pub const QUERY: &str = "index,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw,clocks.sm,temperature.gpu,name"; +/// A new process at most this often; the sample in between is the previous one. +pub const MIN_INTERVAL: Duration = Duration::from_secs(2); +/// A `nvidia-smi` that has not answered by now is killed (a wedged driver can block it for a long time). +pub const RUN_LIMIT: Duration = Duration::from_secs(5); + +/// Where `nvidia-smi` is looked for besides `PATH`: the WSL2 shim and the usual package locations. +const EXTRA_LOCATIONS: [&str; 3] = ["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"]; + +/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and anything else. +fn number(field: &str) -> Option { + let field = field.trim(); + if field.is_empty() || field.starts_with('[') || field.eq_ignore_ascii_case("n/a") { + return None; + } + field.parse::().ok().filter(|v| v.is_finite() && *v >= 0.0) +} + +/// Parse the CSV `nvidia-smi` printed for [`QUERY`] (`--format=csv,noheader,nounits`) and return device `index`. +/// +/// Memory is the one required figure: without used and total VRAM the row is useless and the answer is `None`. +/// Utilisation, power, clock and temperature are optional (a laptop GPU often reports `[N/A]` for power). +pub fn parse_csv(text: &str, index: u32) -> Option { + for line in text.lines() { + let fields: Vec<&str> = line.split(',').map(str::trim).collect(); + if fields.len() < 9 || fields[0].parse::().ok() != Some(index) { + continue; + } + let used = number(fields[3])?; + let total = number(fields[4])?; + if total <= 0.0 || used > total * 1.01 { + return None; + } + // The name is the last field and may itself contain commas on some boards: rejoin whatever is left. + let name = fields[8..].join(", "); + return Some(GpuSample { + index, + util_pct: number(fields[1]).map_or(0, |v| v.round() as u32), + mem_util_pct: number(fields[2]).map_or(0, |v| v.round() as u32), + vram_used_mib: used.round() as u64, + vram_total_mib: total.round() as u64, + power_w: number(fields[5]), + sm_clock_mhz: number(fields[6]).map(|v| v.round() as u32), + temp_c: number(fields[7]).map(|v| v.round() as u32), + name: (!name.is_empty() && !name.starts_with('[')).then_some(name), + }); + } + None +} + +/// The first existing `nvidia-smi` in `PATH`, then in [`EXTRA_LOCATIONS`]. +pub fn find_binary() -> Option { + let from_path = std::env::var_os("PATH").and_then(|paths| { + std::env::split_paths(&paths).map(|dir| dir.join("nvidia-smi")).find(|candidate| candidate.is_file()) + }); + from_path.or_else(|| EXTRA_LOCATIONS.iter().map(std::path::PathBuf::from).find(|candidate| candidate.is_file())) +} + +/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed out or +/// printed something unusable. +pub fn query(binary: &std::path::Path, index: u32) -> Option { + let mut child = Command::new(binary) + .arg(format!("--query-gpu={QUERY}")) + .arg("--format=csv,noheader,nounits") + .arg("-i") + .arg(index.to_string()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let mut stdout = child.stdout.take()?; + let started = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => { + if !status.success() { + return None; + } + let mut text = String::new(); + stdout.by_ref().take(64 * 1024).read_to_string(&mut text).ok()?; + return parse_csv(&text, index); + } + Ok(None) if started.elapsed() < RUN_LIMIT => std::thread::sleep(Duration::from_millis(10)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } +} + +/// A rate-limited probe for the telemetry sampler: `None` when no `nvidia-smi` exists on this host. +pub fn probe(index: u32) -> Option Option + Send + Sync>> { + Some(probe_with(find_binary()?, index)) +} + +/// [`probe`] over a given binary. +pub fn probe_with(binary: std::path::PathBuf, index: u32) -> Box Option + Send + Sync> { + let last: Mutex)>> = Mutex::new(None); + Box::new(move || { + let mut last = last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some((at, sample)) = last.as_ref() { + if at.elapsed() < MIN_INTERVAL { + return sample.clone(); + } + } + let sample = query(&binary, index); + *last = Some((Instant::now(), sample.clone())); + sample + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_desktop_board_parses_with_all_fields() { + let text = "0, 87, 41, 30112, 32607, 478.52, 2842, 63, NVIDIA GeForce RTX 5090\n"; + let sample = parse_csv(text, 0).unwrap(); + assert_eq!((sample.util_pct, sample.mem_util_pct), (87, 41)); + assert_eq!((sample.vram_used_mib, sample.vram_total_mib), (30112, 32607)); + assert_eq!(sample.power_w, Some(478.52)); + assert_eq!((sample.sm_clock_mhz, sample.temp_c), (Some(2842), Some(63))); + assert_eq!(sample.name.as_deref(), Some("NVIDIA GeForce RTX 5090")); + } + + #[test] + fn placeholders_become_missing_values_not_zeros() { + // a laptop board under WSL2: power and clock are not reported + let text = "0, 3, 1, 1420, 16384, [N/A], [Not Supported], 47, NVIDIA GeForce RTX 3080 Laptop GPU\n"; + let sample = parse_csv(text, 0).unwrap(); + assert_eq!(sample.power_w, None); + assert_eq!(sample.sm_clock_mhz, None); + assert_eq!(sample.temp_c, Some(47)); + assert_eq!(sample.vram_total_mib, 16384); + } + + #[test] + fn the_requested_device_is_picked_from_several_rows() { + let text = "0, 10, 5, 1000, 24576, 100.0, 1500, 40, NVIDIA GeForce RTX 3090\n1, 99, 80, 20000, 32607, 450.1, 2900, 71, NVIDIA GeForce RTX 5090\n"; + assert_eq!(parse_csv(text, 1).unwrap().vram_used_mib, 20000); + assert_eq!(parse_csv(text, 0).unwrap().name.as_deref(), Some("NVIDIA GeForce RTX 3090")); + assert_eq!(parse_csv(text, 2), None); + } + + #[test] + fn a_row_without_memory_or_a_garbled_row_is_refused() { + assert_eq!(parse_csv("0, 1, 1, [N/A], [N/A], 1, 1, 1, X\n", 0), None); + assert_eq!(parse_csv("0, 1, 1, 100\n", 0), None); + assert_eq!(parse_csv("", 0), None); + assert_eq!(parse_csv("No devices were found\n", 0), None); + // used larger than total is a corrupt reading, not a number to publish + assert_eq!(parse_csv("0, 1, 1, 40000, 32607, 1, 1, 1, X\n", 0), None); + // a failure message on the same stream + assert_eq!(parse_csv("Failed to initialize NVML: Driver/library version mismatch\n", 0), None); + } + + #[test] + fn a_name_with_a_comma_is_kept_whole_and_a_placeholder_name_is_dropped() { + let text = "0, 1, 1, 100, 200, 5, 300, 30, Odd Board, Rev B\n"; + assert_eq!(parse_csv(text, 0).unwrap().name.as_deref(), Some("Odd Board, Rev B")); + let text = "0, 1, 1, 100, 200, 5, 300, 30, [N/A]\n"; + assert_eq!(parse_csv(text, 0).unwrap().name, None); + } + + #[cfg(unix)] + #[test] + fn a_stand_in_binary_is_run_parsed_and_rate_limited() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("leleka-smi-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let counter = dir.join("calls"); + let script = dir.join("nvidia-smi"); + // appends to a file on every call so the test can count the processes started + std::fs::write( + &script, + format!("#!/bin/sh\necho x >> {}\necho '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU'\n", counter.display()), + ) + .unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let sample = query(&script, 0).expect("the stand-in answers"); + assert_eq!((sample.util_pct, sample.vram_used_mib), (55, 2048)); + // the sampler's probe starts one process for two asks within the interval + let probe = probe_with(script.clone(), 0); + assert!(probe().is_some() && probe().is_some()); + let calls = std::fs::read_to_string(&counter).unwrap().lines().count(); + assert_eq!(calls, 2, "one direct query plus one probe run"); + // a failing binary yields nothing + let failing = dir.join("failing"); + std::fs::write(&failing, "#!/bin/sh\nexit 9\n").unwrap(); + std::fs::set_permissions(&failing, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(query(&failing, 0), None); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs index 648aa50c..42ba38a9 100644 --- a/crates/leleka-memory/src/telemetry.rs +++ b/crates/leleka-memory/src/telemetry.rs @@ -23,7 +23,7 @@ const USER_HZ: f64 = 100.0; /// Weight of the newest request in the running average of the throughput. const EMA_ALPHA: f64 = 0.3; -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize)] pub struct GpuSample { pub index: u32, /// Percent of the last sample period in which any kernel ran (NVML `utilization.gpu`). @@ -34,6 +34,10 @@ pub struct GpuSample { pub vram_total_mib: u64, pub power_w: Option, pub sm_clock_mhz: Option, + /// Core temperature in degrees Celsius. + pub temp_c: Option, + /// Board name as the driver reports it. + pub name: Option, } type GpuProbe = Box Option + Send + Sync>; @@ -53,6 +57,8 @@ struct State { started: Option, first_token: Option, produced_now: u64, + /// Prompt tokens of the request in flight. + prompt_now: u64, /// Lifetime counters. requests: u64, cache_hit_requests: u64, @@ -108,6 +114,7 @@ pub fn request_started(prompt_tokens: u64) { s.started = Some(Instant::now()); s.first_token = None; s.produced_now = 0; + s.prompt_now = prompt_tokens; s.context_live = prompt_tokens; }); } @@ -274,12 +281,21 @@ struct Context { used_pct: Option, } +/// The request in flight, while there is one. +#[derive(Debug, Serialize)] +struct LiveRequest { + prompt_tokens: u64, + generated_tokens: u64, + elapsed_s: f64, +} + #[derive(Debug, Serialize)] struct Document { version: u32, ts_ms: u64, uptime_s: u64, phase: Phase, + request: Option, gpu: Option, ram: Option, cpu: Option, @@ -329,7 +345,12 @@ fn render(state: &State, measured: &Measured) -> String { ts_ms: measured.now_ms, uptime_s: measured.uptime_s, phase: state.phase, - gpu: measured.gpu, + request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { + prompt_tokens: state.prompt_now, + generated_tokens: state.produced_now, + elapsed_s: (started.elapsed().as_secs_f64() * 10.0).round() / 10.0, + }), + gpu: measured.gpu.clone(), ram, cpu: measured.cpu.map(|(process, system)| Cpu { cores: measured.cores, @@ -439,7 +460,7 @@ mod tests { Measured { now_ms: 1, uptime_s: 5, - gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900) }), + gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()) }), meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"), cores: 32, @@ -488,10 +509,30 @@ mod tests { assert_eq!(doc["context"]["live_tokens"], 101_200); assert_eq!(doc["context"]["max_tokens"], 262_144); assert_eq!(doc["gpu"]["util_pct"], 91); + assert_eq!(doc["gpu"]["temp_c"], 61); + assert_eq!(doc["gpu"]["name"], "NVIDIA GeForce RTX 5090"); + assert!(doc["request"].is_null(), "no request in flight after the last one finished"); assert_eq!(doc["ram"]["total_mib"], 122_880); assert_eq!(doc["cpu"]["process_busy_cores"], 7.4); } + #[test] + fn a_request_in_flight_is_reported_with_its_progress() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + request_started(5_000); + tokens_delivered(3); + tokens_delivered(4); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!(doc["phase"], "decode"); + assert_eq!(doc["request"]["prompt_tokens"], 5_000); + assert_eq!(doc["request"]["generated_tokens"], 7); + assert!(doc["request"]["elapsed_s"].as_f64().unwrap() >= 0.0); + request_aborted(); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(doc["request"].is_null()); + } + #[test] fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() { let _serial = lock(&SERIAL); diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 4b2cf661..eab218cc 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -295,6 +295,29 @@ mod runner { Tokenizer, Usage, Utf8Pending, BACKPRESSURE_TIMEOUT, GENERATION_TIMEOUT, QUEUE, }; use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; + + type GpuProbe = Box Option + Send + Sync>; + + /// The telemetry sampler's view of the GPU: NVML when `libnvidia-ml` loads, otherwise polling `nvidia-smi` (WSL2, containers + /// without the management library), otherwise nothing (the document then has no `gpu` block). + fn gpu_probe(ordinal: u32) -> Option { + match leleka_cuda_driver::nvml::Nvml::open(ordinal) { + Some(nvml) => Some(Box::new(move || { + nvml.sample().map(|s| leleka_memory::telemetry::GpuSample { + index: s.index, + util_pct: s.util_pct, + mem_util_pct: s.mem_util_pct, + vram_used_mib: s.vram_used_mib, + vram_total_mib: s.vram_total_mib, + power_w: s.power_w, + sm_clock_mhz: s.sm_clock_mhz, + temp_c: s.temp_c, + name: s.name, + }) + })), + None => leleka_memory::smi::probe(ordinal), + } + } use crate::qwen_forward::{ contract::Error as ForwardError, original_serve_engine::ServeStop, @@ -644,22 +667,7 @@ mod runner { leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None)); // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); - let _telemetry = leleka_memory::telemetry::start( - leleka_cuda_driver::nvml::Nvml::open(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)).map(|nvml| { - Box::new(move || { - nvml.sample().map(|s| leleka_memory::telemetry::GpuSample { - index: s.index, - util_pct: s.util_pct, - mem_util_pct: s.mem_util_pct, - vram_used_mib: s.vram_used_mib, - vram_total_mib: s.vram_total_mib, - power_w: s.power_w, - sm_clock_mhz: s.sm_clock_mhz, - }) - }) as Box Option + Send + Sync> - }), - Duration::from_secs(1), - ); + let _telemetry = leleka_memory::telemetry::start(gpu_probe(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)), Duration::from_secs(1)); let mut stack = Some(stack); if shared.shutdown.load(Ordering::Acquire) { if let Some(stack) = stack.take() { From 75e7e47dcc075856c9ebed42606ee98b319858f4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:18:32 +0100 Subject: [PATCH 02/10] control-plane: /api/requests monitor, the Python Monitor members of /metrics, Prometheus text exposition Opt-in api_monitor keeps the last 100 requests of the chat, messages and responses dialects; /metrics gains engine, live, requests, totals, hardware, history; ?format=prometheus (or a scraper Accept) renders the same document as gauges and counters. Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/app.rs | 126 ++++- control-plane/src/config.rs | 14 + control-plane/src/hardware_view.rs | 194 +++++++ control-plane/src/lib.rs | 3 + control-plane/src/main.rs | 1 + control-plane/src/memory_view.rs | 20 + control-plane/src/metrics.rs | 247 ++++++++- control-plane/src/prometheus.rs | 237 ++++++++ control-plane/src/request_monitor.rs | 617 +++++++++++++++++++++ control-plane/src/server_api.rs | 25 +- control-plane/src/worker.rs | 2 +- control-plane/tests/backend_worker_http.rs | 168 ++++++ crates/deploy/src/app.rs | 3 +- docs/api-contract.md | 39 ++ 14 files changed, 1669 insertions(+), 27 deletions(-) create mode 100644 control-plane/src/hardware_view.rs create mode 100644 control-plane/src/prometheus.rs create mode 100644 control-plane/src/request_monitor.rs diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 9d1e3610..60d80c3f 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use axum::{ Json, Router, - extract::{DefaultBodyLimit, State}, + extract::{DefaultBodyLimit, RawQuery, State}, http::{HeaderMap, StatusCode}, middleware, response::{IntoResponse, Response}, @@ -47,6 +47,8 @@ pub struct AppState { pub prefix_cache: Arc, /// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory` (`docs/memory-safety.md`). pub memory: Arc, + /// The API request monitor (`api_monitor` in the config; off by default): `GET /api/requests`. + pub monitor: Arc, } impl Default for AppState { @@ -71,6 +73,7 @@ impl Default for AppState { vision: None, prefix_cache: Arc::new(Default::default()), memory: Arc::new(Default::default()), + monitor: Arc::new(Default::default()), } } } @@ -117,9 +120,14 @@ pub fn router(state: AppState) -> Router { .route("/v1/models/{id}", get(crate::models_api::retrieve)) .route( "/v1/responses", - post(responses::create_route).layer(middleware::from_fn_with_state( - state.lifecycle.clone(), - crate::lifecycle::admit, + post(responses::create_route) + .layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )) + .layer(middleware::from_fn_with_state( + state.monitor.clone(), + crate::request_monitor::capture, )), ) .route( @@ -131,9 +139,14 @@ pub fn router(state: AppState) -> Router { ) .route( "/v1/chat/completions", - post(crate::chat::create).layer(middleware::from_fn_with_state( - state.lifecycle.clone(), - crate::lifecycle::admit, + post(crate::chat::create) + .layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )) + .layer(middleware::from_fn_with_state( + state.monitor.clone(), + crate::request_monitor::capture, )), ) .route( @@ -152,8 +165,13 @@ pub fn router(state: AppState) -> Router { state.lifecycle.clone(), crate::lifecycle::admit, )) - .layer(middleware::from_fn(crate::messages::protocol)), + .layer(middleware::from_fn(crate::messages::protocol)) + .layer(middleware::from_fn_with_state( + state.monitor.clone(), + crate::request_monitor::capture, + )), ) + .route("/api/requests", get(crate::server_api::api_requests)) .route("/admin/lifecycle", get(lifecycle_status)) .route( "/v1/responses/{id}", @@ -239,31 +257,105 @@ async fn resume(State(state): State, headers: HeaderMap) -> Response { lifecycle_status(State(state)).await.into_response() } -async fn metrics(State(state): State) -> Json { +/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks +/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12. +async fn metrics(State(state): State, RawQuery(query): RawQuery, headers: HeaderMap) -> Response { + let accept = headers.get(axum::http::header::ACCEPT).and_then(|v| v.to_str().ok()); + let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all")); + let document = metrics_document(&state, all).await; + if crate::prometheus::wanted(query.as_deref(), accept) { + let mut response = crate::prometheus::render(&document).into_response(); + response.headers_mut().insert( + axum::http::header::CONTENT_TYPE, + axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE), + ); + return response; + } + Json(document).into_response() +} + +/// The generations shown by default in `requests` (the Python Monitor shows twelve). +const RECENT_REQUESTS: usize = 12; + +/// The `/metrics` document. `schema_version` stays 1: the members below `generation` are the Python Monitor's +/// (`engine`, `live`, `requests`, `requests_kept`, `totals`, `hardware`, `hardware_static`, `history`, `time`) and were added +/// beside the native ones, which are unchanged. +pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_json::Value { let worker = *state.worker.read().await; let generation = worker.metrics; + let lifecycle = state.lifecycle.snapshot(); let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity); let queue_used = state .generation .as_ref() .map(|sender| sender.max_capacity() - sender.capacity()); - Json(serde_json::json!({ + let memory = state.memory.status(); + let (hardware, hardware_static, telemetry, history) = state.memory.hardware(); + let busy = generation.active_since.is_some(); + let phase = telemetry["phase"].as_str(); + let engine_state = if worker.state != WorkerState::Ready { + serde_json::to_value(worker.state).unwrap_or(serde_json::Value::Null) + } else if busy { + serde_json::json!(if phase == Some("prefill") { "reading" } else { "generating" }) + } else { + serde_json::json!("idle") + }; + let elapsed_ms = generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64); + let live = serde_json::json!({ + "state": engine_state, + "active": busy, + "queued": lifecycle.generation_jobs.saturating_sub(usize::from(busy)), + "phase": if busy { phase.map_or(serde_json::Value::Null, |p| serde_json::json!(p)) } else { serde_json::Value::Null }, + "prompt_tokens": if busy { telemetry["request"]["prompt_tokens"].clone() } else { serde_json::Value::Null }, + "generated": if busy { telemetry["request"]["generated_tokens"].clone() } else { serde_json::Value::Null }, + "elapsed_s": elapsed_ms.map(|ms| (ms as f64 / 100.0).round() / 10.0), + "tok_s": if busy { hardware["tok_s"].clone() } else { serde_json::Value::Null }, + "tok_s_mean": if busy { hardware["tok_s_mean"].clone() } else { serde_json::Value::Null }, + "prefill_tok_s_mean": if busy { hardware["prefill_tok_s_mean"].clone() } else { serde_json::Value::Null }, + "prompt_read": null, "prompt_total": null, "max_tokens": null, "tok_s_window_s": null, + }); + let engine = serde_json::json!({ + "model": state.model, "max_context": worker.max_context.or(worker.known_max_context), + "images": state.vision.is_some(), "version": env!("CARGO_PKG_VERSION"), + "api_monitor": state.monitor.enabled(), + "settings": telemetry["settings"].clone(), + }); + let (requests, requests_kept, totals) = match generation.history { + Some(history) => ( + history.requests((!all_requests).then_some(RECENT_REQUESTS)), + history.kept(), + history.totals(), + ), + None => (Vec::new(), 0, serde_json::Value::Null), + }; + serde_json::json!({ "schema_version": 1, "scope": "control_plane_process", "model": state.model, "worker": worker.state, - "active": generation.active_since.is_some(), - "active_elapsed_ms": generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64), + "up": worker.state == WorkerState::Ready, + "active": busy, + "active_elapsed_ms": elapsed_ms, "queue_capacity": queue_capacity, "queue_used": queue_used, "memory": { - "level": state.memory.status()["gate"]["level"].clone(), + "level": memory["gate"]["level"].clone(), "gate_rejections": state.memory.gate_rejections(), - "available_bytes": state.memory.status()["gate"]["available_bytes"].clone(), + "available_bytes": memory["gate"]["available_bytes"].clone(), }, "generation": generation, "done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms), - })) + "engine": engine, + "live": live, + "requests": requests, + "requests_kept": requests_kept, + "totals": totals, + "hardware": hardware, + "hardware_static": hardware_static, + "history": history, + "telemetry": telemetry, + "time": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()), + }) } async fn ready(State(state): State) -> (StatusCode, Json) { @@ -430,7 +522,7 @@ mod tests { ..Default::default() }; let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap(); - let initial_metrics = metrics(State(state.clone())).await.0; + let initial_metrics = metrics_document(&state, false).await; assert_eq!(initial_metrics["active"], false); assert!(initial_metrics["done_decode_tokens_per_second"].is_null()); let (result, _rx) = tokio::sync::oneshot::channel(); @@ -468,7 +560,7 @@ mod tests { initial_status ); receiver.recv().await.unwrap(); - assert_eq!(metrics(State(state)).await.0["queue_used"], 0); + assert_eq!(metrics_document(&state, false).await["queue_used"], 0); server.abort(); } } diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index f006fee8..f315287c 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -36,6 +36,8 @@ pub struct Config { pub cors_origins: Vec, /// Origins that count as this server's own page (`trusted_origins`; no wildcard). pub trusted_origins: Vec, + /// `api_monitor`: keep the last requests' prompts and answers in memory for `GET /api/requests` (off by default). + pub api_monitor: bool, /// The `sampling` block: defaults for what a request leaves out. pub sampling: leleka_serving_policy::shared::ConfigSampling, /// `reasoning_budget_tokens`: the default thinking budget (0: none). @@ -75,6 +77,7 @@ struct FileConfig { aliases: Option, cors_origins: Option, trusted_origins: Option, + api_monitor: Option, sampling: Option, reasoning_budget_tokens: Option, shared_settings_file: Option, @@ -561,6 +564,7 @@ impl Config { aliases, cors_origins, trusted_origins, + api_monitor: file.api_monitor == Some(true), sampling, reasoning_budget_tokens: file.reasoning_budget_tokens, shared_settings_file, @@ -750,6 +754,7 @@ mod tests { assert_eq!(config.aliases, vec!["gpt-local"]); assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]); assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]); + assert!(!config.api_monitor, "the request monitor is opt-in"); assert_eq!(config.sampling.sampling.top_k, Some(30)); assert_eq!(config.sampling.ignored, vec!["nonsense"]); assert_eq!(config.idle_unload, Some(Duration::from_secs(90))); @@ -768,6 +773,15 @@ mod tests { let _ = fs::remove_dir_all(dir); } + #[test] + fn the_request_monitor_is_enabled_only_by_a_true_boolean() { + let dir = temp("api-monitor"); + assert!(load(&dir, json!({"model": "m", "api_monitor": true})).unwrap().api_monitor); + assert!(!load(&dir, json!({"model": "m", "api_monitor": false})).unwrap().api_monitor); + assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err()); + let _ = fs::remove_dir_all(dir); + } + #[test] fn bad_serving_settings_stop_the_start() { let dir = temp("serving-bad"); diff --git a/control-plane/src/hardware_view.rs b/control-plane/src/hardware_view.rs new file mode 100644 index 00000000..5b3ce37d --- /dev/null +++ b/control-plane/src/hardware_view.rs @@ -0,0 +1,194 @@ +//! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`, `hardware_static`, +//! `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document (`leleka-memory`'s +//! `telemetry.rs`, copied here by the worker on its health tick). +//! +//! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in degrees +//! Celsius, throughput in tokens per second. A figure the engine does not report is absent (never zero). + +use std::{collections::VecDeque, sync::Mutex, time::{Duration, Instant}}; + +use serde_json::{Map, Value, json}; + +/// Seconds of history per series, one sample per second (the Monitor's minute). +pub const HISTORY_SECONDS: usize = 60; +/// Samples closer than this are the same second. +const MIN_GAP: Duration = Duration::from_millis(900); +const MIB: f64 = 1_048_576.0; + +/// The series the Monitor charts, in the Python service's names. +pub const SERIES: [&str; 8] = ["gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "cpu", "ram_used", "tok_s", "prefill_tok_s_mean"]; + +fn number(value: &Value) -> Option { + value.as_f64().filter(|v| v.is_finite()) +} + +fn bytes(mib: &Value) -> Value { + number(mib).map_or(Value::Null, |m| json!((m * MIB).round() as u64)) +} + +/// `hardware`: the latest sample. +/// +/// * `gpu_*`: from `gpu` (utilisation, memory, temperature, power, SM clock) +/// * `cpu` is the whole system's busy percentage, `cpu_process_cores` the cores the engine used +/// * `ram_used` is total minus available, `ram_process_*` the engine's resident and pinned bytes +/// * `tok_s` is the live decode rate of the request in flight, 0.0 while nothing decodes; `tok_s_mean` and +/// `prefill_tok_s_mean` are the running averages of the engine's decode and prefill rates (null until measured) +pub fn hardware_now(document: &Value) -> Value { + let mut now = Map::new(); + let gpu = &document["gpu"]; + if gpu.is_object() { + now.insert("gpu_util".into(), gpu["util_pct"].clone()); + now.insert("gpu_mem_util".into(), gpu["mem_util_pct"].clone()); + now.insert("gpu_mem_used".into(), bytes(&gpu["vram_used_mib"])); + now.insert("gpu_mem_total".into(), bytes(&gpu["vram_total_mib"])); + now.insert("gpu_temp".into(), gpu["temp_c"].clone()); + now.insert("gpu_power".into(), gpu["power_w"].clone()); + now.insert("gpu_sm_clock_mhz".into(), gpu["sm_clock_mhz"].clone()); + } + let ram = &document["ram"]; + if ram.is_object() { + let used = match (number(&ram["total_mib"]), number(&ram["available_mib"])) { + (Some(total), Some(available)) => json!(((total - available).max(0.0) * MIB).round() as u64), + _ => Value::Null, + }; + now.insert("ram_used".into(), used); + now.insert("ram_total".into(), bytes(&ram["total_mib"])); + now.insert("ram_process_rss".into(), bytes(&ram["process_rss_mib"])); + now.insert("ram_process_pinned".into(), bytes(&ram["process_pinned_mib"])); + now.insert("swap_used".into(), bytes(&ram["swap_used_mib"])); + } + let cpu = &document["cpu"]; + if cpu.is_object() { + now.insert("cpu".into(), cpu["system_busy_pct"].clone()); + now.insert("cpu_process_cores".into(), cpu["process_busy_cores"].clone()); + } + let throughput = &document["throughput"]; + if throughput.is_object() { + let decoding = document["phase"] == "decode"; + now.insert("tok_s".into(), if decoding { throughput["decode_tok_s_live"].clone() } else { json!(0.0) }); + now.insert("tok_s_mean".into(), throughput["decode_tok_s_avg"].clone()); + now.insert("prefill_tok_s_mean".into(), throughput["prefill_tok_s_avg"].clone()); + } + Value::Object(now) +} + +/// `hardware_static`: what does not change while the engine runs. +pub fn hardware_static(document: &Value) -> Value { + let gpu = &document["gpu"]; + let cores = &document["cpu"]["cores"]; + json!({ + "gpu_name": gpu["name"].clone(), + "gpu_count": if gpu.is_object() { json!(1) } else { json!(0) }, + "threads": cores.clone(), + }) +} + +/// A minute of the headline series, one sample a second, oldest first. A sample the engine did not report is `null`. +#[derive(Default)] +pub struct Series { + inner: Mutex, +} + +#[derive(Default)] +struct Inner { + last: Option, + rows: std::collections::BTreeMap<&'static str, VecDeque>, +} + +impl Series { + /// Add the sample `now` (the result of [`hardware_now`]) unless the previous one is less than a second old. + pub fn push(&self, now: &Value) { + let Ok(mut inner) = self.inner.lock() else { return }; + let at = Instant::now(); + if inner.last.is_some_and(|last| at.duration_since(last) < MIN_GAP) { + return; + } + inner.last = Some(at); + for key in SERIES { + let row = inner.rows.entry(key).or_default(); + if row.len() == HISTORY_SECONDS { + row.pop_front(); + } + row.push_back(now.get(key).cloned().unwrap_or(Value::Null)); + } + } + + pub fn snapshot(&self) -> Value { + let Ok(inner) = self.inner.lock() else { return json!({}) }; + let mut out = Map::new(); + for (key, row) in &inner.rows { + out.insert((*key).to_owned(), Value::Array(row.iter().cloned().collect())); + } + Value::Object(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn document(phase: &str) -> Value { + json!({ + "version": 1, "phase": phase, + "gpu": {"index": 0, "util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, + "power_w": 480.5, "sm_clock_mhz": 2900, "temp_c": 61, "name": "NVIDIA GeForce RTX 5090"}, + "ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0}, + "cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0}, + "throughput": {"decode_tok_s_live": 128.4, "decode_tok_s_avg": 120.0, "prefill_tok_s_avg": 5050.0}, + }) + } + + #[test] + fn the_python_names_and_units_are_produced() { + let now = hardware_now(&document("decode")); + assert_eq!(now["gpu_util"], 91); + assert_eq!(now["gpu_mem_used"], 30000u64 * 1_048_576); + assert_eq!(now["gpu_mem_total"], 32607u64 * 1_048_576); + assert_eq!(now["gpu_temp"], 61); + assert_eq!(now["gpu_power"], 480.5); + assert_eq!(now["cpu"], 31.0); + assert_eq!(now["ram_used"], (122880u64 - 70000) * 1_048_576); + assert_eq!(now["ram_total"], 122880u64 * 1_048_576); + assert_eq!(now["tok_s"], 128.4); + assert_eq!(now["prefill_tok_s_mean"], 5050.0); + let fixed = hardware_static(&document("decode")); + assert_eq!(fixed["gpu_name"], "NVIDIA GeForce RTX 5090"); + assert_eq!((fixed["gpu_count"].clone(), fixed["threads"].clone()), (json!(1), json!(32))); + } + + #[test] + fn tok_s_is_zero_while_nothing_decodes_and_blocks_are_absent_without_the_device() { + assert_eq!(hardware_now(&document("idle"))["tok_s"], 0.0); + assert_eq!(hardware_now(&document("prefill"))["tok_s"], 0.0); + let mut no_gpu = document("idle"); + no_gpu["gpu"] = Value::Null; + let now = hardware_now(&no_gpu); + assert!(now.get("gpu_util").is_none() && now.get("gpu_mem_used").is_none()); + assert_eq!(hardware_static(&no_gpu)["gpu_count"], 0); + assert_eq!(hardware_now(&Value::Null), json!({})); + } + + #[test] + fn the_series_keeps_a_minute_and_one_sample_per_second() { + let series = Series::default(); + let now = hardware_now(&document("idle")); + series.push(&now); + series.push(&now); // within the same second: dropped + let snapshot = series.snapshot(); + assert_eq!(snapshot["gpu_util"].as_array().unwrap().len(), 1); + // fill past the bound by rewinding the gate between pushes + for _ in 0..HISTORY_SECONDS + 5 { + series.inner.lock().unwrap().last = None; + series.push(&now); + } + let snapshot = series.snapshot(); + for key in SERIES { + assert_eq!(snapshot[key].as_array().unwrap().len(), HISTORY_SECONDS, "{key}"); + } + // a series the engine did not report is null, not zero + assert!(snapshot["gpu_temp"].as_array().unwrap().iter().all(|v| v == 61)); + let bare = Series::default(); + bare.push(&json!({})); + assert!(bare.snapshot()["gpu_util"][0].is_null()); + } +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 921007f7..c06bc262 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -44,7 +44,10 @@ pub mod kar_stream_encode; pub mod kar_writer; pub mod key_init; pub mod lifecycle; +pub mod hardware_view; pub mod metrics; +pub mod prometheus; +pub mod request_monitor; pub mod model; pub mod model_pipeline; pub mod models_api; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index c606e722..a76fead7 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -926,6 +926,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box>, /// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied. telemetry: RwLock>, + /// A minute of the headline telemetry series (`GET /metrics` `history`). + series: crate::hardware_view::Series, gated: AtomicU64, } @@ -49,11 +51,29 @@ impl MemoryView { /// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable). pub fn set_telemetry(&self, document: Option) { let value = document.and_then(|text| serde_json::from_str::(&text).ok()).filter(Value::is_object); + if let Some(value) = &value { + self.series.push(&crate::hardware_view::hardware_now(value)); + } if let Ok(mut latest) = self.telemetry.write() { *latest = value.map(|value| (value, Instant::now())); } } + /// For `GET /metrics`: the fresh telemetry document (or `null`), the Python-named `hardware` and `hardware_static` + /// blocks derived from it, and the series history. + pub fn hardware(&self) -> (Value, Value, Value, Value) { + let document = self.telemetry_status(); + if document.is_null() { + return (Value::Null, json!({}), json!({}), self.series.snapshot()); + } + ( + crate::hardware_view::hardware_now(&document), + crate::hardware_view::hardware_static(&document), + document, + self.series.snapshot(), + ) + } + /// For `GET /v1/status` `machine`: the engine's telemetry with its age; a document older than [`FRESH_FOR`] is `null`. pub fn telemetry_status(&self) -> Value { let Ok(latest) = self.telemetry.read() else { return Value::Null }; diff --git a/control-plane/src/metrics.rs b/control-plane/src/metrics.rs index fc6ca2da..acae8c95 100644 --- a/control-plane/src/metrics.rs +++ b/control-plane/src/metrics.rs @@ -1,12 +1,149 @@ //! Payload-free engine telemetry, scoped to one control-plane process. -use std::time::Instant; +use std::{ + collections::VecDeque, + sync::Mutex, + time::{Instant, SystemTime, UNIX_EPOCH}, +}; use serde::Serialize; +use serde_json::{Value, json}; use crate::wire::{Done, Finish}; +/// How many finished generations `GET /metrics` keeps (the Python service keeps 500 too). +pub const HISTORY_KEPT: usize = 500; + +/// One settled generation, as the Python service's `Service.history` entry (`GET /metrics` `requests`). +#[derive(Clone, Debug)] +struct Finished { + /// Start, seconds since the epoch. + time: f64, + duration_s: f64, + /// `stop`, `length`, `cancel`, `disconnect` or `error` (the attempt ended without a DONE). + finish: &'static str, + prompt_tokens: Option, + reused: Option, + output_tokens: Option, + prompt_ms: Option, + decode_ms: Option, + expert_hits: Option, + expert_lookups: Option, + drafts_offered: Option, + drafts_accepted: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Totals { + requests: u64, + prompt_tokens: u64, + reused: u64, + output_tokens: u64, + prompt_ms: f64, + decode_ms: f64, + drafts_offered: u64, + drafts_accepted: u64, +} + +struct Inner { + kept: VecDeque, + totals: Totals, +} + +/// The last finished generations and the totals since the process started: the `requests`, `requests_kept` and `totals` of +/// `GET /metrics`. Payload-free (counts and timings only). One per process: the worker status is `Copy`, so it holds a +/// `&'static` handle, leaked once by [`History::leak`]. +pub struct History { + since: SystemTime, + inner: Mutex, +} + +fn unix_seconds(at: SystemTime) -> f64 { + at.duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) +} + +fn round(value: f64, digits: i32) -> f64 { + let scale = 10f64.powi(digits); + (value * scale).round() / scale +} + +impl History { + pub fn leak() -> &'static History { + Box::leak(Box::new(History { + since: SystemTime::now(), + inner: Mutex::new(Inner { kept: VecDeque::new(), totals: Totals::default() }), + })) + } + + fn record(&self, entry: Finished) { + let Ok(mut inner) = self.inner.lock() else { return }; + let totals = &mut inner.totals; + totals.requests = totals.requests.saturating_add(1); + totals.prompt_tokens = totals.prompt_tokens.saturating_add(entry.prompt_tokens.unwrap_or(0)); + totals.reused = totals.reused.saturating_add(entry.reused.unwrap_or(0)); + totals.output_tokens = totals.output_tokens.saturating_add(entry.output_tokens.unwrap_or(0)); + totals.prompt_ms = (totals.prompt_ms + entry.prompt_ms.unwrap_or(0.0)).min(f64::MAX); + totals.decode_ms = (totals.decode_ms + entry.decode_ms.unwrap_or(0.0)).min(f64::MAX); + totals.drafts_offered = totals.drafts_offered.saturating_add(entry.drafts_offered.unwrap_or(0)); + totals.drafts_accepted = totals.drafts_accepted.saturating_add(entry.drafts_accepted.unwrap_or(0)); + if inner.kept.len() == HISTORY_KEPT { + inner.kept.pop_front(); + } + inner.kept.push_back(entry); + } + + /// Number of generations kept. + pub fn kept(&self) -> usize { + self.inner.lock().map_or(0, |inner| inner.kept.len()) + } + + /// Newest first, at most `limit` (`None`: all). The members are the Python service's, with `null` where the engine did + /// not say (`reused`, `hit_rate`, the draft counters, the timings of a failed attempt). + pub fn requests(&self, limit: Option) -> Vec { + let Ok(inner) = self.inner.lock() else { return Vec::new() }; + inner + .kept + .iter() + .rev() + .take(limit.unwrap_or(usize::MAX)) + .map(|entry| { + let rate = match (entry.output_tokens, entry.decode_ms) { + (Some(tokens), Some(ms)) if tokens > 0 && ms > 0.0 => token_rate(tokens, ms).map(|r| round(r, 1)), + _ => None, + }; + let hit_rate = match (entry.expert_hits, entry.expert_lookups) { + (Some(hits), Some(lookups)) if lookups > 0 => Some(round(hits as f64 / lookups as f64, 3)), + _ => None, + }; + json!({ + "time": round(entry.time, 3), "duration_s": round(entry.duration_s, 1), "finish": entry.finish, + "prompt_tokens": entry.prompt_tokens, "reused": entry.reused, "output_tokens": entry.output_tokens, + "engine_generated": entry.output_tokens, "prompt_ms": entry.prompt_ms, "decode_ms": entry.decode_ms, + "decode_tok_s": rate, "hit_rate": hit_rate, + "drafts_offered": entry.drafts_offered, "drafts_accepted": entry.drafts_accepted, + }) + }) + .collect() + } + + /// The Python service's `totals`: since the process started, summed over every settled generation. + pub fn totals(&self) -> Value { + let totals = self.inner.lock().map(|inner| inner.totals).unwrap_or_default(); + json!({ + "since": round(unix_seconds(self.since), 3), "requests": totals.requests, "prompt_tokens": totals.prompt_tokens, + "reused": totals.reused, "output_tokens": totals.output_tokens, + "prompt_ms": round(totals.prompt_ms, 1), "decode_ms": round(totals.decode_ms, 1), + "drafts_offered": totals.drafts_offered, "drafts_accepted": totals.drafts_accepted, + }) + } +} + #[derive(Clone, Copy, Default, Serialize)] pub struct GenerationMetrics { + /// Where settled generations are listed for `GET /metrics`; `None` in a bare status (nothing is listed then). + #[serde(skip)] + pub history: Option<&'static History>, + #[serde(skip)] + started_wall: Option, #[serde(skip)] pub active_since: Option, pub started: u64, @@ -41,19 +178,58 @@ pub fn token_rate(tokens: u64, milliseconds: f64) -> Option { } impl GenerationMetrics { + /// Metrics that also list settled generations in a process-wide [`History`]. + pub fn with_history() -> Self { + Self { history: Some(History::leak()), ..Self::default() } + } + + fn settle(&mut self, finish: &'static str, done: Option<&Done>) { + let started = self.started_wall.take(); + let Some(history) = self.history else { return }; + let (now, started) = (SystemTime::now(), started.unwrap_or_else(SystemTime::now)); + history.record(Finished { + time: unix_seconds(started), + duration_s: now.duration_since(started).map_or(0.0, |d| d.as_secs_f64()), + finish, + prompt_tokens: done.map(|d| d.prompt_tokens), + reused: done.and_then(|d| d.reused), + output_tokens: done.map(|d| d.generated), + prompt_ms: done.map(|d| d.prompt_ms), + decode_ms: done.map(|d| d.decode_ms), + expert_hits: done.and_then(|d| d.expert_hits), + expert_lookups: done.and_then(|d| d.expert_lookups), + drafts_offered: done.and_then(|d| d.drafts_offered), + drafts_accepted: done.and_then(|d| d.drafts_accepted), + }); + } + pub fn start(&mut self) { self.started = self.started.saturating_add(1); self.active_since = Some(Instant::now()); + self.started_wall = Some(SystemTime::now()); } pub fn fail(&mut self) { if self.active_since.take().is_some() { self.failed_or_interrupted = self.failed_or_interrupted.saturating_add(1); + self.settle("error", None); } } pub fn finish(&mut self, done: &Done, disconnected: bool) { self.active_since = None; + self.settle( + if disconnected { + "disconnect" + } else { + match done.finish { + Finish::Stop => "stop", + Finish::Length => "length", + Finish::Cancel => "cancel", + } + }, + Some(done), + ); if disconnected || done.finish == Finish::Cancel { self.cancelled = self.cancelled.saturating_add(1); } else { @@ -88,17 +264,19 @@ impl GenerationMetrics { mod tests { use super::*; + fn done(line: &str) -> Done { + let crate::wire::Event::Done(done) = crate::wire::parse_line(line).unwrap().unwrap() else { + panic!() + }; + done + } + #[test] fn unavailable_rates_are_null_and_disconnected_done_is_cancelled() { assert_eq!(token_rate(10, 0.0), None); assert_eq!(token_rate(10, f64::MIN_POSITIVE), None); assert_eq!(token_rate(10, 20.0), Some(500.0)); - let crate::wire::Event::Done(done) = crate::wire::parse_line("DONE 2 3 1.0 4.0 stop") - .unwrap() - .unwrap() - else { - panic!() - }; + let done = done("DONE 2 3 1.0 4.0 stop"); let mut metrics = GenerationMetrics::default(); metrics.start(); metrics.finish(&done, true); @@ -117,4 +295,59 @@ mod tests { Some(500.0) ); } + + #[test] + fn settled_generations_are_listed_newest_first_with_totals() { + let mut metrics = GenerationMetrics::with_history(); + let history = metrics.history.unwrap(); + assert_eq!(history.kept(), 0); + metrics.start(); + metrics.finish(&done("DONE 20 100 250.0 1000.0 length"), false); + metrics.start(); + metrics.finish(&done("DONE 4 50 10.0 40.0 stop"), true); + metrics.start(); + metrics.fail(); + // an attempt that was never started has nothing to settle + metrics.fail(); + assert_eq!(history.kept(), 3); + let listed = history.requests(Some(2)); + assert_eq!(listed.len(), 2); + assert_eq!(listed[0]["finish"], "error"); + assert!(listed[0]["prompt_tokens"].is_null() && listed[0]["decode_tok_s"].is_null()); + assert_eq!(listed[1]["finish"], "disconnect"); + let all = history.requests(None); + assert_eq!(all[2]["finish"], "length"); + assert_eq!(all[2]["prompt_tokens"], 100); + assert_eq!(all[2]["output_tokens"], 20); + assert_eq!(all[2]["decode_tok_s"], 20.0); + assert!(all[2]["hit_rate"].is_null()); + let totals = history.totals(); + assert_eq!(totals["requests"], 3); + assert_eq!(totals["prompt_tokens"], 150); + assert_eq!(totals["output_tokens"], 24); + assert_eq!(totals["decode_ms"], 1040.0); + assert!(totals["since"].as_f64().unwrap() > 1.0e9); + } + + #[test] + fn the_history_is_bounded() { + let mut metrics = GenerationMetrics::with_history(); + for _ in 0..HISTORY_KEPT + 7 { + metrics.start(); + metrics.finish(&done("DONE 1 1 1.0 1.0 stop"), false); + } + let history = metrics.history.unwrap(); + assert_eq!(history.kept(), HISTORY_KEPT); + // the totals still count every request + assert_eq!(history.totals()["requests"], HISTORY_KEPT as u64 + 7); + } + + #[test] + fn a_bare_metrics_value_lists_nothing_and_does_not_fail() { + let mut metrics = GenerationMetrics::default(); + metrics.start(); + metrics.fail(); + assert!(metrics.history.is_none()); + assert_eq!(metrics.failed_or_interrupted, 1); + } } diff --git a/control-plane/src/prometheus.rs b/control-plane/src/prometheus.rs new file mode 100644 index 00000000..057af709 --- /dev/null +++ b/control-plane/src/prometheus.rs @@ -0,0 +1,237 @@ +//! `GET /metrics?format=prometheus` (or an `Accept` that asks for `text/plain` / OpenMetrics): the same document as the JSON +//! `/metrics`, as Prometheus text exposition. A figure the document leaves `null` or does not have is not exposed (Prometheus +//! has no null; a missing series is the honest answer for "not measured"). Counters carry the `_total` suffix and +//! count since the control plane started; everything else is a gauge sampled when the endpoint is read. +//! +//! The table below is the contract: metric name, type, help, where it comes from in the JSON document, and a scale. + +use std::fmt::Write; + +use serde_json::Value; + +pub const CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Counter, + Gauge, +} + +struct Series { + name: &'static str, + kind: Kind, + help: &'static str, + /// JSON pointer into the `/metrics` document. + from: &'static str, + scale: f64, + /// A fixed label, `name="value"` (several series of one metric differ only by it). + label: Option<(&'static str, &'static str)>, +} + +const fn counter(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series { + Series { name, kind: Kind::Counter, help, from, scale, label: None } +} +const fn gauge(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series { + Series { name, kind: Kind::Gauge, help, from, scale, label: None } +} +const fn labelled(name: &'static str, help: &'static str, from: &'static str, label: (&'static str, &'static str)) -> Series { + Series { name, kind: Kind::Gauge, help, from, scale: 1.0, label: Some(label) } +} + +const SERIES: &[Series] = &[ + counter("leleka_generations_started_total", "Generations admitted to the engine.", "/generation/started", 1.0), + counter("leleka_generations_completed_total", "Generations that ended with a DONE other than cancel.", "/generation/completed", 1.0), + counter("leleka_generations_cancelled_total", "Generations cancelled or abandoned by the client.", "/generation/cancelled", 1.0), + counter("leleka_generations_failed_total", "Admitted generations that ended without a DONE.", "/generation/failed_or_interrupted", 1.0), + counter("leleka_prompt_tokens_total", "Prompt tokens of settled generations.", "/totals/prompt_tokens", 1.0), + counter("leleka_prompt_tokens_reused_total", "Prompt tokens served from a cache.", "/totals/reused", 1.0), + counter("leleka_generated_tokens_total", "Tokens generated by settled generations.", "/totals/output_tokens", 1.0), + counter("leleka_prefill_seconds_total", "Engine time spent reading prompts.", "/totals/prompt_ms", 1e-3), + counter("leleka_decode_seconds_total", "Engine time spent generating tokens.", "/totals/decode_ms", 1e-3), + counter("leleka_draft_tokens_offered_total", "Speculative draft tokens offered.", "/totals/drafts_offered", 1.0), + counter("leleka_draft_tokens_accepted_total", "Speculative draft tokens accepted.", "/totals/drafts_accepted", 1.0), + counter("leleka_memory_gate_rejections_total", "Requests refused up front for host memory pressure.", "/memory/gate_rejections", 1.0), + gauge("leleka_up", "1 when the engine is loaded and accepting generations.", "/up", 1.0), + gauge("leleka_generation_active", "1 while a generation runs.", "/live/active", 1.0), + gauge("leleka_generation_elapsed_seconds", "Seconds the running generation has been active.", "/live/elapsed_s", 1.0), + gauge("leleka_requests_queued", "Generations waiting for the engine.", "/live/queued", 1.0), + gauge("leleka_queue_used", "Commands in the bounded generation channel.", "/queue_used", 1.0), + gauge("leleka_queue_capacity", "Capacity of the generation channel.", "/queue_capacity", 1.0), + gauge("leleka_context_max_tokens", "Context window the engine serves, in tokens.", "/engine/max_context", 1.0), + gauge("leleka_context_live_tokens", "Tokens in the session context (prompt plus output).", "/telemetry/context/live_tokens", 1.0), + gauge("leleka_context_used_percent", "Share of the context window in use.", "/telemetry/context/used_pct", 1.0), + gauge("leleka_gpu_utilization_percent", "Share of the last sample period in which a kernel ran.", "/hardware/gpu_util", 1.0), + gauge("leleka_gpu_memory_utilization_percent", "Share of the period the memory interface was busy.", "/hardware/gpu_mem_util", 1.0), + gauge("leleka_gpu_memory_used_bytes", "Device memory in use.", "/hardware/gpu_mem_used", 1.0), + gauge("leleka_gpu_memory_total_bytes", "Device memory installed.", "/hardware/gpu_mem_total", 1.0), + gauge("leleka_gpu_temperature_celsius", "GPU core temperature.", "/hardware/gpu_temp", 1.0), + gauge("leleka_gpu_power_watts", "GPU board power draw.", "/hardware/gpu_power", 1.0), + gauge("leleka_gpu_sm_clock_megahertz", "GPU SM clock.", "/hardware/gpu_sm_clock_mhz", 1.0), + gauge("leleka_host_memory_used_bytes", "Host RAM in use (total minus available).", "/hardware/ram_used", 1.0), + gauge("leleka_host_memory_total_bytes", "Host RAM installed.", "/hardware/ram_total", 1.0), + gauge("leleka_host_swap_used_bytes", "Swap in use.", "/hardware/swap_used", 1.0), + gauge("leleka_engine_resident_bytes", "Resident set of the engine process.", "/hardware/ram_process_rss", 1.0), + gauge("leleka_engine_pinned_bytes", "Page-locked memory of the engine process.", "/hardware/ram_process_pinned", 1.0), + gauge("leleka_host_cpu_busy_percent", "Busy share of all CPUs.", "/hardware/cpu", 1.0), + gauge("leleka_engine_cpu_busy_cores", "CPU cores worth of time the engine used.", "/hardware/cpu_process_cores", 1.0), + labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/hardware/tok_s", ("window", "live")), + labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/telemetry/throughput/decode_tok_s_last", ("window", "last")), + labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/hardware/tok_s_mean", ("window", "average")), + labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/telemetry/throughput/decode_tok_s_lifetime", ("window", "lifetime")), + labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/telemetry/throughput/prefill_tok_s_last", ("window", "last")), + labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/hardware/prefill_tok_s_mean", ("window", "average")), + labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/telemetry/throughput/prefill_tok_s_lifetime", ("window", "lifetime")), + gauge("leleka_prefix_cache_requests", "Requests the prefix cache has seen.", "/telemetry/cache/requests", 1.0), + gauge("leleka_prefix_cache_hit_requests", "Requests that reused a checkpoint.", "/telemetry/cache/hit_requests", 1.0), + gauge("leleka_prefix_cache_hit_ratio", "Share of requests that reused a checkpoint.", "/telemetry/cache/hit_ratio", 1.0), + gauge("leleka_prefix_cache_token_hit_ratio", "Share of prompt tokens served from a checkpoint.", "/telemetry/cache/token_hit_ratio", 1.0), + gauge("leleka_prefix_cache_reused_tokens", "Prompt tokens reused since the engine started.", "/telemetry/cache/reused_tokens", 1.0), +]; + +/// The phase the engine reports, as a one-hot gauge (`idle`, `prefill`, `decode`). +const PHASES: [&str; 3] = ["idle", "prefill", "decode"]; + +fn escape(text: &str) -> String { + text.replace('\\', "\\\\").replace('\n', "\\n").replace('"', "\\\"") +} + +fn format_value(value: f64) -> String { + if value.fract() == 0.0 && value.abs() < 1e15 { + format!("{}", value as i64) + } else { + format!("{value}") + } +} + +/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`. +pub fn render(document: &Value) -> String { + let mut out = String::new(); + let mut described: Vec<&str> = Vec::new(); + for series in SERIES { + let Some(raw) = document.pointer(series.from) else { continue }; + let value = match raw { + Value::Bool(flag) => f64::from(u8::from(*flag)), + other => match other.as_f64() { + Some(number) if number.is_finite() => number * series.scale, + _ => continue, + }, + }; + if !described.contains(&series.name) { + described.push(series.name); + let kind = if series.kind == Kind::Counter { "counter" } else { "gauge" }; + let _ = writeln!(out, "# HELP {} {}", series.name, series.help); + let _ = writeln!(out, "# TYPE {} {kind}", series.name); + } + match series.label { + Some((name, label)) => { + let _ = writeln!(out, "{}{{{name}=\"{label}\"}} {}", series.name, format_value(value)); + } + None => { + let _ = writeln!(out, "{} {}", series.name, format_value(value)); + } + } + } + if let Some(phase) = document.pointer("/telemetry/phase").and_then(Value::as_str) { + let _ = writeln!(out, "# HELP leleka_engine_phase 1 for the phase the engine is in."); + let _ = writeln!(out, "# TYPE leleka_engine_phase gauge"); + for candidate in PHASES { + let _ = writeln!(out, "leleka_engine_phase{{phase=\"{candidate}\"}} {}", u8::from(candidate == phase)); + } + } + let _ = writeln!(out, "# HELP leleka_info The served model."); + let _ = writeln!(out, "# TYPE leleka_info gauge"); + let model = document.get("model").and_then(Value::as_str).unwrap_or(""); + let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model)); + out +} + +/// Whether a request asks for the text exposition: `?format=prometheus` (or `openmetrics`/`text`), or an `Accept` that lists +/// `text/plain` or OpenMetrics (what a Prometheus scraper sends) and does not ask for JSON first. +pub fn wanted(query: Option<&str>, accept: Option<&str>) -> bool { + if let Some(query) = query { + for pair in query.split('&') { + if let Some(("format", value)) = pair.split_once('=') { + return matches!(value, "prometheus" | "openmetrics" | "text"); + } + } + } + let Some(accept) = accept else { return false }; + let accept = accept.to_ascii_lowercase(); + let text = accept.find("text/plain").or_else(|| accept.find("openmetrics-text")); + let json = accept.find("application/json"); + match (text, json) { + (Some(text), Some(json)) => text < json, + (Some(_), None) => true, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn document() -> Value { + json!({ + "model": "qwen \"3.8\"", "up": true, "queue_used": 1, "queue_capacity": 64, + "generation": {"started": 5, "completed": 3, "cancelled": 1, "failed_or_interrupted": 1}, + "totals": {"prompt_tokens": 1000, "reused": 400, "output_tokens": 250, "prompt_ms": 2500.0, "decode_ms": 1250.0, "drafts_offered": 90, "drafts_accepted": 60}, + "memory": {"gate_rejections": 2}, + "live": {"active": true, "elapsed_s": 3.5, "queued": 0}, + "engine": {"max_context": 262144}, + "hardware": {"gpu_util": 91, "gpu_mem_used": 31457280000u64, "gpu_temp": 61, "gpu_power": 480.5, "cpu": 31.0, "tok_s": 128.4, "tok_s_mean": 120.0, "prefill_tok_s_mean": 5050.0, "ram_used": 5.0e10}, + "telemetry": {"phase": "decode", "context": {"live_tokens": 101200, "used_pct": 38.6}, + "throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_lifetime": null}, + "cache": {"requests": 2, "hit_ratio": 0.5}}, + }) + } + + #[test] + fn counters_gauges_and_labels_render_in_the_text_format() { + let text = render(&document()); + assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n")); + assert!(text.contains("leleka_prefill_seconds_total 2.5\n")); + assert!(text.contains("leleka_decode_seconds_total 1.25\n")); + assert!(text.contains("leleka_up 1\n") && text.contains("leleka_generation_active 1\n")); + assert!(text.contains("# TYPE leleka_gpu_memory_used_bytes gauge\nleleka_gpu_memory_used_bytes 31457280000\n")); + assert!(text.contains("leleka_gpu_power_watts 480.5\n")); + assert!(text.contains("leleka_context_live_tokens 101200\n")); + // one HELP/TYPE per metric, a series per label value + assert_eq!(text.matches("# TYPE leleka_decode_tokens_per_second").count(), 1); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"live\"} 128.4\n")); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"last\"} 100\n")); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 120\n")); + assert!(text.contains("leleka_engine_phase{phase=\"decode\"} 1\n") && text.contains("leleka_engine_phase{phase=\"idle\"} 0\n")); + assert!(text.contains("leleka_info{model=\"qwen \\\"3.8\\\"\"} 1\n")); + } + + #[test] + fn unmeasured_figures_are_not_exposed() { + let text = render(&document()); + // null in the document: no lifetime decode rate, no GPU clock, no swap + assert!(!text.contains("window=\"lifetime\"")); + assert!(!text.contains("leleka_gpu_sm_clock_megahertz")); + let bare = render(&json!({"model": "m", "up": false})); + assert!(bare.contains("leleka_up 0\n")); + assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase")); + // every line is HELP, TYPE or a sample + for line in text.lines() { + assert!(line.starts_with("# HELP ") || line.starts_with("# TYPE ") || line.starts_with("leleka_"), "{line}"); + } + } + + #[test] + fn the_format_is_chosen_by_query_or_accept() { + assert!(wanted(Some("format=prometheus"), None)); + assert!(wanted(Some("requests=all&format=openmetrics"), None)); + assert!(!wanted(Some("format=json"), Some("text/plain"))); + assert!(!wanted(None, None)); + assert!(!wanted(None, Some("*/*"))); + assert!(!wanted(None, Some("application/json"))); + // what a Prometheus server sends + assert!(wanted(None, Some("application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1"))); + assert!(wanted(None, Some("text/plain"))); + // a browser or SDK that prefers JSON keeps the JSON document + assert!(!wanted(None, Some("application/json, text/plain, */*"))); + } +} diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs new file mode 100644 index 00000000..f453d471 --- /dev/null +++ b/control-plane/src/request_monitor.rs @@ -0,0 +1,617 @@ +//! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the Python +//! service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`, tests in +//! `serve/test_monitor.py`). +//! +//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`, +//! `/v1/responses`) in memory: the request body as pretty JSON, the generated text and reasoning, the usage, the error, the +//! HTTP status and the wall-clock timings. It is off unless the config sets `"api_monitor": true`, because it holds prompts +//! and answers in memory; nothing is written to disk and request headers (credentials) are never captured. Every captured +//! text is bounded to [`CAP`] bytes and says so (`*_truncated`). +//! +//! The capture is a middleware around the three routes: it reads the request body once (bounded by the 16 MiB route limit), +//! hands the same bytes on, and either collects a JSON response or taps an event stream chunk by chunk without delaying it. +//! A stream whose consumer goes away before it ends is recorded as `disconnected`. +//! +//! Differences from the Python monitor, all deliberate: `/v1/responses` is monitored too; `queue_s` and `load_s` are `null` +//! (a request's wait for the engine is not attributed per request here: see `/metrics` `live.queued`); the state is `queued` +//! until the first generated text, then `generating`, then `completed`, `error` or `disconnected`; there is no HTML page. +use std::{ + collections::VecDeque, + pin::Pin, + sync::{Arc, Mutex}, + task::{Context, Poll}, + time::{Instant, SystemTime, UNIX_EPOCH}, +}; + +use axum::{ + body::{Body, Bytes}, + extract::{Request, State}, + http::{HeaderValue, StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use futures_core::Stream; +use serde_json::{Map, Value, json}; + +/// Requests kept. +pub const RETENTION: usize = 100; +/// Bytes kept of each captured text (the request, the output, the reasoning, the response). +pub const CAP: usize = 262_144; +/// Body limit of the generation routes. +const BODY_LIMIT: usize = 16 * 1024 * 1024; +/// A response collected whole (not an event stream) is read up to this size for capture. +const RESPONSE_LIMIT: usize = 64 * 1024 * 1024; +/// A single event line longer than this is dropped from the capture (the stream itself is untouched). +const LINE_LIMIT: usize = 1 << 20; + +#[derive(Debug)] +struct Record { + id: String, + path: String, + model: Value, + started_at: f64, + state: &'static str, + outcome: Option<&'static str>, + stream: bool, + response_format: Value, + input: String, + input_truncated: bool, + output: String, + output_truncated: bool, + reasoning: String, + reasoning_truncated: bool, + first_token_s: Option, + usage: Option, + error: Option, + http_status: Option, + response: Option, + response_truncated: bool, + wallclock_s: Option, + finished_at: Option, + clock: Instant, +} + +fn now_unix() -> f64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) +} + +fn seconds(since: Instant) -> f64 { + (since.elapsed().as_secs_f64() * 1000.0).round() / 1000.0 +} + +/// Append `add` to `target` without exceeding [`CAP`] bytes (cut at a character boundary); true when something was left out. +fn append_clipped(target: &mut String, flag: &mut bool, add: &str) { + let room = CAP.saturating_sub(target.len()); + if add.len() <= room { + target.push_str(add); + return; + } + let mut end = room; + while end > 0 && !add.is_char_boundary(end) { + end -= 1; + } + target.push_str(&add[..end]); + *flag = true; +} + +fn clipped(text: &str) -> (String, bool) { + let mut out = String::new(); + let mut flag = false; + append_clipped(&mut out, &mut flag, text); + (out, flag) +} + +impl Record { + fn first_text(&mut self) { + if self.first_token_s.is_none() { + self.first_token_s = Some(seconds(self.clock)); + self.state = "generating"; + } + } + + fn add_output(&mut self, text: Option<&str>) { + if let Some(text) = text.filter(|t| !t.is_empty()) { + self.first_text(); + append_clipped(&mut self.output, &mut self.output_truncated, text); + } + } + + fn add_reasoning(&mut self, text: Option<&str>) { + if let Some(text) = text.filter(|t| !t.is_empty()) { + self.first_text(); + append_clipped(&mut self.reasoning, &mut self.reasoning_truncated, text); + } + } + + /// One server-sent event (`data:` payload) of any of the three dialects. + fn absorb_event(&mut self, event: &Value) { + if let Some(choices) = event.get("choices").and_then(Value::as_array) { + if let Some(delta) = choices.first().and_then(|choice| choice.get("delta")) { + self.add_output(delta.get("content").and_then(Value::as_str)); + self.add_reasoning(delta.get("reasoning_content").or_else(|| delta.get("reasoning")).and_then(Value::as_str)); + } + if let Some(usage) = event.get("usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + return; + } + match event.get("type").and_then(Value::as_str) { + Some("content_block_delta") => { + let delta = &event["delta"]; + self.add_output(delta.get("text").and_then(Value::as_str)); + self.add_reasoning(delta.get("thinking").and_then(Value::as_str)); + } + Some("message_start") => { + if let Some(usage) = event.pointer("/message/usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + } + Some("message_delta") => { + if let Some(update) = event.get("usage").and_then(Value::as_object) { + let mut merged = self.usage.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); + merged.extend(update.clone()); + self.usage = Some(Value::Object(merged)); + } + } + Some("response.output_text.delta") => self.add_output(event.get("delta").and_then(Value::as_str)), + Some("response.reasoning_text.delta" | "response.reasoning_summary_text.delta") => { + self.add_reasoning(event.get("delta").and_then(Value::as_str)); + } + Some("response.completed" | "response.incomplete") => { + if let Some(usage) = event.pointer("/response/usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + } + Some("response.failed") => { + self.error = Some(event.pointer("/response/error").cloned().unwrap_or_else(|| event.clone())); + } + Some("error") => self.error = Some(event.get("error").cloned().unwrap_or_else(|| event.clone())), + _ => {} + } + } + + /// A response that was sent whole (any dialect). + fn absorb_response(&mut self, body: &Value) { + if let Some(error) = body.get("error").filter(|e| !e.is_null()) { + self.error = Some(error.clone()); + } + if let Some(usage) = body.get("usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + // Chat Completions + if let Some(message) = body.pointer("/choices/0/message") { + self.add_output(message.get("content").and_then(Value::as_str)); + self.add_reasoning(message.get("reasoning_content").or_else(|| message.get("reasoning")).and_then(Value::as_str)); + } + // Messages + if let Some(blocks) = body.get("content").and_then(Value::as_array) { + for block in blocks { + match block.get("type").and_then(Value::as_str) { + Some("text") => self.add_output(block.get("text").and_then(Value::as_str)), + Some("thinking") => self.add_reasoning(block.get("thinking").and_then(Value::as_str)), + _ => {} + } + } + } + // Responses + if let Some(items) = body.get("output").and_then(Value::as_array) { + for item in items { + let parts = item.get("content").and_then(Value::as_array).into_iter().flatten(); + match item.get("type").and_then(Value::as_str) { + Some("message") => { + for part in parts { + if part.get("type").and_then(Value::as_str) == Some("output_text") { + self.add_output(part.get("text").and_then(Value::as_str)); + } + } + } + Some("reasoning") => { + for part in parts.chain(item.get("summary").and_then(Value::as_array).into_iter().flatten()) { + self.add_reasoning(part.get("text").and_then(Value::as_str)); + } + } + _ => {} + } + } + } + if let Ok(pretty) = serde_json::to_string_pretty(body) { + let (text, truncated) = clipped(&pretty); + self.response = Some(text); + self.response_truncated = truncated; + } + } + + fn settle(&mut self, outcome: Option<&'static str>) { + if self.finished_at.is_some() { + return; + } + self.wallclock_s = Some(seconds(self.clock)); + self.finished_at = Some(now_unix()); + if let Some(outcome) = outcome { + self.outcome = Some(outcome); + } + let failed = self.error.is_some() || self.http_status.is_some_and(|status| status >= 400); + self.state = if failed { + "error" + } else if self.outcome == Some("disconnected") { + "disconnected" + } else { + "completed" + }; + } + + /// The summary row (no prompts or answers) or the whole record. + fn render(&self, detail: bool) -> Value { + let mut out = Map::new(); + let mut put = |key: &str, value: Value| { + out.insert(key.to_owned(), value); + }; + put("id", json!(self.id)); + put("path", json!(self.path)); + put("model", self.model.clone()); + put("started_at", json!(self.started_at)); + put("state", json!(self.state)); + put("stream", json!(self.stream)); + put("response_format", self.response_format.clone()); + put("input_truncated", json!(self.input_truncated)); + put("output_truncated", json!(self.output_truncated)); + put("reasoning_truncated", json!(self.reasoning_truncated)); + put("queue_s", Value::Null); + put("load_s", Value::Null); + put("first_token_s", json!(self.first_token_s)); + put("wallclock_s", json!(self.wallclock_s.unwrap_or_else(|| seconds(self.clock)))); + if let Some(status) = self.http_status { + put("http_status", json!(status)); + } + if let Some(at) = self.finished_at { + put("finished_at", json!(at)); + } + if let Some(outcome) = self.outcome { + put("outcome", json!(outcome)); + } + if let Some(usage) = &self.usage { + put("usage", usage.clone()); + } + if let Some(error) = &self.error { + put("error", error.clone()); + } + if self.response.is_some() { + put("response_truncated", json!(self.response_truncated)); + } + if detail { + put("input", json!(self.input)); + put("output", json!(self.output)); + put("reasoning", json!(self.reasoning)); + if let Some(response) = &self.response { + put("response", json!(response)); + } + } + Value::Object(out) + } +} + +type Shared = Arc>; + +/// The monitor: disabled (nothing is kept) or a bounded list of request records. +#[derive(Default)] +pub struct RequestMonitor { + enabled: bool, + records: Mutex>, +} + +impl RequestMonitor { + pub fn new(enabled: bool) -> Self { + Self { enabled, records: Mutex::new(VecDeque::new()) } + } + + pub fn enabled(&self) -> bool { + self.enabled + } + + fn begin(&self, path: &str, body: &[u8]) -> Shared { + let request: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + let raw = if request.is_null() { + String::from_utf8_lossy(body).into_owned() + } else { + serde_json::to_string_pretty(&request).unwrap_or_default() + }; + let (input, input_truncated) = clipped(&raw); + let record = Arc::new(Mutex::new(Record { + id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(), + path: path.to_owned(), + model: request.get("model").filter(|m| m.is_string()).cloned().unwrap_or(Value::Null), + started_at: now_unix(), + state: "queued", + outcome: None, + stream: request.get("stream") == Some(&json!(true)), + response_format: request + .get("response_format") + .and_then(|f| f.get("type")) + .or_else(|| request.pointer("/text/format/type")) + .cloned() + .unwrap_or(Value::Null), + input, + input_truncated, + output: String::new(), + output_truncated: false, + reasoning: String::new(), + reasoning_truncated: false, + first_token_s: None, + usage: None, + error: None, + http_status: None, + response: None, + response_truncated: false, + wallclock_s: None, + finished_at: None, + clock: Instant::now(), + })); + if let Ok(mut records) = self.records.lock() { + if records.len() == RETENTION { + records.pop_front(); + } + records.push_back(record.clone()); + } + record + } + + /// Newest first, without prompts and answers. + pub fn summaries(&self) -> Vec { + let records: Vec = self.records.lock().map(|r| r.iter().rev().cloned().collect()).unwrap_or_default(); + records.iter().filter_map(|record| record.lock().ok().map(|r| r.render(false))).collect() + } + + /// One whole record, `None` once it was evicted (or never existed). + pub fn detail(&self, id: &str) -> Option { + let record = self.records.lock().ok()?.iter().find(|r| r.lock().is_ok_and(|r| r.id == id))?.clone(); + let rendered = record.lock().ok()?.render(true); + Some(rendered) + } +} + +/// An event stream passed through unchanged while its events are read into the record. +struct Tap { + inner: axum::body::BodyDataStream, + record: Shared, + pending: Vec, + done: bool, +} + +impl Tap { + fn absorb(&mut self, chunk: &[u8]) { + self.pending.extend_from_slice(chunk); + let Ok(mut record) = self.record.lock() else { return }; + while let Some(newline) = self.pending.iter().position(|b| *b == b'\n') { + let line: Vec = self.pending.drain(..=newline).collect(); + let line = String::from_utf8_lossy(&line); + let Some(data) = line.trim_end_matches(['\r', '\n']).strip_prefix("data:") else { continue }; + let data = data.trim(); + if data.is_empty() || data == "[DONE]" || data.len() > LINE_LIMIT { + continue; + } + if let Ok(event) = serde_json::from_str::(data) { + record.absorb_event(&event); + } + } + if self.pending.len() > LINE_LIMIT { + self.pending.clear(); + } + } + + fn settle(&mut self, outcome: Option<&'static str>) { + self.done = true; + if let Ok(mut record) = self.record.lock() { + record.settle(outcome); + } + } +} + +impl Stream for Tap { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match Pin::new(&mut self.inner).poll_next(cx) { + Poll::Ready(Some(Ok(chunk))) => { + self.absorb(&chunk); + Poll::Ready(Some(Ok(chunk))) + } + Poll::Ready(Some(Err(error))) => { + self.settle(Some("disconnected")); + Poll::Ready(Some(Err(error))) + } + Poll::Ready(None) => { + self.settle(None); + Poll::Ready(None) + } + Poll::Pending => Poll::Pending, + } + } +} + +impl Drop for Tap { + fn drop(&mut self) { + if !self.done { + // the consumer went away before the stream ended + self.settle(Some("disconnected")); + } + } +} + +fn too_large() -> Response { + let body = json!({"error": {"message": "request body too large", "type": "invalid_request_error"}}); + (StatusCode::PAYLOAD_TOO_LARGE, axum::Json(body)).into_response() +} + +/// Middleware for the generation routes: record the request and its answer when the monitor is on; a no-op otherwise. +pub async fn capture(State(monitor): State>, request: Request, next: Next) -> Response { + if !monitor.enabled { + return next.run(request).await; + } + let path = request.uri().path().to_owned(); + let (parts, body) = request.into_parts(); + let Ok(bytes) = axum::body::to_bytes(body, BODY_LIMIT).await else { + return too_large(); + }; + let record = monitor.begin(&path, &bytes); + let response = next.run(Request::from_parts(parts, Body::from(bytes))).await; + let (mut parts, body) = response.into_parts(); + if let Ok(mut r) = record.lock() { + r.http_status = Some(parts.status.as_u16()); + } + let streaming = parts + .headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("text/event-stream")); + if streaming { + let tap = Tap { inner: body.into_data_stream(), record, pending: Vec::new(), done: false }; + return Response::from_parts(parts, Body::from_stream(tap)); + } + match axum::body::to_bytes(body, RESPONSE_LIMIT).await { + Ok(bytes) => { + if let Ok(mut r) = record.lock() { + if let Ok(value) = serde_json::from_slice::(&bytes) { + r.absorb_response(&value); + } + r.settle(None); + } + if let Ok(length) = HeaderValue::from_str(&bytes.len().to_string()) { + parts.headers.insert(header::CONTENT_LENGTH, length); + } + Response::from_parts(parts, Body::from(bytes)) + } + Err(error) => { + if let Ok(mut r) = record.lock() { + r.settle(Some("disconnected")); + } + crate::elog!("request monitor: could not read a response body: {error}"); + (StatusCode::INTERNAL_SERVER_ERROR, "response body unavailable").into_response() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record() -> Shared { + RequestMonitor::new(true).begin("/v1/chat/completions", br#"{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}"#) + } + + #[test] + fn the_request_is_captured_as_pretty_json_with_its_model_and_stream_flag() { + let monitor = RequestMonitor::new(true); + let shared = monitor.begin("/v1/responses", br#"{"model":"qwen","stream":false,"text":{"format":{"type":"json_object"}},"input":"hi"}"#); + let r = shared.lock().unwrap(); + assert_eq!((r.model.clone(), r.stream, r.state), (json!("qwen"), false, "queued")); + assert_eq!(r.response_format, json!("json_object")); + assert!(r.input.contains("\"input\": \"hi\""), "{}", r.input); + assert_eq!(r.id.len(), 12); + // a body that is not JSON is kept as text + let other = monitor.begin("/v1/responses", b"not json"); + assert_eq!(other.lock().unwrap().input, "not json"); + } + + #[test] + fn chat_anthropic_and_responses_streams_are_read() { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.absorb_event(&json!({"choices": [{"delta": {"content": "Hel"}}]})); + assert_eq!(r.state, "generating"); + assert!(r.first_token_s.is_some()); + r.absorb_event(&json!({"choices": [{"delta": {"content": "lo", "reasoning_content": "think"}}], "usage": {"completion_tokens": 2}})); + r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "!"}})); + r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "+"}})); + r.absorb_event(&json!({"type": "response.output_text.delta", "delta": "?"})); + r.absorb_event(&json!({"type": "response.reasoning_text.delta", "delta": "-"})); + assert_eq!((r.output.as_str(), r.reasoning.as_str()), ("Hello!?", "think+-")); + assert_eq!(r.usage, Some(json!({"completion_tokens": 2}))); + r.absorb_event(&json!({"type": "message_start", "message": {"usage": {"input_tokens": 9, "output_tokens": 1}}})); + r.absorb_event(&json!({"type": "message_delta", "usage": {"output_tokens": 7}})); + assert_eq!(r.usage, Some(json!({"input_tokens": 9, "output_tokens": 7}))); + r.absorb_event(&json!({"type": "response.completed", "response": {"usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}}})); + assert_eq!(r.usage.as_ref().unwrap()["total_tokens"], 7); + r.absorb_event(&json!({"type": "response.failed", "response": {"error": {"message": "boom"}}})); + assert_eq!(r.error, Some(json!({"message": "boom"}))); + r.settle(None); + assert_eq!(r.state, "error"); + } + + #[test] + fn whole_responses_of_the_three_dialects_are_read() { + let chat = json!({"choices": [{"message": {"content": "A", "reasoning_content": "r"}}], "usage": {"completion_tokens": 1}}); + let messages = json!({"type": "message", "content": [{"type": "thinking", "thinking": "t"}, {"type": "text", "text": "B"}], "usage": {"output_tokens": 1}}); + let responses = json!({"object": "response", "output": [ + {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "x"}], "summary": [{"text": "y"}]}, + {"type": "message", "content": [{"type": "output_text", "text": "C"}]}], "usage": {"output_tokens": 3}}); + for (body, output, reasoning) in [(chat, "A", "r"), (messages, "B", "t"), (responses, "C", "xy")] { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.absorb_response(&body); + r.settle(None); + assert_eq!((r.output.as_str(), r.reasoning.as_str(), r.state), (output, reasoning, "completed")); + assert_eq!(serde_json::from_str::(r.response.as_ref().unwrap()).unwrap(), body); + assert!(r.usage.is_some()); + } + } + + #[test] + fn an_http_error_or_a_dropped_stream_is_not_a_success() { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.http_status = Some(429); + r.settle(None); + assert_eq!(r.state, "error"); + let shared = record(); + let mut r = shared.lock().unwrap(); + r.http_status = Some(200); + r.settle(Some("disconnected")); + assert_eq!((r.state, r.outcome), ("disconnected", Some("disconnected"))); + // settling twice keeps the first verdict + r.settle(None); + assert_eq!(r.state, "disconnected"); + } + + #[test] + fn captured_text_is_bounded_and_flagged_at_a_character_boundary() { + let shared = record(); + let mut r = shared.lock().unwrap(); + let big = "é".repeat(CAP); + r.add_output(Some(&big)); + r.add_output(Some("more")); + assert!(r.output.len() <= CAP && r.output_truncated); + assert!(r.output.chars().all(|c| c == 'é')); + let monitor = RequestMonitor::new(true); + let body = format!("{{\"input\":\"{}\"}}", "x".repeat(CAP + 100)); + let huge = monitor.begin("/v1/responses", body.as_bytes()); + let huge = huge.lock().unwrap(); + assert_eq!(huge.input.len(), CAP); + assert!(huge.input_truncated); + } + + #[test] + fn retention_evicts_the_oldest_and_summaries_leave_the_payload_out() { + let monitor = RequestMonitor::new(true); + let first = monitor.begin("/v1/messages", br#"{"messages":[]}"#); + let first_id = first.lock().unwrap().id.clone(); + for _ in 0..RETENTION { + monitor.begin("/v1/messages", br#"{"messages":[]}"#); + } + assert_eq!(monitor.summaries().len(), RETENTION); + assert!(monitor.detail(&first_id).is_none()); + let newest = monitor.summaries().remove(0); + for payload in ["input", "output", "reasoning", "response"] { + assert!(newest.get(payload).is_none(), "{payload}"); + } + let detail = monitor.detail(newest["id"].as_str().unwrap()).unwrap(); + assert!(detail.get("input").is_some() && detail.get("output").is_some()); + assert!(newest["queue_s"].is_null() && newest["load_s"].is_null()); + } + + #[test] + fn a_disabled_monitor_keeps_nothing() { + let monitor = RequestMonitor::default(); + assert!(!monitor.enabled()); + assert!(monitor.summaries().is_empty()); + } +} diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 4d6ccaaf..0ff9d8ea 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -14,7 +14,7 @@ use std::{ use axum::{ Json, body::Bytes, - extract::{Request, State}, + extract::{RawQuery, Request, State}, http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}, middleware::Next, response::{IntoResponse, Response}, @@ -559,6 +559,29 @@ pub async fn v1_reconfigure(State(state): State, headers: HeaderMap, b } } +/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without +/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted. +pub async fn api_requests(State(state): State, RawQuery(query): RawQuery) -> Response { + if !state.monitor.enabled() { + return not_found().await; + } + let id = query.as_deref().and_then(|query| { + query.split('&').find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned())) + }); + if let Some(id) = id { + return match state.monitor.detail(&id) { + Some(record) => reply(StatusCode::OK, record), + None => reply(StatusCode::NOT_FOUND, error_body(None, "request no longer retained")), + }; + } + let worker = *state.worker.read().await; + reply( + StatusCode::OK, + json!({"requests": state.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false, + "loaded": is_loaded(&worker), "auto_load": state.control.is_some()}), + ) +} + /// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`. pub async fn not_found() -> Response { reply(StatusCode::NOT_FOUND, error_body(None, "not found")) diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index c84e941c..7ea36431 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -94,7 +94,7 @@ impl Default for WorkerStatus { max_context: None, known_max_context: None, last_activity: None, - metrics: Default::default(), + metrics: crate::metrics::GenerationMetrics::with_history(), output_cap: None, text_level_engine: false, } diff --git a/control-plane/tests/backend_worker_http.rs b/control-plane/tests/backend_worker_http.rs index 6a3e654b..9b8dc3b1 100644 --- a/control-plane/tests/backend_worker_http.rs +++ b/control-plane/tests/backend_worker_http.rs @@ -111,6 +111,15 @@ impl Stack { } async fn start_with(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig)) -> Self { + Self::start_full(name, tune, false).await + } + + /// The same stack with the API request monitor (`api_monitor`) on. + async fn start_monitored(name: &str) -> Self { + Self::start_full(name, |_| {}, true).await + } + + async fn start_full(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig), monitor: bool) -> Self { let dir = common::scratch(name); let tokenizer = merging_tokenizer(&dir); let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor()); @@ -147,6 +156,7 @@ impl Stack { tokenizer: Some(tokenizer.clone()), generation: Some(requests), control: Some(control), + monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(monitor)), ..Default::default() }; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1502,3 +1512,161 @@ async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() { ); stack.finish().await; } + +/// The telemetry document an engine publishes (`leleka-memory`'s `telemetry.rs`), as the worker copies it into the view. +fn engine_telemetry() -> String { + json!({ + "version": 1, "phase": "idle", "request": null, + "gpu": {"index": 0, "util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, + "power_w": 480.5, "sm_clock_mhz": 2900, "temp_c": 61, "name": "NVIDIA GeForce RTX 5090"}, + "ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0}, + "cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0}, + "throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_avg": 100.0, "decode_tok_s_lifetime": 100.0, "decode_tok_s_live": null, + "prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5050.0, "prefill_tok_s_lifetime": 5000.0}, + "cache": {"requests": 2, "hit_requests": 1, "hit_ratio": 0.5, "prompt_tokens": 201000, "reused_tokens": 80000, "token_hit_ratio": 0.398, "last_prompt_tokens": 101000, "last_reused_tokens": 0}, + "context": {"live_tokens": 101200, "max_tokens": 262144, "used_pct": 38.6}, + "settings": {"context_tokens": 262144}, + }) + .to_string() +} + +#[tokio::test] +async fn the_request_monitor_records_prompts_answers_and_usage_in_the_three_dialects() { + let stack = Stack::start_monitored("bw-monitor").await; + let parse = |body: &str| -> Value { serde_json::from_str(body).unwrap() }; + assert_eq!(parse(&stack.get("/api/requests").await.1)["requests"].as_array().unwrap().len(), 0); + + stack.engine.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0))); + let chat = json!({"model": "fixture", "messages": [{"role": "user", "content": "say hi"}]}); + assert_eq!(stack.post("/v1/chat/completions", &chat).await.0, 200); + stack.engine.push(Script::stop_with(&["str", "eam"], usage(7, 2, 0))); + let streamed = json!({"model": "fixture", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "go"}]}); + assert_eq!(stack.post("/v1/chat/completions", &streamed).await.0, 200); + stack.engine.push(Script::stop_with(&["res", "p"], usage(4, 2, 1))); + assert_eq!(stack.post("/v1/responses", &body(json!({"stream": true}))).await.0, 200); + stack.engine.push(Script::stop_with(&["whole"], usage(4, 1, 0))); + assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200); + // a refused request is recorded as an error with its status, not as a success + let (status, _) = stack.post("/v1/responses", &json!({"model": "fixture", "input": "x", "bogus": 1})).await; + assert!(status >= 400); + + let listed = parse(&stack.get("/api/requests").await.1); + assert_eq!(listed["retention"], 100); + assert_eq!(listed["persistent"], false); + assert_eq!(listed["loaded"], true); + let rows = listed["requests"].as_array().unwrap(); + assert_eq!(rows.len(), 5); + // newest first: the refusal, then the buffered Responses, the streamed Responses, the streamed Chat, the buffered Chat + assert_eq!(rows[0]["state"], "error"); + assert!(rows[0]["http_status"].as_u64().unwrap() >= 400); + let expected = [("/v1/responses", "whole"), ("/v1/responses", "resp"), ("/v1/chat/completions", "stream"), ("/v1/chat/completions", "hello")]; + for (row, (path, output)) in rows[1..].iter().zip(expected) { + assert_eq!(row["path"], path); + assert_eq!(row["state"], "completed", "{row}"); + assert_eq!(row["http_status"], 200); + assert!(row.get("input").is_none() && row.get("output").is_none(), "summaries carry no payload"); + assert!(row["wallclock_s"].as_f64().unwrap() >= row["first_token_s"].as_f64().unwrap()); + let detail = parse(&stack.get(&format!("/api/requests?id={}", row["id"].as_str().unwrap())).await.1); + assert_eq!(detail["output"], output, "{detail}"); + assert!(detail["input"].as_str().unwrap().contains("\"model\": \"fixture\"")); + assert!(detail["usage"].is_object(), "{detail}"); + assert_eq!(detail["model"], "fixture"); + } + let streamed_chat = parse(&stack.get(&format!("/api/requests?id={}", rows[3]["id"].as_str().unwrap())).await.1); + assert_eq!(streamed_chat["stream"], true); + assert!(streamed_chat.get("response").is_none(), "a stream has no single response body"); + let buffered_chat = parse(&stack.get(&format!("/api/requests?id={}", rows[4]["id"].as_str().unwrap())).await.1); + assert_eq!(parse(buffered_chat["response"].as_str().unwrap())["choices"][0]["message"]["content"], "hello"); + assert!(buffered_chat["input"].as_str().unwrap().contains("say hi")); + assert_eq!(stack.get("/api/requests?id=missing").await.0, 404); + stack.finish().await; +} + +#[tokio::test] +async fn the_request_monitor_is_off_by_default_and_keeps_nothing() { + let stack = Stack::start("bw-monitor-off").await; + stack.engine.push(Script::stop_with(&["x"], usage(2, 1, 0))); + assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200); + let (status, text) = stack.get("/api/requests").await; + assert_eq!(status, 404, "{text}"); + assert_eq!(stack.get("/api/requests?id=anything").await.0, 404); + assert!(stack.state.monitor.summaries().is_empty()); + let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap(); + assert_eq!(metrics["engine"]["api_monitor"], false); + stack.finish().await; +} + +#[tokio::test] +async fn metrics_carry_the_python_monitor_members_and_a_prometheus_view() { + let stack = Stack::start("bw-metrics-monitor").await; + stack.state.memory.set_telemetry(Some(engine_telemetry())); + stack.engine.push(Script::stop_with(&["a", "b"], usage(10, 2, 4))); + assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200); + stack.engine.push(Script::stop_with(&["c"], usage(6, 1, 0))); + assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200); + + let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap(); + // the native members are untouched + assert_eq!(metrics["schema_version"], 1); + assert_eq!(metrics["generation"]["completed"], 2); + // the Python Monitor members + assert_eq!(metrics["engine"]["model"], "fixture"); + assert_eq!(metrics["engine"]["max_context"], 262_144); + assert_eq!(metrics["engine"]["images"], false); + assert_eq!(metrics["live"]["state"], "idle"); + assert_eq!(metrics["live"]["queued"], 0); + assert_eq!(metrics["requests_kept"], 2); + let requests = metrics["requests"].as_array().unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!(requests[0]["prompt_tokens"], 6); + assert_eq!(requests[1]["prompt_tokens"], 10); + assert_eq!(requests[1]["reused"], 4); + assert_eq!(requests[1]["output_tokens"], 2); + assert_eq!(requests[1]["finish"], "stop"); + assert_eq!(metrics["totals"]["requests"], 2); + assert_eq!(metrics["totals"]["prompt_tokens"], 16); + assert_eq!(metrics["totals"]["reused"], 4); + assert_eq!(metrics["totals"]["output_tokens"], 3); + assert_eq!(metrics["hardware"]["gpu_util"], 91); + assert_eq!(metrics["hardware"]["gpu_mem_used"], 30000u64 * 1_048_576); + assert_eq!(metrics["hardware"]["gpu_temp"], 61); + assert_eq!(metrics["hardware"]["tok_s"], 0.0); + assert_eq!(metrics["hardware_static"]["gpu_name"], "NVIDIA GeForce RTX 5090"); + assert_eq!(metrics["history"]["gpu_util"].as_array().unwrap().len(), 1); + assert!(metrics["time"].as_f64().unwrap() > 1.0e9); + assert_eq!(metrics["telemetry"]["context"]["max_tokens"], 262_144); + // `?requests=all` lists everything kept (here the same two) + let all: Value = serde_json::from_str(&stack.get("/metrics?requests=all").await.1).unwrap(); + assert_eq!(all["requests"].as_array().unwrap().len(), 2); + + // Prometheus text: by query and by the Accept header a scraper sends + let scrape = |accept: Option<&str>, query: &str| { + let mut request = stack.client.get(format!("{}/metrics{query}", stack.base)); + if let Some(accept) = accept { + request = request.header("accept", accept); + } + request + }; + for (accept, query) in [(None, "?format=prometheus"), (Some("application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1"), "")] { + let response = scrape(accept, query).send().await.unwrap(); + assert_eq!(response.status(), 200); + assert!(response.headers()["content-type"].to_str().unwrap().starts_with("text/plain; version=0.0.4")); + let text = response.text().await.unwrap(); + assert!(text.contains("leleka_generations_completed_total 2\n"), "{text}"); + assert!(text.contains("leleka_prompt_tokens_total 16\n") && text.contains("leleka_prompt_tokens_reused_total 4\n")); + assert!(text.contains("leleka_generated_tokens_total 3\n")); + assert!(text.contains("leleka_up 1\n")); + assert!(text.contains("leleka_gpu_utilization_percent 91\n")); + assert!(text.contains("leleka_gpu_memory_used_bytes 31457280000\n")); + assert!(text.contains("leleka_gpu_temperature_celsius 61\n")); + assert!(text.contains("leleka_host_memory_used_bytes 55448698880\n"), "{text}"); + assert!(text.contains("leleka_context_live_tokens 101200\n") && text.contains("leleka_context_max_tokens 262144\n")); + assert!(text.contains("leleka_prefix_cache_token_hit_ratio 0.398\n")); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 100\n")); + assert!(text.contains("leleka_engine_phase{phase=\"idle\"} 1\n")); + } + // a JSON client keeps getting JSON + let json_reply = scrape(Some("application/json"), "").send().await.unwrap(); + assert_eq!(json_reply.headers()["content-type"], "application/json"); + stack.finish().await; +} diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 7b1c6f42..55918280 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -476,10 +476,11 @@ pub fn render_machine(machine: &Value) -> String { let gpu = &machine["gpu"]; if gpu.is_object() { out.push_str(&format!( - " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}\n", + " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n", gpu["util_pct"], gpu["mem_util_pct"], gib(&gpu["vram_used_mib"]), gib(&gpu["vram_total_mib"]), gpu["power_w"].as_f64().map_or(String::new(), |w| format!(", {w:.0} W")), gpu["sm_clock_mhz"].as_u64().map_or(String::new(), |m| format!(", {m} MHz")), + gpu["temp_c"].as_u64().map_or(String::new(), |t| format!(", {t} C")), )); } let cpu = &machine["cpu"]; diff --git a/docs/api-contract.md b/docs/api-contract.md index 9bca21f5..18c5f7f2 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -301,6 +301,45 @@ Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support observation; paired workload and quality measurements remain necessary for any performance claim. +### Monitor members, Prometheus text and `GET /api/requests` + +`/metrics` also carries the members of the Python service's Monitor (`engine/strata/serve/server.py` `Service.metrics`), added beside the +native ones above, which are unchanged (`schema_version` stays 1): + +| member | content | +| --- | --- | +| `engine` | `model`, `max_context`, `images`, `version`, `api_monitor`, and `settings` (the settings the engine reports: context, prefill chunk, caches, workers) | +| `live` | `state` (`idle`, `reading`, `generating`, or the worker state while it is not ready), `active`, `queued` (generations waiting for the engine), `phase`, `prompt_tokens`, `generated`, `elapsed_s`, `tok_s`, `tok_s_mean`, `prefill_tok_s_mean`; `prompt_read`, `prompt_total`, `max_tokens` and `tok_s_window_s` are `null` (the runtime does not report them) | +| `requests`, `requests_kept` | the last 12 settled generations, newest first (`?requests=all`: every one kept, up to 500): `time`, `duration_s`, `finish` (`stop`, `length`, `cancel`, `disconnect`, `error`), `prompt_tokens`, `reused`, `output_tokens`, `engine_generated`, `prompt_ms`, `decode_ms`, `decode_tok_s`, `hit_rate`, `drafts_offered`, `drafts_accepted`; `null` where the engine did not say or the attempt had no DONE. Counts and timings only, no payload | +| `totals` | since the process started: `requests`, `prompt_tokens`, `reused`, `output_tokens`, `prompt_ms`, `decode_ms`, `drafts_offered`, `drafts_accepted` | +| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and a minute of the headline series, one sample a second. A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) | +| `telemetry`, `time` | the raw telemetry document (the same as `/v1/status` `machine`, without its age) and the wall-clock second | + +The GPU block comes from NVML; where `libnvidia-ml` cannot be loaded (WSL2, containers without the management library) the engine polls +`nvidia-smi --query-gpu=...` instead (at most every 2 s, `leleka-memory/src/smi.rs`), so the block is present on those hosts too. + +**Prometheus.** `GET /metrics?format=prometheus`, or any request whose `Accept` asks for `text/plain` or OpenMetrics before JSON (what a +Prometheus scraper sends), returns the text exposition (`text/plain; version=0.0.4`) of the same document under the same bearer-key rule: +counters `leleka_generations_{started,completed,cancelled,failed}_total`, `leleka_prompt_tokens_total`, +`leleka_prompt_tokens_reused_total`, `leleka_generated_tokens_total`, `leleka_{prefill,decode}_seconds_total`, draft counters, +`leleka_memory_gate_rejections_total`; gauges `leleka_up`, `leleka_generation_active`, `leleka_requests_queued`, `leleka_queue_used`, +`leleka_context_{max,live}_tokens`, `leleka_context_used_percent`, `leleka_gpu_{utilization_percent,memory_used_bytes,memory_total_bytes,temperature_celsius,power_watts,sm_clock_megahertz}`, +`leleka_host_{memory_used_bytes,memory_total_bytes,swap_used_bytes,cpu_busy_percent}`, `leleka_engine_{resident_bytes,pinned_bytes,cpu_busy_cores}`, +`leleka_decode_tokens_per_second{window=live|last|average|lifetime}`, `leleka_prefill_tokens_per_second{window=last|average|lifetime}`, +`leleka_prefix_cache_*`, `leleka_engine_phase{phase=...}` and `leleka_info{model=...}`. Unmeasured figures are not exposed (no zeros for "unknown"). +The table in `control-plane/src/prometheus.rs` is the contract. JSON stays the default for every other client. + +**`GET /api/requests`** is the Python service's opt-in request monitor. It is off unless the config sets `"api_monitor": true` (then +the route answers 404, as the Original's does): it keeps prompts and answers in memory. It records `/v1/chat/completions`, +`/v1/messages` and `/v1/responses` (the Original: the first two), the last 100 of them, bounded to 256 KiB per captured text +(`input_truncated`, `output_truncated`, `reasoning_truncated`, `response_truncated`). Without `id` it lists them newest first without +payload (`{"requests": [...], "retention": 100, "persistent": false, "loaded": ..., "auto_load": ...}`); `?id=ID` returns one whole +record (`input` as pretty JSON, `output`, `reasoning`, `response` of a buffered reply, `usage`, `error`, `http_status`, +`first_token_s`, `wallclock_s`), or 404 `request no longer retained` once evicted. States: `queued` until the first generated text, +`generating`, then `completed`, `error` (an error body or HTTP status >= 400) or `disconnected` (the consumer left before the stream +ended). Headers and API keys are never captured. Differences from the Python monitor: `queue_s` and `load_s` are `null` (the wait for +the engine is not attributed per request; `live.queued` shows the queue), and there is no `/api-monitor` HTML page. + The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open. The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility. From ee1717e2f76c3f6b097a4bdb435d081e8500f969 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:29:39 +0100 Subject: [PATCH 03/10] leleka reconfigure: --persist, and --gpu-budget-gib/--preset by restarting only the engine under the supervisor The CLI hands budget and preset changes to the supervisor through a request file; the supervisor checks them with the resource planner twice (before and after stopping the engine), restarts the engine with the sealed archive descriptor it holds, keeps the gateway and API processes and ports, and restores the previous settings when the planner or the new engine refuses. --persist writes the result into leleka.json (and strata.json for the context). leleka.json now records the profile before the preset changed it so that dedicated undoes workstation. Co-Authored-By: Claude Sonnet 5.5 --- crates/deploy/src/app.rs | 140 +++- crates/deploy/src/bin/fake_runtime.rs | 8 + crates/deploy/src/cli.rs | 100 ++- crates/deploy/src/config.rs | 5 + crates/deploy/src/layout.rs | 8 + crates/deploy/src/lib.rs | 1 + crates/deploy/src/plan.rs | 2 + crates/deploy/src/profile.rs | 25 + crates/deploy/src/reconfigure.rs | 1103 +++++++++++++++++++++++++ crates/deploy/src/supervisor.rs | 174 +++- crates/deploy/tests/e2e.rs | 234 ++++++ docs/deploy.md | 32 +- 12 files changed, 1815 insertions(+), 17 deletions(-) create mode 100644 crates/deploy/src/reconfigure.rs diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 55918280..acdf4bc8 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -1,6 +1,6 @@ //! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`. use crate::{ - cli::{Command, Environment, USAGE, UpOptions, parse}, + cli::{Command, Environment, ReconfigureArgs, USAGE, UpOptions, parse}, plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan}, preflight::Report, profile::{BUILTIN, Profile}, @@ -69,7 +69,7 @@ pub async fn main_with(args: Vec) -> i32 { Command::Up(opts) => up(opts).await, Command::Status(opts) => status(opts).await, Command::Down(opts) => down(opts).await, - Command::Reconfigure(opts, settings) => reconfigure(opts, settings).await, + Command::Reconfigure(opts, args) => reconfigure(opts, args).await, Command::Verify(opts) => verify(opts).await, Command::Run { config, kar_fd } => { supervisor::run(supervisor::Options { config, kar_fd }).await @@ -407,9 +407,18 @@ async fn status(opts: UpOptions) -> i32 { i32::from(!ready) } -/// `leleka reconfigure`: POST the settings to the running gateway (same API key as every request). -async fn reconfigure(opts: UpOptions, settings: String) -> i32 { +/// `leleka reconfigure`. +/// +/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A +/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process. +/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise). +async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 { let paths = opts.dirs.paths(); + let supervised = crate::plan::service_running(&paths); + if args.needs_restart() { + return reconfigure_by_restart(&opts, &args, supervised).await; + } + let settings = serde_json::Value::Object(args.settings.clone()).to_string(); let api = crate::config::RunConfig::read(&paths.run_config()) .map(|config| config.ports.api) .unwrap_or_else(|_| opts.ports.api.clone()); @@ -426,16 +435,29 @@ async fn reconfigure(opts: UpOptions, settings: String) -> i32 { match response { Ok(response) => { let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null); + let mut persisted = None; + if response.status == 200 && args.persist { + persisted = Some(persist_settings(&paths, &args.settings, supervised).await); + } if opts.json { - println!("{}", serde_json::to_string_pretty(&document).unwrap_or(response.body)); + let mut shown = document.clone(); + if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) { + object.insert("persisted".into(), json!(result.is_ok())); + } + println!("{}", serde_json::to_string_pretty(&shown).unwrap_or(response.body)); } else if response.status == 200 { println!("reconfigured; the engine runs with:"); print!("{}", render_settings(&document["settings"])); + match &persisted { + Some(Ok(note)) => println!("persisted: {note}"), + Some(Err(why)) => eprintln!("leleka: the engine runs with the new settings, but they were not persisted: {why}"), + None => {} + } } else { let message = document["error"]["message"].as_str().unwrap_or(&response.body); eprintln!("leleka: the change was refused (HTTP {}): {message}", response.status); } - i32::from(response.status != 200) + i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err())) } Err(message) => { eprintln!("leleka: {message}"); @@ -444,6 +466,112 @@ async fn reconfigure(opts: UpOptions, settings: String) -> i32 { } } +/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine +/// keeps it) and writes the file; with no supervisor the file is edited directly. +async fn persist_settings(paths: &crate::layout::Paths, settings: &serde_json::Map, supervised: bool) -> Result { + if !supervised { + let changed = crate::reconfigure::persist_offline(paths, settings)?; + return Ok(format!("leleka.json updated ({} changed; no supervisor was running)", changed.len())); + } + let request = crate::reconfigure::Request { + id: crate::reconfigure::new_request_id(), + settings: settings.clone(), + persist: true, + ..Default::default() + }; + let outcome = ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?; + if outcome.state == crate::reconfigure::State::Done && outcome.persisted { + Ok(outcome.message) + } else { + Err(outcome.message) + } +} + +/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end). +async fn ask_supervisor( + paths: &crate::layout::Paths, + request: &crate::reconfigure::Request, + limit: std::time::Duration, + show_progress: bool, +) -> Result { + use crate::reconfigure::{State, read_outcome, write_request}; + write_request(paths, request)?; + let started = std::time::Instant::now(); + let mut last = String::new(); + loop { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + match read_outcome(paths, &request.id) { + Some(outcome) if outcome.state != State::Running => return Ok(outcome), + Some(outcome) if show_progress && outcome.message != last => { + eprintln!("leleka: {}", outcome.message); + last = outcome.message; + } + _ => {} + } + if !crate::plan::service_running(paths) { + return Err("the supervisor stopped before it answered; see the service log".into()); + } + if started.elapsed() > limit { + let _ = std::fs::remove_file(paths.reconfigure_request()); + return Err(format!("the supervisor did not answer within {} s", limit.as_secs())); + } + } +} + +/// A budget or preset change: the supervisor restarts the engine process with the new numbers. +async fn reconfigure_by_restart(opts: &UpOptions, args: &ReconfigureArgs, supervised: bool) -> i32 { + let paths = opts.dirs.paths(); + if !supervised { + eprintln!( + "leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`", + paths.dirs.state.display() + ); + return 1; + } + let load_timeout = crate::config::RunConfig::read(&paths.run_config()).map_or(1800, |config| config.load_timeout_s); + let request = crate::reconfigure::Request { + id: crate::reconfigure::new_request_id(), + gpu_budget_gib: args.gpu_budget_gib, + preset: args.preset, + settings: args.settings.clone(), + persist: args.persist, + }; + eprintln!("leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)"); + // two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks + let limit = std::time::Duration::from_secs(2 * load_timeout + 300); + let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await { + Ok(outcome) => outcome, + Err(why) => { + eprintln!("leleka: {why}"); + return 1; + } + }; + let done = outcome.state == crate::reconfigure::State::Done; + if opts.json { + println!("{}", serde_json::to_string_pretty(&outcome).unwrap_or_default()); + } else if done { + println!("reconfigured: {}", outcome.message); + if let Some(effective) = &outcome.effective { + print!("{}", render_effective(effective)); + } + } else { + eprintln!("leleka: the change was not made: {}", outcome.message); + } + i32::from(!done) +} + +/// The numbers in force after a restart-in-place, one line each. +pub fn render_effective(effective: &Value) -> String { + let Some(object) = effective.as_object() else { return String::new() }; + let mut out = String::new(); + for (key, value) in object { + if !value.is_null() { + out.push_str(&format!(" {key:20} {value}\n")); + } + } + out +} + /// The settings block of the engine, one line per member. pub fn render_settings(settings: &Value) -> String { let Some(object) = settings.as_object() else { return String::new() }; diff --git a/crates/deploy/src/bin/fake_runtime.rs b/crates/deploy/src/bin/fake_runtime.rs index e5d82f00..41f9a7f7 100644 --- a/crates/deploy/src/bin/fake_runtime.rs +++ b/crates/deploy/src/bin/fake_runtime.rs @@ -91,6 +91,14 @@ fn engine(fake: &Path, args: &[String]) { eprintln!("fake engine: HF_TOKEN leaked into the engine environment"); std::process::exit(3); } + // `fail-engine-budget` holds a `--gpu-budget` value (bytes) the engine refuses to start with: a new setting that + // does not come up, while the previous one does. + if let (Ok(refused), Some(budget)) = (fs::read_to_string(fake.join("fail-engine-budget")), flag(args, "--gpu-budget")) + && refused.trim() == budget + { + eprintln!("fake engine: refusing a budget of {budget} bytes"); + std::process::exit(9); + } let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned(); if let Some(fd) = flag(args, "--kar-archive-fd") { // The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd. diff --git a/crates/deploy/src/cli.rs b/crates/deploy/src/cli.rs index 9b76cc46..822676ee 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -51,7 +51,7 @@ UP / PREFLIGHT OPTIONS --service-user NAME system unit only: account the service runs as (default leleka, created if missing) RECONFIGURE OPTIONS (any of them; the engine reopens its serve stack in tens of seconds, the weights stay loaded; a refused change -keeps the previous settings; the VRAM budget and the preset need a restart: `leleka up`) +keeps the previous settings) --context-tokens N tokens of context (1..262144) --prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192 --kv-resident N K/V cells kept in VRAM per layer (0 = all, else >= 20480) @@ -61,6 +61,10 @@ keeps the previous settings; the VRAM budget and the preset need a restart: `lel --prefix-retention-min N minutes an idle cached session is kept (0 = no limit) --cpu-workers N CPU expert workers (1..64) --spec-min-p P draft-probability floor (0..1) + --gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the supervisor restarts + the engine process (the model loads again, minutes), the gateway and the API keep their ports + --preset dedicated|workstation resource preset (same restart); refused when the host cannot hold it + --persist keep the change across restarts of the service (writes leleka.json) --assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force ENVIRONMENT @@ -104,6 +108,26 @@ pub struct UpOptions { pub kar_fd: Option, } +/// What `leleka reconfigure` was asked to change. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ReconfigureArgs { + /// Runtime settings (the members of `POST /v1/reconfigure`): the engine reopens its serve stack. + pub settings: serde_json::Map, + /// New VRAM budget: needs a new engine process. + pub gpu_budget_gib: Option, + /// New resource preset: needs a new engine process. + pub preset: Option, + /// Keep the change across restarts of the service (`leleka.json`). + pub persist: bool, +} + +impl ReconfigureArgs { + /// The budget and the preset are fixed when the CUDA context is created. + pub fn needs_restart(&self) -> bool { + self.gpu_budget_gib.is_some() || self.preset.is_some() + } +} + #[derive(Debug)] pub enum Command { Up(UpOptions), @@ -115,8 +139,8 @@ pub enum Command { ExecInherit(Vec), Status(UpOptions), Down(UpOptions), - /// The options locate the running service; the document is the JSON object of settings to change. - Reconfigure(UpOptions, String), + /// The options locate the running service; the arguments are what to change. + Reconfigure(UpOptions, ReconfigureArgs), Verify(UpOptions), Profiles(Option), Version, @@ -377,6 +401,7 @@ const RECONFIGURE_FLAGS: &[(&str, &str)] = &[ fn reconfigure_command(args: &[String], env: &Environment) -> Result { let mut rest: Vec = Vec::new(); let mut document = serde_json::Map::new(); + let mut extra = ReconfigureArgs::default(); let mut index = 0; while index < args.len() { let arg = &args[index]; @@ -384,6 +409,38 @@ fn reconfigure_command(args: &[String], env: &Environment) -> Result (name, Some(value.to_owned())), _ => (arg.as_str(), None), }; + if name == "--persist" { + if inline.is_some() { + return Err("--persist takes no value".into()); + } + extra.persist = true; + index += 1; + continue; + } + if name == "--gpu-budget-gib" || name == "--preset" { + let value = match inline { + Some(value) => value, + None => { + index += 1; + args.get(index).ok_or_else(|| format!("{name} needs a value"))?.clone() + } + }; + if name == "--preset" { + if extra.preset.replace(crate::resources::Preset::parse(&value)?).is_some() { + return Err(format!("{name} given twice")); + } + } else { + let gib: u64 = value.parse().map_err(|_| format!("{name} needs a whole number of GiB"))?; + if !(1..=1024).contains(&gib) { + return Err(format!("{name} must be 1..1024")); + } + if extra.gpu_budget_gib.replace(gib).is_some() { + return Err(format!("{name} given twice")); + } + } + index += 1; + continue; + } if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) { let value = match inline { Some(value) => value, @@ -405,11 +462,12 @@ fn reconfigure_command(args: &[String], env: &Environment) -> Result Result { @@ -545,14 +603,15 @@ mod tests { #[test] fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() { - let Ok(Command::Reconfigure(options, document)) = parse_as( + let Ok(Command::Reconfigure(options, args)) = parse_as( false, &["reconfigure", "--context-tokens", "65536", "--prefix-cache-tail=reply", "--prefix-cache-mib", "20480", "--spec-min-p", "0.5", "--state-dir", "/var/lib/leleka/state"], ) else { panic!("reconfigure did not parse"); }; assert_eq!(options.dirs.state, std::path::PathBuf::from("/var/lib/leleka/state")); - let value: serde_json::Value = serde_json::from_str(&document).unwrap(); + assert!(!args.needs_restart() && !args.persist); + let value = serde_json::Value::Object(args.settings); assert_eq!(value["context_tokens"], 65536); assert_eq!(value["prefix_cache_tail"], "reply"); assert_eq!(value["prefix_cache_mib"], "20480"); @@ -562,6 +621,33 @@ mod tests { assert!(parse_as(false, &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"]).unwrap_err().contains("twice")); } + #[test] + fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { + let Ok(Command::Reconfigure(options, args)) = parse_as( + false, + &["reconfigure", "--gpu-budget-gib", "24", "--preset=workstation", "--persist", "--context-tokens", "65536", "--state-dir", "/s"], + ) else { + panic!("reconfigure did not parse"); + }; + assert!(args.needs_restart() && args.persist); + assert_eq!(args.gpu_budget_gib, Some(24)); + assert_eq!(args.preset, Some(crate::resources::Preset::Workstation)); + assert_eq!(args.settings["context_tokens"], 65536); + // they are the restart request, not `up` options: the service is located by the remaining flags only + assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); + assert_eq!(options.gpu_budget_gib, None); + assert_eq!(options.preset, crate::resources::Preset::Dedicated); + // the budget or the preset alone is a request; nothing at all is not + assert!(matches!(parse_as(false, &["reconfigure", "--preset", "dedicated"]), Ok(Command::Reconfigure(..)))); + assert!(matches!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), Ok(Command::Reconfigure(..)))); + assert!(parse_as(false, &["reconfigure", "--persist"]).unwrap_err().contains("at least one setting")); + assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]).unwrap_err().contains("1..1024")); + assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]).unwrap_err().contains("whole number")); + assert!(parse_as(false, &["reconfigure", "--preset", "shared"]).unwrap_err().contains("unknown preset")); + assert!(parse_as(false, &["reconfigure", "--persist=yes", "--cpu-workers", "2"]).unwrap_err().contains("no value")); + assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20", "--gpu-budget-gib", "21"]).unwrap_err().contains("twice")); + } + #[test] fn api_bind_is_explicit_and_only_for_the_api() { let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index a899f309..7744b1d5 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -44,6 +44,10 @@ pub struct RunConfig { 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, /// The resource preset `up` applied (the profile and `engine_env` already carry its numbers). #[serde(default)] pub preset: crate::resources::Preset, @@ -91,6 +95,7 @@ impl RunConfig { ports, gpu, profile, + base_profile: None, preset: crate::resources::Preset::default(), engine_env, load_timeout_s: 1800, diff --git a/crates/deploy/src/layout.rs b/crates/deploy/src/layout.rs index ae1a5518..bac823af 100644 --- a/crates/deploy/src/layout.rs +++ b/crates/deploy/src/layout.rs @@ -109,6 +109,14 @@ impl Paths { pub fn status_file(&self) -> PathBuf { self.run_dir().join("status.json") } + /// A pending `leleka reconfigure` for the supervisor (`reconfigure.rs`); consumed by it. + pub fn reconfigure_request(&self) -> PathBuf { + self.run_dir().join("reconfigure-request.json") + } + /// The supervisor's answer to the request with the same id. + pub fn reconfigure_result(&self) -> PathBuf { + self.run_dir().join("reconfigure-result.json") + } pub fn stamps(&self) -> PathBuf { self.dirs.state.join("stamps") } diff --git a/crates/deploy/src/lib.rs b/crates/deploy/src/lib.rs index 024b387c..ca9b195e 100644 --- a/crates/deploy/src/lib.rs +++ b/crates/deploy/src/lib.rs @@ -13,6 +13,7 @@ pub mod manifest; pub mod plan; pub mod preflight; pub mod profile; +pub mod reconfigure; pub mod resources; pub mod sealed; pub mod steps; diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index d6d3f87a..74319c02 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -247,6 +247,7 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context Ok(p) => { needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); let mut engine_env = BTreeMap::new(); + let base_profile = p.clone(); let resources = crate::resources::compute(&facts, gpu, p, opts.preset); crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some()); needs.resources = Some(resources); @@ -270,6 +271,7 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context engine_env, ); config.preset = opts.preset; + config.base_profile = Some(base_profile); let report = evaluate(&facts, p, &needs); (Some(config), Some(report)) } diff --git a/crates/deploy/src/profile.rs b/crates/deploy/src/profile.rs index 9081f762..deb0e5ef 100644 --- a/crates/deploy/src/profile.rs +++ b/crates/deploy/src/profile.rs @@ -94,6 +94,13 @@ pub struct MemoryBudget { /// where the agent's next turn resumes: the slot-equivalent resume, `docs/prefix-cache.md`). Absent: the engine's default (off). #[serde(default)] pub prefix_cache_tail: Option, + /// `--prefix-cache-block`: tokens per prefix block and chunk-grid step (a multiple of 256, at most 8192; 0 = the prefill chunk). + /// Only passed while the prefix cache is on. + #[serde(default)] + pub prefix_cache_block: Option, + /// Minutes an idle cached session is kept (`LELEKA_PREFIX_RETENTION_S`; 0 = no time limit). Only passed while the cache is on. + #[serde(default)] + pub prefix_retention_min: Option, /// Below this much available host memory the caches shed (`LELEKA_MEMORY_SOFT_FLOOR_MIB`). #[serde(default)] pub soft_floor_mib: Option, @@ -130,6 +137,11 @@ impl MemoryBudget { { return Err("memory.prefix_cache_tail must be off, prompt or reply".into()); } + if let Some(block) = self.prefix_cache_block + && (block % 256 != 0 || block > 8192) + { + return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); + } if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib) && hard >= soft { @@ -157,9 +169,19 @@ impl MemoryBudget { if let Some(tail) = &self.prefix_cache_tail { args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]); } + if let Some(block) = self.prefix_cache_block + && self.prefix_cache_on() + { + args.extend(["--prefix-cache-block".to_owned(), block.to_string()]); + } args } + /// The prefix cache is configured and not switched off (`0`). + pub fn prefix_cache_on(&self) -> bool { + self.prefix_cache_mib.as_deref().is_some_and(|mib| mib != "0") + } + /// The engine environment this section adds. pub fn env(&self) -> BTreeMap { let mut env = BTreeMap::new(); @@ -185,6 +207,9 @@ impl MemoryBudget { self.cache_share_percent.map(|v| v.to_string()), ); put("LELEKA_MEMORY_LOCK", self.lock.clone()); + if self.prefix_cache_on() { + put("LELEKA_PREFIX_RETENTION_S", self.prefix_retention_min.map(|minutes| minutes.saturating_mul(60).to_string())); + } put( "LELEKA_MEMORY_HEAL", self.heal.map(|v| if v { "1" } else { "0" }.to_owned()), diff --git a/crates/deploy/src/reconfigure.rs b/crates/deploy/src/reconfigure.rs new file mode 100644 index 00000000..08c6a3fa --- /dev/null +++ b/crates/deploy/src/reconfigure.rs @@ -0,0 +1,1103 @@ +//! `leleka reconfigure` for the settings the running engine cannot reopen by itself, and `--persist` for all of them. +//! +//! The engine reopens its serve stack with a new context, prefill chunk, caches, workers or draft floor without reloading +//! anything (`POST /v1/reconfigure`, `docs/deploy.md` 4d). What is fixed when the CUDA context is created (the VRAM budget +//! `--gpu-budget-gib` and the resource preset `--preset`, which sets the budget, the host-RAM floors and the CPU workers) +//! needs a new engine process. The supervisor (`supervisor.rs`) restarts only that process: the sealed archive memfd it holds +//! is handed to the new engine as it is to a crash-restarted one, and the gateway and the API keep their processes and ports. +//! +//! The operator side (`leleka reconfigure`) and the supervisor talk through two small private files in `STATE/run/`: the CLI +//! writes a [`Request`], the supervisor takes it, answers with an [`Outcome`] (first `running`, then `done`, `refused` or +//! `failed`) and the CLI waits for it. Everything that decides is a pure function here and is unit-tested: +//! +//! * [`apply_settings`]: the runtime settings (the same members as `POST /v1/reconfigure`) as profile fields +//! * [`plan`]: the new run configuration for a request, refused by the resource planner when the host cannot hold it +//! * [`persist`]: the files that make the change survive a restart (`leleka.json`, and `strata.json` for the context) +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; + +use crate::{ + config::{RunConfig, to_file_text}, + facts::{Facts, Gpu}, + layout::Paths, + profile::{ARCHIVE_BYTES, Profile}, + resources::{self, CPU_WORKERS_ENV, Preset, ResourcePlan}, +}; + +const GIB: u64 = 1 << 30; +const MIB: u64 = 1 << 20; +/// The runtime settings a request may carry, as `leleka reconfigure` and `POST /v1/reconfigure` name them. +pub const SETTINGS: [&str; 9] = [ + "context_tokens", + "prefill_capacity", + "kv_resident", + "prefix_cache_mib", + "prefix_cache_tail", + "prefix_cache_block", + "prefix_retention_min", + "cpu_workers", + "spec_min_p", +]; +/// The default prefill chunk of the engine when the profile names none. +const DEFAULT_PREFILL_CHUNK: u32 = 2048; +const PREFILL_CAPACITIES: [u64; 8] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192]; + +/// What the operator asks the supervisor for. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + /// Unique per request; the answer carries it. + pub id: String, + /// Restart the engine with this VRAM budget. + #[serde(default)] + pub gpu_budget_gib: Option, + /// Restart the engine under this resource preset. + #[serde(default)] + pub preset: Option, + /// Runtime settings (members of [`SETTINGS`]). With a budget or preset they come with the restart; alone they are + /// recorded only: the live engine already runs with them (the CLI called `POST /v1/reconfigure` first). + #[serde(default)] + pub settings: Map, + /// Write the result into `leleka.json` so that a restart of the service keeps it. + #[serde(default)] + pub persist: bool, +} + +impl Request { + /// A budget or preset change needs a new engine process. + pub fn needs_restart(&self) -> bool { + self.gpu_budget_gib.is_some() || self.preset.is_some() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + Running, + /// Applied (the engine runs with it; the files are written when asked). + Done, + /// Refused before or after stopping the engine; the previous settings are in force. + Refused, + /// The new engine did not come up and the previous one could not be restored either. + Failed, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Outcome { + pub id: String, + pub state: State, + pub message: String, + /// The numbers in force (see [`effective`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effective: Option, + #[serde(default)] + pub persisted: bool, +} + +// ---------------------------------------------------------------------------------------------------------- settings + +fn whole(value: &Value, name: &str) -> Result { + value + .as_u64() + .ok_or_else(|| format!("{name} must be a whole number")) +} + +/// The prefix-cache members imply the cache: the engine opens an `auto` cache when one of them is set while it is off. +fn enable_prefix_cache(profile: &mut Profile) { + if profile.memory.prefix_cache_mib.is_none() { + profile.memory.prefix_cache_mib = Some("auto".into()); + } +} + +/// Apply runtime `settings` to a profile the way the engine's `Tuning::apply` does (same members, same ranges); returns the +/// names that changed value. The profile is left untouched on error. +pub fn apply_settings( + profile: &mut Profile, + settings: &Map, +) -> Result, String> { + let mut next = profile.clone(); + for key in settings.keys() { + if !SETTINGS.contains(&key.as_str()) { + return Err(format!( + "unknown setting {key} (members: {})", + SETTINGS.join(", ") + )); + } + } + for (name, value) in settings { + match name.as_str() { + "context_tokens" => { + let tokens = whole(value, name)?; + if !(1..=262_144).contains(&tokens) { + return Err("context_tokens must be 1..=262144".into()); + } + next.context_tokens = tokens as u32; + } + "prefill_capacity" => { + let chunk = whole(value, name)?; + if !PREFILL_CAPACITIES.contains(&chunk) { + return Err(format!( + "prefill_capacity must be one of {PREFILL_CAPACITIES:?}" + )); + } + next.prefill_capacity = Some(chunk as u32); + } + "kv_resident" => { + let cells = whole(value, name)?; + if cells != 0 && !(20_480..=u64::from(u32::MAX)).contains(&cells) { + return Err( + "kv_resident must be 0 (the whole context) or at least 20480".into(), + ); + } + next.kv_resident = Some(cells as u32); + } + "prefix_cache_mib" => { + let text = match value { + Value::String(text) => text.trim().to_ascii_lowercase(), + Value::Number(number) => number.to_string(), + _ => { + return Err( + "prefix_cache_mib must be \"auto\", \"off\" or a size in MiB".into(), + ); + } + }; + next.memory.prefix_cache_mib = Some(match text.as_str() { + "auto" => "auto".to_owned(), + "off" | "0" => "0".to_owned(), + mib => mib + .parse::() + .ok() + .filter(|m| *m <= 1 << 30) + .ok_or("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB")? + .to_string(), + }); + } + "prefix_cache_tail" => { + let tail = value + .as_str() + .filter(|t| matches!(*t, "off" | "prompt" | "reply")); + next.memory.prefix_cache_tail = Some( + tail.ok_or("prefix_cache_tail must be off, prompt or reply")? + .to_owned(), + ); + enable_prefix_cache(&mut next); + } + "prefix_cache_block" => { + let block = whole(value, name)?; + if block % 256 != 0 || block > 8192 { + return Err("prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); + } + next.memory.prefix_cache_block = Some(block as u32); + enable_prefix_cache(&mut next); + } + "prefix_retention_min" => { + next.memory.prefix_retention_min = Some(whole(value, name)?); + enable_prefix_cache(&mut next); + } + "cpu_workers" => { + let workers = whole(value, name)?; + if !(1..=64).contains(&workers) { + return Err("cpu_workers must be 1..=64".into()); + } + next.engine_env + .insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); + } + "spec_min_p" => { + let p = value + .as_f64() + .filter(|p| p.is_finite() && (0.0..=1.0).contains(p)); + next.spec_min_p = Some(p.ok_or("spec_min_p must be within 0..=1")?); + } + _ => unreachable!("checked above"), + } + } + let chunk = next.prefill_capacity.unwrap_or(DEFAULT_PREFILL_CHUNK); + if next.memory.prefix_cache_on() + && let Some(block) = next.memory.prefix_cache_block + && block > chunk + { + return Err(format!( + "prefix_cache_block {block} is larger than the prefill chunk {chunk}" + )); + } + next.validate()?; + let changed = SETTINGS + .iter() + .filter(|name| { + settings.contains_key(**name) + && setting_view(&next, name) != setting_view(profile, name) + }) + .map(|name| (*name).to_owned()) + .collect(); + *profile = next; + Ok(changed) +} + +/// One runtime setting of a profile, for comparison and display. +fn setting_view(profile: &Profile, name: &str) -> Value { + match name { + "context_tokens" => json!(profile.context_tokens), + "prefill_capacity" => json!(profile.prefill_capacity), + "kv_resident" => json!(profile.kv_resident), + "prefix_cache_mib" => json!(profile.memory.prefix_cache_mib), + "prefix_cache_tail" => json!(profile.memory.prefix_cache_tail), + "prefix_cache_block" => json!(profile.memory.prefix_cache_block), + "prefix_retention_min" => json!(profile.memory.prefix_retention_min), + "cpu_workers" => json!(profile.engine_env.get(CPU_WORKERS_ENV)), + "spec_min_p" => json!(profile.spec_min_p), + _ => Value::Null, + } +} + +/// The numbers a run configuration starts the engine with, for the answer and for `leleka status`. +pub fn effective(config: &RunConfig) -> Value { + let env = config.engine_environment(); + let mut out = Map::new(); + out.insert( + "gpu_budget_gib".into(), + json!(config.profile.gpu_budget_bytes as f64 / GIB as f64), + ); + out.insert("preset".into(), json!(config.preset.as_str())); + out.insert( + "cpu_workers".into(), + json!(env.get(CPU_WORKERS_ENV).and_then(|w| w.parse::().ok())), + ); + out.insert( + "expert_source".into(), + json!(config.profile.expert_source.as_str()), + ); + for name in SETTINGS.iter().filter(|name| **name != "cpu_workers") { + out.insert((*name).to_owned(), setting_view(&config.profile, name)); + } + out.insert( + "ram_floors_mib".into(), + json!([ + config.profile.memory.soft_floor_mib, + config.profile.memory.hard_floor_mib + ]), + ); + Value::Object(out) +} + +// ---------------------------------------------------------------------------------------------------------- planning + +/// A request turned into the configuration the engine restarts with. +#[derive(Clone, Debug)] +pub struct Planned { + pub config: RunConfig, + pub resources: ResourcePlan, + /// Nothing differs from the configuration in force: no restart is needed. + pub unchanged: bool, +} + +/// What the host would offer once the engine is stopped: its VRAM and RAM are free again. Used before the engine is stopped, +/// so that only what is impossible even then is refused without disturbing the service; the exact check follows the stop. +pub fn optimistic(facts: &Facts) -> Facts { + let mut facts = facts.clone(); + for gpu in &mut facts.gpus { + gpu.vram_free_mib = gpu.vram_total_mib; + } + facts.memory.available = facts.memory.total; + facts +} + +fn gpu_of(facts: &Facts, index: u32) -> Option<&Gpu> { + facts.gpus.iter().find(|gpu| gpu.index == index) +} + +/// The new configuration for `request`, or why the host cannot take it. +/// +/// `archive_resident`: the supervisor holds the sealed archive memfd. Its pages already count against the host's available RAM, +/// so the planner is told they are there (it would otherwise charge the archive twice and decide the host is too small), and +/// a plan that would switch to the file-backed form is refused: the held memfd would be wasted and the new form was never +/// verified for this installation (`leleka up` decides that). +pub fn plan( + config: &RunConfig, + request: &Request, + facts: &Facts, + archive_resident: bool, +) -> Result { + let preset = request.preset.unwrap_or(config.preset); + let mut base = match &config.base_profile { + Some(base) => base.clone(), + None if config.preset == Preset::Workstation && preset != Preset::Workstation => { + return Err(format!( + "this installation did not record its profile before the {} preset changed it, so {} cannot be restored here: run `leleka up --preset {}`", + config.preset.as_str(), + preset.as_str(), + preset.as_str() + )); + } + None => config.profile.clone(), + }; + apply_settings(&mut base, &request.settings)?; + if let Some(gib) = request.gpu_budget_gib { + if !(1..=1024).contains(&gib) { + return Err("--gpu-budget-gib must be 1..1024".into()); + } + base.gpu_budget_bytes = gib * GIB; + // The profile's free-VRAM need is its measured peak under the budget; it cannot exceed the budget. + base.min_vram_free_mib = base.min_vram_free_mib.map(|need| need.min(gib * 1024)); + } + base.validate()?; + let mut profile = base.clone(); + + let mut seen = facts.clone(); + if archive_resident { + seen.memory.available = seen.memory.available.saturating_add(ARCHIVE_BYTES); + } + let gpu = gpu_of(&seen, config.gpu).cloned(); + let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset); + if !resources.problems.is_empty() { + return Err(resources.problems.join("; ")); + } + if let Some(requested) = request.gpu_budget_gib + && resources.gpu_budget_bytes < requested * GIB + { + return Err(format!( + "the {} preset leaves {:.1} GiB of VRAM to the engine and --gpu-budget-gib {requested} asks for more: lower the budget or use --preset dedicated", + preset.as_str(), + resources.gpu_budget_bytes as f64 / GIB as f64 + )); + } + if resources.mapped_resident_gib.is_some() && archive_resident { + return Err(format!( + "this host cannot keep the sealed archive and the {} preset's free memory at once, which would need the file-backed form; run `leleka up --preset {}` to change the form", + preset.as_str(), + preset.as_str() + )); + } + let mut env = config.engine_env.clone(); + env.remove(CPU_WORKERS_ENV); + resources::apply( + &resources, + &mut profile, + &mut env, + request.gpu_budget_gib.is_some(), + ); + profile.validate()?; + if let Some(gpu) = &gpu { + let budget_mib = profile.gpu_budget_bytes / MIB; + if budget_mib > gpu.vram_total_mib { + return Err(format!( + "GPU memory: a budget of {} MiB does not fit the {} MiB of {}", + budget_mib, gpu.vram_total_mib, gpu.name + )); + } + let need = profile.min_vram_free_mib.unwrap_or(budget_mib); + if gpu.vram_free_mib < need { + return Err(format!( + "GPU memory: {} MiB free but the engine needs {need} MiB (another process holds VRAM; see nvidia-smi)", + gpu.vram_free_mib + )); + } + } + let mut next = config.clone(); + next.profile = profile; + next.base_profile = Some(base); + next.preset = preset; + next.engine_env = env; + let unchanged = next.profile == config.profile + && next.preset == config.preset + && next.engine_env == config.engine_env; + Ok(Planned { + config: next, + resources, + unchanged, + }) +} + +/// `--persist` without a restart: the live engine already runs with `settings`; fold them into the configuration. Returns +/// the names that changed. +pub fn record_settings( + config: &mut RunConfig, + settings: &Map, +) -> Result, String> { + let mut next = config.clone(); + let changed = apply_settings(&mut next.profile, settings)?; + if let Some(base) = &mut next.base_profile { + apply_settings(base, settings)?; + } + // The preset's own worker count (in the up-resolved environment) must not shadow an explicit one. + if settings.contains_key("cpu_workers") { + next.engine_env.remove(CPU_WORKERS_ENV); + } + *config = next; + Ok(changed) +} + +// ---------------------------------------------------------------------------------------------------------- files + +/// Write `leleka.json` (and `strata.json`, which carries the context the API advertises) atomically with mode 0600. +pub fn persist(paths: &Paths, config: &RunConfig) -> Result<(), String> { + crate::supervisor::write_private(&paths.run_config(), &to_file_text(config)) + .map_err(|error| format!("cannot write {}: {error}", paths.run_config().display()))?; + let strata = to_file_text(&config.strata_json()); + if std::fs::read_to_string(paths.strata_config()) + .ok() + .as_deref() + != Some(strata.as_str()) + { + crate::supervisor::write_private(&paths.strata_config(), &strata).map_err(|error| { + format!("cannot write {}: {error}", paths.strata_config().display()) + })?; + } + Ok(()) +} + +/// `--persist` when no supervisor runs: edit the files directly. +pub fn persist_offline( + paths: &Paths, + settings: &Map, +) -> Result, String> { + let mut config = RunConfig::read(&paths.run_config())?; + let changed = record_settings(&mut config, settings)?; + persist(paths, &config)?; + Ok(changed) +} + +fn write_json(path: &std::path::Path, value: &impl Serialize) -> Result<(), String> { + crate::supervisor::write_private(path, &to_file_text(value)) + .map_err(|error| format!("cannot write {}: {error}", path.display())) +} + +/// Leave a request for the supervisor. A request still pending is not overwritten. +pub fn write_request(paths: &Paths, request: &Request) -> Result<(), String> { + if paths.reconfigure_request().exists() { + return Err("another reconfigure request is waiting for the supervisor".into()); + } + let _ = std::fs::remove_file(paths.reconfigure_result()); + write_json(&paths.reconfigure_request(), request) +} + +/// The supervisor takes the pending request (the file is removed so that it runs once). `Err`: it could not be read. +pub fn take_request(paths: &Paths) -> Option> { + let path = paths.reconfigure_request(); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None, + Err(error) => { + let _ = std::fs::remove_file(&path); + return Some(Err(format!("cannot read the request: {error}"))); + } + }; + let _ = std::fs::remove_file(&path); + Some( + serde_json::from_str::(&text) + .map_err(|error| format!("invalid reconfigure request: {error}")), + ) +} + +pub fn write_outcome(paths: &Paths, outcome: &Outcome) -> Result<(), String> { + write_json(&paths.reconfigure_result(), outcome) +} + +pub fn read_outcome(paths: &Paths, id: &str) -> Option { + let text = std::fs::read_to_string(paths.reconfigure_result()).ok()?; + serde_json::from_str::(&text) + .ok() + .filter(|outcome| outcome.id == id) +} + +/// A request id that two invocations do not share. +pub fn new_request_id() -> String { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + format!("{}-{nanos}", std::process::id()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{config::Ports, facts::Memory, layout::Dirs, profile::KarSource}; + use std::collections::BTreeMap; + + fn gpu(total: u64, free: u64) -> Gpu { + Gpu { + index: 0, + name: "NVIDIA GeForce RTX 5090".into(), + driver: "595.99".into(), + vram_total_mib: total, + vram_free_mib: free, + sm: Some(120), + } + } + + fn host(cores: u32, ram_gib: u64, avail_gib: u64, gpus: Vec) -> Facts { + Facts { + cpu_cores: cores, + memory: Memory { + total: ram_gib * GIB, + available: avail_gib * GIB, + swap_total: 0, + }, + gpus, + ..Facts::default() + } + } + + /// The server as `leleka up` left it (no preset): the dedicated profile of the RTX 5090. + fn server_config() -> RunConfig { + let dirs = Dirs { + prefix: "/opt/leleka".into(), + state: "/var/lib/leleka/state".into(), + assets: "/data".into(), + }; + let ports = Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }; + let profile = Profile::builtin("rtx5090-32g").unwrap(); + // `up` resolved the dedicated preset's worker count into the environment + let env = BTreeMap::from([(CPU_WORKERS_ENV.to_owned(), "8".to_owned())]); + let mut config = RunConfig::new(&dirs, ports, 0, profile.clone(), env); + config.base_profile = Some(profile); + config + } + + fn request(budget: Option, preset: Option, settings: Value) -> Request { + Request { + id: "t".into(), + gpu_budget_gib: budget, + preset, + settings: settings.as_object().cloned().unwrap_or_default(), + persist: false, + } + } + + fn big_host() -> Facts { + host(32, 121, 100, vec![gpu(32607, 32100)]) + } + + #[test] + fn runtime_settings_become_profile_fields_with_the_engines_ranges() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let settings = json!({ + "context_tokens": 131072, "prefill_capacity": 8192, "kv_resident": 0, "prefix_cache_mib": "20480", + "prefix_cache_tail": "reply", "prefix_cache_block": 8192, "prefix_retention_min": 30, "cpu_workers": 6, "spec_min_p": 0.5 + }); + let changed = apply_settings(&mut profile, settings.as_object().unwrap()).unwrap(); + for name in [ + "context_tokens", + "prefill_capacity", + "prefix_cache_mib", + "prefix_cache_block", + "prefix_retention_min", + "cpu_workers", + "spec_min_p", + ] { + assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); + } + assert_eq!( + ( + profile.context_tokens, + profile.prefill_capacity, + profile.kv_resident + ), + (131072, Some(8192), Some(0)) + ); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("20480")); + assert_eq!(profile.memory.prefix_cache_tail.as_deref(), Some("reply")); + assert_eq!( + ( + profile.memory.prefix_cache_block, + profile.memory.prefix_retention_min + ), + (Some(8192), Some(30)) + ); + assert_eq!( + profile.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("6") + ); + assert_eq!(profile.spec_min_p, Some(0.5)); + // the same document again changes nothing + assert!( + apply_settings(&mut profile, settings.as_object().unwrap()) + .unwrap() + .is_empty() + ); + // and they reach the engine as flags and environment + let config = RunConfig::new( + &Dirs { + prefix: "/p".into(), + state: "/s".into(), + assets: "/a".into(), + }, + Ports { + api: "127.0.0.1:1".into(), + engine: "127.0.0.1:2".into(), + daemon: "127.0.0.1:3".into(), + }, + 0, + profile, + BTreeMap::new(), + ); + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + args.contains("--context-tokens 131072") + && args.contains("--original-prefill-capacity 8192"), + "{args}" + ); + assert!( + args.contains("--kv-resident 0") && args.contains("--prefix-cache-mib 20480"), + "{args}" + ); + assert!( + args.contains("--prefix-cache-tail reply") + && args.contains("--prefix-cache-block 8192"), + "{args}" + ); + assert!(args.contains("--spec-min-p 0.5"), "{args}"); + let env = config.engine_environment(); + assert_eq!( + env.get("LELEKA_PREFIX_RETENTION_S").map(String::as_str), + Some("1800") + ); + assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("6")); + } + + #[test] + fn invalid_settings_change_nothing_and_say_why() { + for (bad, why) in [ + (json!({"context_tokens": 0}), "context_tokens"), + (json!({"context_tokens": 300000}), "context_tokens"), + (json!({"context_tokens": "big"}), "whole number"), + (json!({"prefill_capacity": 5000}), "prefill_capacity"), + (json!({"kv_resident": 1000}), "kv_resident"), + (json!({"cpu_workers": 0}), "cpu_workers"), + (json!({"cpu_workers": 65}), "cpu_workers"), + (json!({"spec_min_p": 1.5}), "spec_min_p"), + (json!({"prefix_cache_tail": "always"}), "prefix_cache_tail"), + (json!({"prefix_cache_mib": "lots"}), "prefix_cache_mib"), + (json!({"prefix_cache_block": 300}), "multiple of 256"), + ( + json!({"prefix_cache_block": 8192}), + "larger than the prefill chunk", + ), + (json!({"nonsense": 1}), "unknown setting"), + ] { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let before = profile.clone(); + let error = apply_settings(&mut profile, bad.as_object().unwrap()).unwrap_err(); + assert!(error.contains(why), "{bad}: {error}"); + assert_eq!(profile, before, "{bad} must change nothing"); + } + } + + #[test] + fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memory.prefix_cache_mib = None; + apply_settings( + &mut profile, + json!({"prefix_cache_tail": "prompt"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!( + profile.memory.prefix_cache_mib.as_deref(), + Some("auto"), + "the engine opens an auto cache for a lone member" + ); + apply_settings( + &mut profile, + json!({"prefix_cache_mib": "off"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("0")); + profile.memory.prefix_cache_block = Some(512); + let mut config = server_config(); + config.profile = profile; + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + !args.contains("--prefix-cache-block"), + "a block is not passed while the cache is off: {args}" + ); + } + + #[test] + fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { + let config = server_config(); + let planned = plan( + &config, + &request(Some(24), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(!planned.unchanged); + assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!( + planned + .config + .base_profile + .as_ref() + .unwrap() + .gpu_budget_bytes, + 24 * GIB + ); + assert_eq!( + planned.config.profile.context_tokens, + config.profile.context_tokens + ); + assert_eq!(planned.config.preset, Preset::Dedicated); + let args = planned + .config + .engine_args(crate::config::KarArg::Fd) + .join(" "); + assert!( + args.contains(&format!("--gpu-budget {}", 24 * GIB)), + "{args}" + ); + // the same budget again is a no-op, not a five-minute restart + let same = plan( + &config, + &request(Some(30), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(same.unchanged, "the profile already has a 30 GiB budget"); + } + + #[test] + fn the_workstation_preset_applies_and_dedicated_undoes_it() { + let config = server_config(); + let to_workstation = plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + let ws = &to_workstation.config; + assert_eq!(ws.preset, Preset::Workstation); + assert_eq!( + ws.profile.gpu_budget_bytes, + 27 * GIB, + "32100 MiB free minus the 4 GiB left to the desktop" + ); + assert_eq!(ws.profile.memory.soft_floor_mib, Some(16384)); + assert_eq!( + ws.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("8") + ); + // back: the unmodified profile is restored from the recorded base + let back = plan( + ws, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(back.config.profile, config.profile); + assert_eq!(back.config.preset, Preset::Dedicated); + // `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it + let both = plan( + &config, + &request(Some(24), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!(both.config.preset, Preset::Workstation); + assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384)); + } + + #[test] + fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset() { + let mut config = server_config(); + config.base_profile = None; + config.preset = Preset::Workstation; + let error = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap_err(); + assert!(error.contains("leleka up --preset dedicated"), "{error}"); + // staying on workstation, or going to it from dedicated, works without a base + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &big_host(), + true + ) + .is_ok() + ); + config.preset = Preset::Dedicated; + assert!( + plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true + ) + .is_ok() + ); + } + + #[test] + fn unsafe_values_are_refused_by_the_planner() { + let config = server_config(); + let refused = |request: Request, facts: &Facts, resident: bool| { + plan(&config, &request, facts, resident).unwrap_err() + }; + // more than the card has + let error = refused(request(Some(40), None, json!({})), &big_host(), true); + assert!(error.contains("does not fit the 32607 MiB"), "{error}"); + // not a budget at all + assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024")); + assert!( + refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024") + ); + // another process holds the card (checked once the engine is stopped) + let busy = host(32, 121, 100, vec![gpu(32607, 9000)]); + let error = refused(request(Some(24), None, json!({})), &busy, true); + assert!( + error.contains("9000 MiB free") && error.contains("needs"), + "{error}" + ); + // the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM + assert!( + plan( + &config, + &request(Some(24), None, json!({})), + &optimistic(&busy), + true + ) + .is_ok() + ); + // the workstation preset on a card that is mostly taken is a problem, not a silent shrink + let taken = host(32, 121, 100, vec![gpu(32607, 12000)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &taken, + true, + ); + assert!(error.contains("workstation preset"), "{error}"); + // an explicit budget the preset cannot give + let error = refused( + request(Some(30), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ); + assert!(error.contains("asks for more"), "{error}"); + // a bad runtime setting riding along refuses the whole request + assert!( + refused( + request(Some(24), None, json!({"cpu_workers": 99})), + &big_host(), + true + ) + .contains("cpu_workers") + ); + // a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form + let small = host(32, 64, 10, vec![gpu(32607, 32100)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &small, + true, + ); + assert!( + error.contains("file-backed form") || error.contains("leleka up"), + "{error}" + ); + } + + #[test] + fn the_resident_archive_is_not_charged_twice_to_the_host() { + // 121 GiB host, 100 GiB available *with* the 55 GB memfd already resident: fits the dedicated preset + let config = server_config(); + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &host(32, 121, 40, vec![gpu(32607, 32100)]), + true + ) + .is_ok() + ); + // a profile that reads the archive from a file keeps charging it to the planner as before + let mut file = server_config(); + file.profile.kar_source = KarSource::File; + file.base_profile = Some(file.profile.clone()); + assert!( + plan( + &file, + &request(Some(20), None, json!({})), + &host(32, 121, 40, vec![gpu(32607, 32100)]), + false + ) + .is_ok() + ); + } + + #[test] + fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() { + let mut config = plan( + &server_config(), + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!( + config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("8") + ); + let changed = record_settings( + &mut config, + json!({"context_tokens": 65536, "cpu_workers": 5}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!( + changed, + vec!["context_tokens".to_owned(), "cpu_workers".to_owned()] + ); + assert_eq!(config.profile.context_tokens, 65536); + assert_eq!(config.base_profile.as_ref().unwrap().context_tokens, 65536); + assert_eq!( + config + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); + // an invalid document leaves the configuration alone + let before = config.clone(); + assert!( + record_settings( + &mut config, + json!({"context_tokens": 0}).as_object().unwrap() + ) + .is_err() + ); + assert_eq!(config, before); + // switching preset afterwards keeps the explicit setting + let again = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!(again.profile.context_tokens, 65536); + assert_eq!( + again + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); + } + + #[test] + fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { + let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + assert!(take_request(&paths).is_none()); + let asked = request( + Some(24), + Some(Preset::Workstation), + json!({"context_tokens": 65536}), + ); + write_request(&paths, &asked).unwrap(); + assert!( + write_request(&paths, &asked) + .unwrap_err() + .contains("waiting") + ); + assert_eq!(take_request(&paths).unwrap().unwrap(), asked); + assert!(take_request(&paths).is_none(), "the file is consumed"); + // a corrupt request is reported, not retried forever + std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); + assert!( + take_request(&paths) + .unwrap() + .unwrap_err() + .contains("invalid") + ); + assert!(!paths.reconfigure_request().exists()); + let outcome = Outcome { + id: asked.id.clone(), + state: State::Refused, + message: "no".into(), + effective: None, + persisted: false, + }; + write_outcome(&paths, &outcome).unwrap(); + assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); + assert_eq!(read_outcome(&paths, "other"), None); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { + let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + let mut config = server_config(); + config.prefix = dirs.prefix.display().to_string(); + config.state = dirs.state.display().to_string(); + config.assets = dirs.assets.display().to_string(); + persist(&paths, &config).unwrap(); + let changed = persist_offline( + &paths, + json!({"context_tokens": 100000, "prefix_cache_tail": "prompt"}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!(changed.len(), 2); + let back = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!(back.profile.context_tokens, 100000); + assert_eq!( + back.profile.memory.prefix_cache_tail.as_deref(), + Some("prompt") + ); + let strata: Value = + serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); + assert_eq!(strata["runtime"]["max_context"], 100000); + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(paths.run_config()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn the_effective_summary_names_the_numbers_in_force() { + let summary = effective(&server_config()); + assert_eq!(summary["gpu_budget_gib"], 30.0); + assert_eq!(summary["preset"], "dedicated"); + assert_eq!(summary["context_tokens"], 262144); + assert_eq!(summary["cpu_workers"], 8); + } +} diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index db9f69d4..3ba14937 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -11,7 +11,7 @@ use crate::{ http, layout::{MTP_PROFILE, Paths}, profile::{ARCHIVE_BYTES, KarSource, archive_sha256}, - sealed, + reconfigure, sealed, }; use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; use serde::Serialize; @@ -701,11 +701,28 @@ impl Supervisor { )); let mut ready_since = Instant::now(); let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32); + // `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); // 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(), + 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.line(&format!("engine exited ({text}); the API reports not-ready until it is back")); @@ -1060,6 +1077,161 @@ impl Supervisor { } } + /// 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, 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 = self.start_engine(gateway).await?; + *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(()) + } + /// 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() { diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs index d44adeb3..cf8f839f 100644 --- a/crates/deploy/tests/e2e.rs +++ b/crates/deploy/tests/e2e.rs @@ -956,3 +956,237 @@ fn profiles_and_usage_commands() { assert_eq!(bad.status.code(), Some(2)); assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option")); } + +// ------------------------------------------------------------------------------------------------ leleka reconfigure + +mod reconfigure_flow { + use super::*; + use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request}; + use leleka_deploy::resources::Preset; + use serde_json::json; + + const GIB: u64 = 1 << 30; + + fn request(id: &str, budget_gib: Option, preset: Option, settings: serde_json::Value, persist: bool) -> Request { + Request { + id: id.to_owned(), + gpu_budget_gib: budget_gib, + preset, + settings: settings.as_object().cloned().unwrap_or_default(), + persist, + } + } + + fn ask(fixture: &Fixture, request: &Request, limit: Duration) -> Outcome { + write_request(&fixture.dirs.paths(), request).unwrap(); + let started = Instant::now(); + loop { + if let Some(outcome) = read_outcome(&fixture.dirs.paths(), &request.id) + && outcome.state != State::Running + { + return outcome; + } + assert!(started.elapsed() < limit, "no answer to {}; logs:\n{}", request.id, fixture.logs()); + std::thread::sleep(Duration::from_millis(200)); + } + } + + /// A supervisor with the fake runtime programs and an inherited sealed archive, ready. + struct Service { + fixture: Fixture, + supervisor: Child, + _memfd: fs::File, + first: serde_json::Value, + } + + fn start(name: &str) -> Service { + let fixture = Fixture::new(name); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::Memfd; + let config = fixture.write_state(profile); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let supervisor = start_supervisor(&fixture, &config, Some(std::os::fd::AsRawFd::as_raw_fd(&memfd))); + let first = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + Service { fixture, supervisor, _memfd: memfd, first } + } + + impl Service { + fn starts(&self) -> Vec { + fs::read_to_string(self.fixture.fake_dir().join("calls.log")) + .unwrap() + .lines() + .filter(|line| line.starts_with("leleka-inference ")) + .map(str::to_owned) + .collect() + } + + fn stop(mut self) { + signal(u64::from(self.supervisor.id()), "TERM"); + assert!(wait_exit(&mut self.supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), "{}", self.fixture.logs()); + } + } + + #[test] + fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { + let service = start("reconf-budget"); + let fixture = &service.fixture; + let (engine, gateway, api) = ( + service.first["engine_pid"].as_u64().unwrap(), + service.first["gateway_pid"].as_u64().unwrap(), + service.first["api_pid"].as_u64().unwrap(), + ); + let before = fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(); + let outcome = ask(fixture, &request("budget", Some(2), None, json!({}), false), Duration::from_secs(120)); + assert_eq!(outcome.state, State::Done, "{}\n{}", outcome.message, fixture.logs()); + assert!(!outcome.persisted); + assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0); + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| s["phase"] == "ready"); + assert_ne!(after["engine_pid"].as_u64().unwrap(), engine, "the engine process is new"); + assert!(!pid_alive(engine), "the old engine is gone"); + assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway, "the gateway keeps its process"); + assert_eq!(after["api_pid"].as_u64().unwrap(), api, "the API keeps its process"); + assert_eq!(after["engine_restarts"], 0, "a planned restart is not a crash"); + assert_eq!(fixture.http_status("/ready"), 200); + let starts = service.starts(); + assert_eq!(starts.len(), 2, "{starts:?}"); + assert!(starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), "{}", starts[0]); + assert!(starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), "{}", starts[1]); + // the sealed descriptor of the first engine was handed on, and it is the one already verified + assert!(starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), "{}", starts[1]); + let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); + assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); + // not persisted: the file still has the old budget + assert_eq!(fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), before); + // asking for what is in force is answered at once, without another restart + let same = ask(fixture, &request("same", Some(2), None, json!({}), false), Duration::from_secs(20)); + assert_eq!((same.state, same.message.contains("already")), (State::Done, true), "{}", same.message); + assert_eq!(service.starts().len(), 2); + service.stop(); + } + + #[test] + fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { + let service = start("reconf-persist"); + let fixture = &service.fixture; + let gateway = service.first["gateway_pid"].as_u64().unwrap(); + let api = service.first["api_pid"].as_u64().unwrap(); + let outcome = ask( + fixture, + &request("persist", Some(3), Some(Preset::Workstation), json!({"context_tokens": 4096, "cpu_workers": 3}), true), + Duration::from_secs(120), + ); + assert_eq!(outcome.state, State::Done, "{}\n{}", outcome.message, fixture.logs()); + assert!(outcome.persisted, "{}", outcome.message); + let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB); + assert_eq!(config.profile.context_tokens, 4096); + assert_eq!(config.preset, Preset::Workstation); + assert!(config.base_profile.is_some(), "the unmodified profile is kept to undo the preset"); + assert_eq!(config.engine_environment().get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").map(String::as_str), Some("3")); + // the API advertises the new context: its process was restarted on the same port, the gateway was not + let strata: serde_json::Value = serde_json::from_str(&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap()).unwrap(); + assert_eq!(strata["runtime"]["max_context"], 4096); + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| s["phase"] == "ready"); + assert_ne!(after["api_pid"].as_u64().unwrap(), api); + assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway); + assert_eq!(fixture.http_status("/ready"), 200); + // a crash of the new engine restarts it with the new numbers, not the old ones + signal(after["engine_pid"].as_u64().unwrap(), "KILL"); + let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| s["phase"] == "ready" && s["engine_restarts"] == 1); + assert_ne!(again["engine_pid"], after["engine_pid"]); + let starts = service.starts(); + let last = starts.last().unwrap(); + assert!(last.contains(&format!("--gpu-budget {}", 3 * GIB)) && last.contains("--context-tokens 4096"), "{last}"); + service.stop(); + } + + #[test] + fn settings_alone_are_recorded_and_persisted_without_a_restart() { + let service = start("reconf-record"); + let fixture = &service.fixture; + let engine = service.first["engine_pid"].as_u64().unwrap(); + let outcome = ask(fixture, &request("record", None, None, json!({"prefix_cache_tail": "prompt", "spec_min_p": 0.25}), true), Duration::from_secs(30)); + assert_eq!((outcome.state, outcome.persisted), (State::Done, true), "{}", outcome.message); + let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.memory.prefix_cache_tail.as_deref(), Some("prompt")); + assert_eq!(config.profile.spec_min_p, Some(0.25)); + assert_eq!(fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), engine, "no restart"); + assert_eq!(service.starts().len(), 1); + // not persisted: in force for this supervisor only + let quiet = ask(fixture, &request("quiet", None, None, json!({"context_tokens": 2048}), false), Duration::from_secs(30)); + assert_eq!((quiet.state, quiet.persisted), (State::Done, false)); + let file = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_ne!(file.profile.context_tokens, 2048); + // an invalid document is refused and changes nothing + let bad = ask(fixture, &request("bad", None, None, json!({"cpu_workers": 99}), true), Duration::from_secs(30)); + assert_eq!(bad.state, State::Refused); + assert!(bad.message.contains("cpu_workers"), "{}", bad.message); + service.stop(); + } + + #[test] + fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one() { + let service = start("reconf-refuse"); + let fixture = &service.fixture; + let engine = service.first["engine_pid"].as_u64().unwrap(); + // refused before the engine is touched + let bad = ask(fixture, &request("bad", Some(2), None, json!({"cpu_workers": 99}), false), Duration::from_secs(30)); + assert_eq!(bad.state, State::Refused); + assert!(bad.message.contains("nothing was changed"), "{}", bad.message); + let unknown = ask(fixture, &request("unknown", Some(2), None, json!({"nonsense": 1}), false), Duration::from_secs(30)); + assert_eq!(unknown.state, State::Refused); + assert_eq!(fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), engine, "the engine was not stopped"); + assert!(pid_alive(engine)); + // a budget the new engine cannot start with: the previous engine is started again with the previous numbers + fs::write(fixture.fake_dir().join("fail-engine-budget"), (4 * GIB).to_string()).unwrap(); + let outcome = ask(fixture, &request("fails", Some(4), None, json!({}), true), Duration::from_secs(180)); + assert_eq!(outcome.state, State::Refused, "{}\n{}", outcome.message, fixture.logs()); + assert!(outcome.message.contains("previous settings are back"), "{}", outcome.message); + let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| s["phase"] == "ready"); + assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine); + assert_eq!(fixture.http_status("/ready"), 200); + let starts = service.starts(); + assert_eq!(starts.len(), 3, "{starts:?}"); + assert!(starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), "{starts:?}"); + // nothing was persisted from the failed attempt + let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); + service.stop(); + } + + #[test] + fn the_cli_asks_the_supervisor_and_prints_the_answer() { + let service = start("reconf-cli"); + let dirs = service.fixture.dirs.clone(); + let run = |args: &[&str]| { + Process::new(LELEKA) + .arg("reconfigure") + .args(args) + .arg("--state-dir") + .arg(&dirs.state) + .arg("--assets") + .arg(&dirs.assets) + .arg("--prefix") + .arg(&dirs.prefix) + .output() + .unwrap() + }; + let output = run(&["--gpu-budget-gib", "5", "--persist"]); + let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{text}\n{}", service.fixture.logs()); + assert!(text.contains("reconfigured") && text.contains("gpu_budget_gib"), "{text}"); + let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB); + // a refusal is a non-zero exit with the reason + let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]); + assert!(!refused.status.success()); + let text = String::from_utf8_lossy(&refused.stderr); + assert!(text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"), "{text}"); + service.stop(); + // without a supervisor the restart path says what to do instead of hanging + let stopped = run(&["--preset", "workstation"]); + assert!(!stopped.status.success()); + assert!(String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"), "{}", String::from_utf8_lossy(&stopped.stderr)); + } +} diff --git a/docs/deploy.md b/docs/deploy.md index 279e2129..3c38b27d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -170,9 +170,35 @@ leleka status # prints "settings in force" with the engine telemetry The same call is `POST /v1/reconfigure` with the JSON document (`{"context_tokens": 131072, ...}`; same bearer key; the answer carries the effective settings) and gRPC `Runtime.Reconfigure`. The prefix cache is rebuilt empty (its host images belong to the old stack), so the -next request of every session reads its prompt again once. Run-time changes do not survive a restart: to keep them, change the profile -(`--context-tokens`, `memory.prefix_cache_*`) or the preset and run `leleka up` again. What cannot change at run time is fixed when the CUDA -context is created: the VRAM budget (`--gpu-budget-gib`) and the preset; those take a restart. +next request of every session reads its prompt again once. + +**Keeping a change (`--persist`).** Without it a change lasts until the service restarts. With `--persist` the supervisor also writes the +result into `STATE/leleka.json` (profile fields: `context_tokens`, `prefill_capacity`, `kv_resident`, `spec_min_p`, +`memory.prefix_cache_{mib,tail,block}`, `memory.prefix_retention_min`, and `engine_env.LELEKA_ORIGINAL_SERVE_CPU_WORKERS` for the workers) and +regenerates `strata.json`, so a restart of the service, and a restart of a crashed engine, start with the new numbers. The file written is the +configuration in force, so a change made earlier without `--persist` in the same service life is written with it. With no supervisor running +the file is edited directly. + +**Budget and preset: restart in place.** The VRAM budget and the resource preset are fixed when the CUDA context is created, so the running +engine cannot reopen them. `leleka reconfigure --gpu-budget-gib 24 --preset workstation` (either alone, plus any runtime settings and +`--persist`) hands the request to the supervisor (a small file in `STATE/run/`, answered in `reconfigure-result.json`), which + +1. checks it with the resource planner (`resources.rs`) without disturbing the service, and refuses what cannot work even with the engine gone + (a budget above the card, the workstation preset on a card that is mostly taken, an explicit budget the preset cannot give, an invalid + runtime setting, a host too small to keep the sealed archive and the preset's free memory at once); +2. stops the engine process (SIGINT, then SIGKILL after the grace period) and checks again against what the host really has free; +3. starts the engine again with the new numbers (`--gpu-budget`, the preset's CPU workers and RAM floors, the runtime settings), handing it the + sealed archive descriptor the supervisor still holds (no second 55 GB copy, no second hash: the first engine already verified this memfd), + and loads the model (minutes); +4. keeps the gateway and the API in their processes and on their ports; requests that arrive during the restart see `/ready` 503. With + `--persist` and a new context the API process is restarted too (seconds), because `strata.json` carries the context it advertises. + +If the planner refuses after the stop, or the new engine does not come up, the previous settings are started again and the call answers +`... ; the previous settings are back` with a non-zero exit. A request that equals what is in force is answered at once. A planned restart does +not count against the crash-restart limit. The planner needs the supervisor to hold the archive (`kar_source: memfd`) and refuses a plan that +would switch the installation to the file-backed form: `leleka up` decides that. Going back from `workstation` to `dedicated` restores the +profile as `up` resolved it (`base_profile` in `leleka.json`, written since this feature; an older file can leave `workstation` only through +`leleka up --preset dedicated`). ## 5. Flags From d2701dbc6579426e6c9766024c3a45755f26b474 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:36:50 +0100 Subject: [PATCH 04/10] docs: feasibility decisions for KAR routed/prefill experts and the multi-GPU handoff; bring-up print review with a source-scan guard Item 5: the patch source is not in the tree but is in the git objects of the codex KAR branch; recorded what it is, what can be recovered and why it is not ported. Item 6: scope of set_stage/set_next and what a layer split needs; nothing implemented. Item 8: every production DBG/PROBE print is behind LELEKA_BRINGUP_TRACE or a switch of its own; crates/leleka-runtime/tests/bringup_prints_gated.rs keeps it so. Co-Authored-By: Claude Sonnet 5.5 --- .../src/qwen_forward/original_serve_stack.rs | 1 + .../tests/bringup_prints_gated.rs | 142 ++++++++++++++++++ docs/port-remaining.md | 103 ++++++++++++- docs/port-status.md | 4 +- 4 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 crates/leleka-runtime/tests/bringup_prints_gated.rs diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index a04ad96d..94926c47 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1235,6 +1235,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); } + // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. eprintln!( "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", 100.0 * by_initial / total, diff --git a/crates/leleka-runtime/tests/bringup_prints_gated.rs b/crates/leleka-runtime/tests/bringup_prints_gated.rs new file mode 100644 index 00000000..1a616bf3 --- /dev/null +++ b/crates/leleka-runtime/tests/bringup_prints_gated.rs @@ -0,0 +1,142 @@ +//! Production serving prints nothing of the bring-up diagnostics. +//! +//! Every `eprintln!("DBG ...")` / `eprintln!("PROBE ...")` in the production code of `leleka-runtime` and `leleka-cuda-driver` must be +//! silent unless somebody asked for it: through `bringup_trace!` (`LELEKA_BRINGUP_TRACE`), or under a dedicated opt-in switch of its +//! own (`LELEKA_SERVE_PROFILE`, `LELEKA_SPEC_TRACE`, `LELEKA_SEED_TRACE`, `LELEKA_TRACE_PLE`, ...), which the print has to sit +//! behind within a few lines. Test-only modules (the `#[ignore]`d GPU smokes, whose output is their evidence) are exempt. +//! +//! This reads the sources; it does not execute anything and needs no GPU. It exists so that a new unguarded `DBG` line cannot slip +//! into a release unnoticed (the review that gated the existing ones is in `docs/port-remaining.md`). +use std::{ + fs, + path::{Path, PathBuf}, +}; + +/// A print counts as guarded when one of these appears on its line or within [`LOOKBACK`] lines above it. +const GUARDS: &[&str] = &[ + "bringup_trace", + "enabled()", + "stats_enabled", + "trace_enabled", + "trace_ple()", + "trace_residual()", + "trace_logprobs()", + "LELEKA_SEED_TRACE", + "seed_coverage_trace", + "window_clock", + "gpu_profile.is_empty()", +]; +const LOOKBACK: usize = 20; + +fn rust_files(dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + rust_files(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push(path); + } + } +} + +/// Files that only exist in test builds: declared as `mod name;` right after a `#[cfg(test)]`-like attribute, or marked `#![cfg(test)]`. +fn test_only(files: &[PathBuf]) -> Vec { + let mut gated = Vec::new(); + for file in files { + let text = fs::read_to_string(file).unwrap_or_default(); + if text.lines().take(40).any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test")) { + gated.push(file.clone()); + } + let lines: Vec<&str> = text.lines().collect(); + for (index, line) in lines.iter().enumerate() { + let trimmed = line.trim_start(); + let declared = trimmed.strip_prefix("pub(crate) mod ").or_else(|| trimmed.strip_prefix("pub(super) mod ")).or_else(|| trimmed.strip_prefix("pub mod ")).or_else(|| trimmed.strip_prefix("mod ")); + let Some(name) = declared.and_then(|rest| rest.strip_suffix(';')) else { continue }; + let above = lines[index.saturating_sub(3)..index].join(" "); + if above.contains("cfg(test)") || above.contains("cfg(all(test") || above.contains("cfg(any(test") { + let dir = file.parent().unwrap(); + gated.push(dir.join(format!("{name}.rs"))); + gated.push(dir.join(name).join("mod.rs")); + // `#[path = "other_name.rs"] mod name;` + if let Some(path) = above.split("#[path = \"").nth(1).and_then(|rest| rest.split('"').next()) { + gated.push(dir.join(path)); + } + } + } + } + gated +} + +/// The first string literal of the macro call starting at `at` in `lines`, or `None`. +fn first_literal(lines: &[&str], at: usize, column: usize) -> Option { + let mut text = String::from(&lines[at][column..]); + for line in lines.iter().skip(at + 1).take(2) { + text.push(' '); + text.push_str(line); + } + let start = text.find('"')? + 1; + Some(text[start..].chars().take(12).collect()) +} + +fn findings(root: &Path) -> Vec { + let mut files = Vec::new(); + for crate_dir in ["crates/leleka-runtime/src", "crates/cuda-driver/src"] { + rust_files(&root.join(crate_dir), &mut files); + } + let exempt = test_only(&files); + let mut bad = Vec::new(); + for file in &files { + if exempt.contains(file) { + continue; + } + let text = fs::read_to_string(file).unwrap_or_default(); + let lines: Vec<&str> = text.lines().collect(); + // from the first `#[cfg(test)] mod tests` on, the rest of the file is test code + let end = lines + .iter() + .enumerate() + .position(|(i, l)| l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod "))) + .unwrap_or(lines.len()); + for (index, line) in lines.iter().enumerate().take(end) { + let Some(column) = ["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min() else { continue }; + let Some(literal) = first_literal(&lines, index, column) else { continue }; + if !(literal.starts_with("DBG") || literal.starts_with("PROBE")) { + continue; + } + let from = index.saturating_sub(LOOKBACK); + let context = lines[from..=index].join("\n"); + if !GUARDS.iter().any(|guard| context.contains(guard)) { + bad.push(format!("{}:{}: {}", file.strip_prefix(root).unwrap_or(file).display(), index + 1, line.trim())); + } + } + } + bad +} + +#[test] +fn every_production_dbg_or_probe_print_is_behind_a_switch() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bad = findings(&root); + assert!( + bad.is_empty(), + "these DBG/PROBE prints fire without LELEKA_BRINGUP_TRACE or a switch of their own; route them through bringup_trace! (or add the switch to GUARDS if it is a real opt-in):\n{}", + bad.join("\n") + ); +} + +#[test] +fn the_scan_sees_the_prints_it_is_meant_to_guard() { + // A scan that finds nothing would pass forever: make sure it reads the files and recognises both shapes. + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + rust_files(&root.join("crates/leleka-runtime/src"), &mut files); + let total: usize = files + .iter() + .map(|f| fs::read_to_string(f).unwrap_or_default().matches("DBG").count()) + .sum(); + assert!(total > 20, "only {total} DBG mentions: is the source path wrong?"); + let lines = [" eprintln!(\"DBG x {}\", 1);", " eprintln!(", " \"PROBE y\","]; + assert_eq!(first_literal(&lines, 0, 14).as_deref(), Some("DBG x {}\", 1")); + assert_eq!(first_literal(&lines, 1, 14).as_deref(), Some("PROBE y\",")); +} diff --git a/docs/port-remaining.md b/docs/port-remaining.md index 85f6c14d..c5d00d03 100644 --- a/docs/port-remaining.md +++ b/docs/port-remaining.md @@ -136,7 +136,104 @@ before any driver call. Not done (needs nvcc and a GPU): compiling the three `.c the smokes. The "misc" kernels of `mmq_original_prefill_misc.cu` already have their owner (`mmq_original_prefill_misc.rs`), so only the poison fill of `device.cu` was open. -## 5-7. Not started +## 5. KAR routed / prefill experts: feasibility note (decision: not ported) -* 5 (KAR routed/prefill experts): `engine/strata/src/core/experimental_routed.hpp` and `prefill/experimental_experts.hpp` are not in the imported tree (only `docs/experiments/2026-10-14-experimental-modes-port.md` names them as unported local patches), so there is no source to transcribe; the local-patch source has to be located first. -* 6 (multi-GPU verify stage handoff) and 7 (`/api/requests` monitor, extra `/metrics` fields): open. +**What the brief calls them.** The Original-side local patch of 2026-10-06/07 that lets an explicit, default-off experimental arm of the +C++ engine take every routed expert row from the KAR GPU component (`gpu/kar`, the "KAR miss callback") instead of from the native bank: +`STRATA_NEXT_KAR_PREFILL=1` (prefill dispatches the grouped expert rows to the callback) and `STRATA_NEXT_KAR_ALL_ROUTED=1` (additionally the +target's native routed storage, cache slots and staging rings are not allocated). The patch's own provenance note calls it "an experimental +quality arm, not full compressed-model residency or a qualified speedup". + +**What is missing from the imported tree (this branch).** `engine/strata/` is the pinned upstream snapshot and has none of the patch: + +* `include/strata/core/experimental_routed.hpp` (the admission profile `validate_experimental_routed_profile`, `dispatch_experimental_all_routed` + with its input/output validation, `dispatch_experimental_routed_window`), +* `include/strata/prefill/experimental_experts.hpp` (`dispatch_grouped_experts`, the grouped, batch-of-8 prefill dispatch), +* the call-site hunks: `src/core/verify.cpp` (+52 lines: the early multi-token callback before any native lookahead, an absent native + tier), `src/prefill/prefill.cpp` (+123: the allocation mode that omits the routed GU/MMQ/staging buffers), `src/core/expert_source.cpp`, + `src/program/generate.cpp` (+93: option parsing and admission), and the header edits (`expert_source.hpp`, `verify.hpp`, `prefill.hpp`), +* the contract tests `tests/kar-all-routed-contract.cpp`, `tests/kar-prefill-contract.cpp` with their scripts, and the CI workflow. + +**The earlier note ("the local-patch source has to be located first") is out of date: it is located.** It exists in this repository's object +store, only on the remote-tracking branch `origin/codex/stra10-bounded-kar-cache-gitea` (commits `33f075f` "explicit bounded batched prefill +backend" and `b6563e3` "isolate target native routed storage in explicit mode", based on the import commit `4013e0c`; neither is an ancestor of +this branch). `git show b6563e3:engine/strata/include/strata/core/experimental_routed.hpp` prints it and `git diff 4013e0c b6563e3 -- engine/strata` +is the whole patch (about 230 changed lines in the four `.cpp` files plus the two headers). The Rust port has no counterpart of the `gpu/kar` +miss callback either: what exists is `KarExpertSource::routed_mlp` (KAR level 2..5 decode on CUDA, `NativeBackendConfig::kar_expert_source`), +which feeds the preview path's `MoeExpertStage`, not the Original serve path (verifier window MoE, grouped prefill MMQ, CPU pool). + +**What can be done from what exists.** Only the pure half: the two headers are about 200 lines of host-only contracts (flag parsing, the +admission profile, finite/range/duplicate-expert validation, `kind == 3` ownership, grouping offsets, the batch limit of 8), and the authors' +C++ contract tests can be compiled from the git objects on a dev machine to produce goldens, the way the other `experimental-ref` oracles were +made. That is about a day of work with a full oracle, and it would be dead code: the consumers (a native-bank-free verifier window and a +native-bank-free prefill carve) live in the sealed GPU paths and cannot be validated without a GPU run. + +**Decision.** Do not port. The arm is a quality experiment of the earlier Strata-next line. It requires `--expert-cache 0`, `--pcie-frac 0`, one +GPU, a fixed prefill chunk and no CPU pool (each a throughput loss against the product configuration), it keeps the MTP drafter's native experts +anyway (so it can claim no VRAM saving), and nothing in the charter's milestones consumes it. If a compressed-residency product is wanted later, the +entry point is `KarExpertSource` plus a KAR owner in `original_verify_window_moe*.rs` and `original_moe_prompt_device.rs`, designed against the +Rust owners rather than transcribed from the C++ patch; keep the patch only as a reference for the contracts above. + +## 6. Multi-GPU verify stage handoff: feasibility note (decision: not done) + +**Scope in the Original.** `Verifier::set_stage(layer_begin, layer_end, handoff_in, handoff_out)` and `set_next` (`verify.hpp:104-118`, +`verify.cpp:191,436,853,1230,1395-1423`): a verifier runs layers `[lb, le)` of every window. A stage that does not start at layer 0 reads the +previous stage's residual `R` (hc x n_embd), pending write `bo` (n_embd) and `inject` (hc) per token (`handoff_floats`) from mapped pinned +memory instead of embedding the tokens; one that does not end at the last layer writes them and has no head; `run`, `commit`, `wait_commit`, +`window_logprobs` and `copy_logits` chain into `next_`. It is one piece of the layer split of `docs/MULTI_GPU.md`. + +**What the port has.** `OriginalVerifier` loops all 48 layers and has no stage bounds, no hand-off buffers and no next-stage owner +(`PORT-GAPS-MODE17.md`). Around it the layer split needs the rest of that document, none of which exists in Rust: a second CUDA context with its +own streams, graphs and doorbells (the driver `Context` is thread-confined and `GPU_ORDINAL` is process-global, so two contexts on one thread need +explicit context switching), a session and KV per stage (`session.cpp`), a prompt pipeline across stages (a chunk flowing through the cards, 1.5 GB +of prefill buffers each), an expert cache and adaptive swaps per stage, the MTP drafter and the head on the last stage, per-stage checkpoints for +the conversation and prefix caches, the `--layer-split auto` placement search over the expert profile, and the WDDM pin caps. + +**Cost and value.** The verifier slice alone (stage bounds in the window planners, the hand-off read and write, forwarding on the last stage) is +small, perhaps two days, and it has a one-GPU check: the Original runs both stages on one device (`--layer-split K --split-device 0`) and compares +bit for bit with the unsplit window, so the handoff could be validated on the single RTX 5090. On its own it delivers nothing a user can run. The +usable feature is the whole list above: weeks of work that can only be qualified with two cards on one host (this project has one card per +machine: the 5090 server and the 3080 laptop), for a product whose targets are single-GPU hosts (the profiles are `rtx5090-32g` and +`rtx3080-16g`). The Original's own measurements say a second card helps when the routed experts do not fit the faster one (+18-20 % on +prompts, decode on par); the 5090 profile already keeps a 50 GB resident host bank and a VRAM expert tier. + +**Decision.** Nothing implemented. Revisit only if a two-card host becomes a product target; then do the verifier slice first, behind the +one-device bit-exact check, before any of the surrounding work. + +## 7. `/api/requests` monitor and the extra `/metrics` fields: done + +`control-plane/src/request_monitor.rs`, `hardware_view.rs`, `prometheus.rs` and `app.rs` `metrics_document`; the reference behaviour is +`Service.begin_request` / `request_records` / `metrics` in `engine/strata/serve/server.py` and `serve/test_monitor.py`. The contract, the +differences from Python and the Prometheus series are in `docs/api-contract.md` ("Monitor members, Prometheus text and `GET /api/requests`"). +Tests: the `request_monitor`, `hardware_view`, `prometheus` and `metrics` unit tests and `tests/backend_worker_http.rs` +(`the_request_monitor_*`, `metrics_carry_the_python_monitor_members_and_a_prometheus_view`). Not carried over: the `/api-monitor` HTML page and +per-request `queue_s` / `load_s` attribution. The telemetry block comes from NVML or, where `libnvidia-ml` cannot be loaded (WSL2, containers), +from polling `nvidia-smi` (`leleka-memory/src/smi.rs`). + +## 8. Bring-up diagnostics are silent in production + +Review of every `eprintln!`/`println!` compiled into the production libraries of `leleka-runtime` and `leleka-cuda-driver` (found with +`cargo clippy -p leleka-runtime -p leleka-cuda-driver --lib -- -A clippy::all -W clippy::print_stderr -W clippy::print_stdout`, which skips test +code): no `DBG` / `PROBE` / `PREFILL-*` print fires without an explicit opt-in. The unconditional ones were already routed through +`bringup_trace!` (`LELEKA_BRINGUP_TRACE`) by the earlier gating pass; what remains outside that macro is one of: + +| print | fires only under | +| --- | --- | +| `PREFILL-ALLOC`, `PREFILL-STALL`, `PREFILL-SITE` (`compute_drain.rs`) | `LELEKA_PREFILL_ALLOC_TRACE=1`, `LELEKA_PREFILL_STALL_TRACE=1` | +| `DBG mtp ... graph`, `DBG graph window/commit` (`mtp_original_full_drafter.rs`, `original_verify_schedule.rs`) | `LELEKA_SERVE_PROFILE` (`host_profile::enabled`) | +| `DBG profile`, `DBG window`, `DBG vram`, `DBG tier request` (`original_serve_profile.rs`, `original_serve_host.rs`, `original_serve_stack.rs`) | `LELEKA_SERVE_PROFILE` | +| `DBG spec-stats`, `DBG spec-trace` | `LELEKA_SPEC_STATS`, `LELEKA_SPEC_TRACE` | +| `DBG verify-profile` | `STRATA_VERIFY_PROFILE` | +| `DBG seed`, `DBG seed-coverage` | `LELEKA_SEED_TRACE` | +| `DBG ple` (`input.rs`) | `LELEKA_TRACE_PLE` | +| `DBG residual*`, the logprobs line (`original_serve_native.rs`) | `LELEKA_TRACE_RESIDUAL=`, `LELEKA_TRACE_LOGPROBS=` | +| `PREFILL-R` (`executor_original_prompt.rs`) | `LELEKA_TRACE_PREFILL_R` | +| `driver error: ...` (nine `driver_error` helpers) | `LELEKA_TRACE_DRIVER_ERRORS` | +| `PREFILL-PROFILE`, `PREFILL-COMMANDS` (`prefill_profile.rs`) | `LELEKA_BRINGUP_TRACE` (its own `enabled()`) | +| cpu pool notices and the router-lookahead summary (`original_serve_pool.rs`) | the non-default pool modes (`LELEKA_CPU_POOL`, `LELEKA_CPU_POOL_FENCE=job`, `LELEKA_CPU_POOL_LOOKAHEAD=on`) | +| `OriginalNativeOutput::load: ... refused`, `DenseWeightCache::new_original_prompt_capacity: ... refused`, `leleka-ple-reader-unavailable`, `native embedding: cannot pin`, `resident RAM budget ...` | operator-facing notices on a refusal or a fallback, not diagnostics (kept) | + +The test-only smokes (`backend_original_serve_*smoke*.rs`, `_replay.rs`, `_arms.rs`, `*_gpu.rs`) print `DBG`/`PROBE` lines as their evidence and are not +compiled outside `cargo test`. A source scan, `crates/leleka-runtime/tests/bringup_prints_gated.rs`, now fails when a production `DBG`/`PROBE` print has +neither `bringup_trace!` nor one of the opt-in switches in the lines above it. The only source change of this pass is one comment in +`original_serve_stack.rs`; behaviour is unchanged. diff --git a/docs/port-status.md b/docs/port-status.md index e721dcd0..652a41b8 100644 --- a/docs/port-status.md +++ b/docs/port-status.md @@ -100,7 +100,7 @@ A `.cu` file may sit at **S** while its Rust host side sits at **L** or **O**; b | CPU expert pool | `crates/native-cpu-expert` | full source, Linux x86-64 only | L; parity binary exists, not run | | Expert cache, slots, stager, file source, STRP profile, adaptive policy | `cuda-driver/src/original_{expert_cache,expert_slots,expert_stager,file_expert_source}*.rs`, `leleka-runtime/.../cache_*.rs`, `original_cache_startup.rs` | full for the host owners; RAM-source and non-Linux paths absent | L, T for pure policy | | `pinned.cu` shared-file arena | `model-format/src/pinned_arena_plan.rs` | planner (header, registration plan, parallel load) | T | -| Layer split, remote experts, `set_stage` handoff | `experimental-ref/src/remote_experts.rs` (planner only) | planner; second-GPU context, staging and launches absent | O for selection, grouping, metadata, scatter | +| Layer split, remote experts, `set_stage` handoff | `experimental-ref/src/remote_experts.rs` (planner only) | planner; second-GPU context, staging and launches absent; handoff not done by decision (`docs/port-remaining.md` section 6) | O for selection, grouping, metadata, scatter | ## MTP, verifier, prefill and session @@ -126,7 +126,7 @@ A `.cu` file may sit at **S** while its Rust host side sits at **L** or **O**; b | KV streaming planner and CLOCK resolver | `experimental-ref/src/kv_stream.rs`, `experimental_kv_stream.cu` | references full | O (480 plan cases + resolver) | | `kv_q8.cu` INT8 append, `kv_stream.cu` resolve/copy/reset/stage, `--kv-resident` (serve path) | `qsa_prompt_kv.cu`, `mtp_original_kv.cu`, `qsa_prompt_resolver.{cu,rs}`, `qsa_resident_transport.rs`, `serving_context::configure_kv_resident`, `StackConfig::{kv_format, kv_resident}` | full for INT8; fp16/q4_0/k8v4 excluded on the serve path (`docs/kv-streaming.md`) | G: `kv_stream_gpu` model-free proofs on the RTX 5090 (2026-10-16); real-model long-context run pending | | Experimental driver facade, opt-in, pins | `cuda-driver/src/experimental{,_gpu,_gpu_smoke}.rs`, `leleka-runtime/src/experimental.rs` | full; every mode refuses at Load until the consumer is wired (`FORWARD_CONSUMER_WIRED`) | L; entry signatures cross-checked against the `.cu` text (T) | -| `experimental_routed.hpp`, `experimental_experts.hpp` prefill patches | none | absent | not applicable | +| `experimental_routed.hpp`, `experimental_experts.hpp` prefill patches | none | absent from the imported tree; the patch source is in the git objects of `origin/codex/stra10-bounded-kar-cache-gitea` (`b6563e3`); decision: not ported (`docs/port-remaining.md` section 5) | not applicable | ## What is open for every row From 02abdddf700168f286d2d4a35d94728170f68057 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:42:04 +0100 Subject: [PATCH 05/10] tests: real nvidia-smi output as fixtures; /api/requests is behind the API key Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/auth.rs | 1 + crates/leleka-memory/src/smi.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/control-plane/src/auth.rs b/control-plane/src/auth.rs index 7ede76df..4b7d3420 100644 --- a/control-plane/src/auth.rs +++ b/control-plane/src/auth.rs @@ -182,6 +182,7 @@ mod tests { for path in [ "/status", "/metrics", + "/api/requests", "/ready", "/v1/responses", "/admin/drain", diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index d77d5e0d..f973c4a0 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -144,6 +144,18 @@ mod tests { assert_eq!(sample.name.as_deref(), Some("NVIDIA GeForce RTX 5090")); } + #[test] + fn output_captured_from_real_drivers_parses() { + // `nvidia-smi --query-gpu= --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02, Linux) + let server = parse_csv("0, 94, 21, 31606, 32607, 271.40, 2887, 58, NVIDIA GeForce RTX 5090\n", 0).unwrap(); + assert_eq!((server.util_pct, server.vram_used_mib, server.vram_total_mib), (94, 31606, 32607)); + assert_eq!((server.power_w, server.sm_clock_mhz, server.temp_c), (Some(271.4), Some(2887), Some(58))); + // and on the RTX 3080 Laptop through the Windows driver (the path WSL2 takes) + let laptop = parse_csv("0, 0, 100, 0, 16384, 32.83, 1545, 59, NVIDIA GeForce RTX 3080 Laptop GPU\n", 0).unwrap(); + assert_eq!((laptop.vram_used_mib, laptop.vram_total_mib, laptop.temp_c), (0, 16384, Some(59))); + assert_eq!(laptop.name.as_deref(), Some("NVIDIA GeForce RTX 3080 Laptop GPU")); + } + #[test] fn placeholders_become_missing_values_not_zeros() { // a laptop board under WSL2: power and clock are not reported From 27d070162d0db5af0b99a510a23c3ef1cf8482f1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:42:59 +0100 Subject: [PATCH 06/10] docs: telemetry GPU fallback and request block; clippy: collapse a let-chain Co-Authored-By: Claude Sonnet 5.5 --- crates/leleka-memory/src/smi.rs | 8 ++++---- docs/deploy.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index f973c4a0..708afb41 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -118,10 +118,10 @@ pub fn probe_with(binary: std::path::PathBuf, index: u32) -> Box Opt let last: Mutex)>> = Mutex::new(None); Box::new(move || { let mut last = last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some((at, sample)) = last.as_ref() { - if at.elapsed() < MIN_INTERVAL { - return sample.clone(); - } + if let Some((at, sample)) = last.as_ref() + && at.elapsed() < MIN_INTERVAL + { + return sample.clone(); } let sample = query(&binary, index); *last = Some((Instant::now(), sample.clone())); diff --git a/docs/deploy.md b/docs/deploy.md index 3c38b27d..d003c122 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -136,12 +136,12 @@ gRPC `Snapshot.telemetry_json` -> the gateway -> `GET /v1/status` `machine` -> ` | block | figures | | --- | --- | -| `gpu` | utilisation %, memory-bus %, VRAM used/total (NVML, loaded with `dlopen`; absent when NVML is not installed), power, SM clock | +| `gpu` | utilisation %, memory-bus %, VRAM used/total, power, SM clock, temperature, board name (NVML, loaded with `dlopen`; where `libnvidia-ml` cannot be loaded, WSL2 and containers, the engine polls `nvidia-smi` instead, at most every 2 s; absent when neither exists) | | `ram` | host total/available, engine resident and pinned, swap in use | | `cpu` | engine CPU in busy cores (of the cores this process may use), whole-system busy % | | `throughput` | prefill tok/s (last request, running average, lifetime) and decode tok/s (same, plus the live rate of the request in flight) | | `cache` | requests and how many reused a checkpoint, prompt tokens reused of all, the last request's reused/prompt tokens | -| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode | +| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode; `request` (prompt and generated tokens, seconds) while one runs | Prefill rate counts the tokens actually prefilled (prompt minus reused). Rates are `null` until a request has been measured. From 1a77b2805c3665d3187b639a6fe6d6e31796877e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:57:51 +0100 Subject: [PATCH 07/10] metrics: history is the last 60 health-tick samples, documented as such Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/hardware_view.rs | 17 +++++++++-------- docs/api-contract.md | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/control-plane/src/hardware_view.rs b/control-plane/src/hardware_view.rs index 5b3ce37d..e6a48c72 100644 --- a/control-plane/src/hardware_view.rs +++ b/control-plane/src/hardware_view.rs @@ -9,8 +9,9 @@ use std::{collections::VecDeque, sync::Mutex, time::{Duration, Instant}}; use serde_json::{Map, Value, json}; -/// Seconds of history per series, one sample per second (the Monitor's minute). -pub const HISTORY_SECONDS: usize = 60; +/// Samples kept per series. The worker copies the telemetry document on its health tick (2 s by default), so 60 samples are about two +/// minutes (the Python Monitor samples every second and keeps a minute). +pub const HISTORY_SAMPLES: usize = 60; /// Samples closer than this are the same second. const MIN_GAP: Duration = Duration::from_millis(900); const MIB: f64 = 1_048_576.0; @@ -83,7 +84,7 @@ pub fn hardware_static(document: &Value) -> Value { }) } -/// A minute of the headline series, one sample a second, oldest first. A sample the engine did not report is `null`. +/// The last [`HISTORY_SAMPLES`] samples of the headline series, oldest first. A sample the engine did not report is `null`. #[derive(Default)] pub struct Series { inner: Mutex, @@ -96,7 +97,7 @@ struct Inner { } impl Series { - /// Add the sample `now` (the result of [`hardware_now`]) unless the previous one is less than a second old. + /// Add the sample `now` (the result of [`hardware_now`]) unless the previous one is less than a second old (a burst of ticks is one sample). pub fn push(&self, now: &Value) { let Ok(mut inner) = self.inner.lock() else { return }; let at = Instant::now(); @@ -106,7 +107,7 @@ impl Series { inner.last = Some(at); for key in SERIES { let row = inner.rows.entry(key).or_default(); - if row.len() == HISTORY_SECONDS { + if row.len() == HISTORY_SAMPLES { row.pop_front(); } row.push_back(now.get(key).cloned().unwrap_or(Value::Null)); @@ -169,7 +170,7 @@ mod tests { } #[test] - fn the_series_keeps_a_minute_and_one_sample_per_second() { + fn the_series_keeps_the_last_sixty_samples_and_drops_a_burst() { let series = Series::default(); let now = hardware_now(&document("idle")); series.push(&now); @@ -177,13 +178,13 @@ mod tests { let snapshot = series.snapshot(); assert_eq!(snapshot["gpu_util"].as_array().unwrap().len(), 1); // fill past the bound by rewinding the gate between pushes - for _ in 0..HISTORY_SECONDS + 5 { + for _ in 0..HISTORY_SAMPLES + 5 { series.inner.lock().unwrap().last = None; series.push(&now); } let snapshot = series.snapshot(); for key in SERIES { - assert_eq!(snapshot[key].as_array().unwrap().len(), HISTORY_SECONDS, "{key}"); + assert_eq!(snapshot[key].as_array().unwrap().len(), HISTORY_SAMPLES, "{key}"); } // a series the engine did not report is null, not zero assert!(snapshot["gpu_temp"].as_array().unwrap().iter().all(|v| v == 61)); diff --git a/docs/api-contract.md b/docs/api-contract.md index 18c5f7f2..beab46fb 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -312,7 +312,7 @@ native ones above, which are unchanged (`schema_version` stays 1): | `live` | `state` (`idle`, `reading`, `generating`, or the worker state while it is not ready), `active`, `queued` (generations waiting for the engine), `phase`, `prompt_tokens`, `generated`, `elapsed_s`, `tok_s`, `tok_s_mean`, `prefill_tok_s_mean`; `prompt_read`, `prompt_total`, `max_tokens` and `tok_s_window_s` are `null` (the runtime does not report them) | | `requests`, `requests_kept` | the last 12 settled generations, newest first (`?requests=all`: every one kept, up to 500): `time`, `duration_s`, `finish` (`stop`, `length`, `cancel`, `disconnect`, `error`), `prompt_tokens`, `reused`, `output_tokens`, `engine_generated`, `prompt_ms`, `decode_ms`, `decode_tok_s`, `hit_rate`, `drafts_offered`, `drafts_accepted`; `null` where the engine did not say or the attempt had no DONE. Counts and timings only, no payload | | `totals` | since the process started: `requests`, `prompt_tokens`, `reused`, `output_tokens`, `prompt_ms`, `decode_ms`, `drafts_offered`, `drafts_accepted` | -| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and a minute of the headline series, one sample a second. A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) | +| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and `history`, the last 60 samples of the headline series (one per engine health tick, 2 s by default; a burst of ticks within a second counts once). A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) | | `telemetry`, `time` | the raw telemetry document (the same as `/v1/status` `machine`, without its age) and the wall-clock second | The GPU block comes from NVML; where `libnvidia-ml` cannot be loaded (WSL2, containers without the management library) the engine polls From 9f26eee613ad75dbf179260429c26f2694c9b011 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 12:59:45 +0100 Subject: [PATCH 08/10] deploy: an inherited sealed archive is not charged to the resource planner twice With --kar-fd the memfd is already missing from MemAvailable; compute() charged the archive again and sent a host that fits to the mapped form. The reconfigure planner shares the correction. Co-Authored-By: Claude Sonnet 5.5 --- crates/deploy/src/plan.rs | 4 +++- crates/deploy/src/reconfigure.rs | 7 ++----- crates/deploy/src/resources.rs | 25 +++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index 74319c02..a39aca3f 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -248,7 +248,9 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); let mut engine_env = BTreeMap::new(); let base_profile = p.clone(); - let resources = crate::resources::compute(&facts, gpu, p, opts.preset); + // An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. + let planned_host = if opts.kar_fd.is_some() { crate::resources::with_resident_archive(&facts) } else { facts.clone() }; + let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some()); needs.resources = Some(resources); if needs.expert_profile == Some(ExpertProfileState::Valid) diff --git a/crates/deploy/src/reconfigure.rs b/crates/deploy/src/reconfigure.rs index 08c6a3fa..638d6200 100644 --- a/crates/deploy/src/reconfigure.rs +++ b/crates/deploy/src/reconfigure.rs @@ -20,7 +20,7 @@ use crate::{ config::{RunConfig, to_file_text}, facts::{Facts, Gpu}, layout::Paths, - profile::{ARCHIVE_BYTES, Profile}, + profile::Profile, resources::{self, CPU_WORKERS_ENV, Preset, ResourcePlan}, }; @@ -342,10 +342,7 @@ pub fn plan( base.validate()?; let mut profile = base.clone(); - let mut seen = facts.clone(); - if archive_resident { - seen.memory.available = seen.memory.available.saturating_add(ARCHIVE_BYTES); - } + let seen = if archive_resident { resources::with_resident_archive(facts) } else { facts.clone() }; let gpu = gpu_of(&seen, config.gpu).cloned(); let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset); if !resources.problems.is_empty() { diff --git a/crates/deploy/src/resources.rs b/crates/deploy/src/resources.rs index edea8b05..0274d1d9 100644 --- a/crates/deploy/src/resources.rs +++ b/crates/deploy/src/resources.rs @@ -94,6 +94,15 @@ pub fn workstation_ram_target(total: u64) -> u64 { } } +/// The host as the planner should see it when the sealed archive memfd is already resident (an inherited `--kar-fd`, or the +/// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the +/// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not. +pub fn with_resident_archive(facts: &Facts) -> Facts { + let mut facts = facts.clone(); + facts.memory.available = facts.memory.available.saturating_add(ARCHIVE_BYTES); + facts +} + pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan { let mut plan = ResourcePlan { preset, @@ -335,6 +344,22 @@ mod tests { assert!(env.is_empty()); } + #[test] + fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() { + // the server with the 51.5 GiB memfd already resident: 121 GiB total, 9 GiB available (no other consumer left) + let resident = host(32, 121, 9); + let charged_twice = compute(&resident, Some(&gpu(32607, 32100)), &server(), Preset::Dedicated); + assert!(charged_twice.mapped_resident_gib.is_some(), "without the correction the pinned form looks impossible"); + let corrected = compute(&with_resident_archive(&resident), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated); + assert_eq!(corrected.mapped_resident_gib, None, "the archive is already paid for: only the engine's 3 GiB remain"); + assert!(corrected.ram_expected_free_after_bytes.is_some()); + // a host that really lacks the engine's own memory is still sent to the mapped form + let tiny = host(32, 121, 2); + assert!(compute(&with_resident_archive(&tiny), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated).mapped_resident_gib.is_some()); + // saturating, not wrapping + assert!(with_resident_archive(&host(1, 1, u64::MAX / GIB)).memory.available >= u64::MAX / 2); + } + #[test] fn unknown_core_count_leaves_the_engine_default() { let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); From da6f8f2f48db55123686258381c27c8e9f7f0e79 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 13:05:12 +0100 Subject: [PATCH 09/10] metrics: empty hardware blocks and a null telemetry member while the engine publishes nothing Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/memory_view.rs | 2 +- control-plane/tests/backend_worker_http.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/control-plane/src/memory_view.rs b/control-plane/src/memory_view.rs index 7fb6b687..6e62210d 100644 --- a/control-plane/src/memory_view.rs +++ b/control-plane/src/memory_view.rs @@ -64,7 +64,7 @@ impl MemoryView { pub fn hardware(&self) -> (Value, Value, Value, Value) { let document = self.telemetry_status(); if document.is_null() { - return (Value::Null, json!({}), json!({}), self.series.snapshot()); + return (json!({}), json!({}), Value::Null, self.series.snapshot()); } ( crate::hardware_view::hardware_now(&document), diff --git a/control-plane/tests/backend_worker_http.rs b/control-plane/tests/backend_worker_http.rs index 9b8dc3b1..30f78fd7 100644 --- a/control-plane/tests/backend_worker_http.rs +++ b/control-plane/tests/backend_worker_http.rs @@ -1593,6 +1593,11 @@ async fn the_request_monitor_is_off_by_default_and_keeps_nothing() { assert!(stack.state.monitor.summaries().is_empty()); let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap(); assert_eq!(metrics["engine"]["api_monitor"], false); + // an engine that publishes no telemetry (yet): empty hardware blocks, no raw document, the rest of the document intact + assert_eq!(metrics["hardware"], json!({})); + assert_eq!(metrics["hardware_static"], json!({})); + assert!(metrics["telemetry"].is_null()); + assert_eq!(metrics["requests_kept"], 1); stack.finish().await; } From 1f17b5d2d7830a2432498d954827d8a3cf09fd63 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 13:29:22 +0100 Subject: [PATCH 10/10] supervisor: say so in the answer when the previous engine cannot be restored after a refused reconfigure Co-Authored-By: Claude Sonnet 5.5 --- crates/deploy/src/supervisor.rs | 9 ++++++++- crates/deploy/tests/e2e.rs | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index 3ba14937..8fdf0e50 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -1225,7 +1225,14 @@ impl Supervisor { // 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 = self.start_engine(gateway).await?; + 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); diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs index cf8f839f..7d062959 100644 --- a/crates/deploy/tests/e2e.rs +++ b/crates/deploy/tests/e2e.rs @@ -1189,4 +1189,18 @@ mod reconfigure_flow { assert!(!stopped.status.success()); assert!(String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"), "{}", String::from_utf8_lossy(&stopped.stderr)); } + + #[test] + fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer() { + let mut service = start("reconf-lost"); + let fixture = &service.fixture; + // from now on no engine starts at all: the new one fails, and so does the restored one + fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap(); + let outcome = ask(fixture, &request("lost", Some(4), None, json!({}), false), Duration::from_secs(120)); + assert_eq!(outcome.state, State::Failed, "{}\n{}", outcome.message, fixture.logs()); + assert!(outcome.message.contains("could not be restored"), "{}", outcome.message); + let status = wait_exit(&mut service.supervisor, Duration::from_secs(60)).expect("the supervisor must give up"); + assert_eq!(status.code(), Some(1)); + assert_eq!(fixture.status().unwrap()["phase"], "failed"); + } }