From 7da6a63e612bc80ee899cd5aecedfcc4dd2d4734 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 18 Oct 2026 01:20:21 +0200 Subject: [PATCH] feat(memory): leleka-memory crate: procfs/cgroup/PSI facts, inventory, load ledger, budget planner, pressure monitor, governor, memfd lock/residency guard, census Model-free and CUDA-free. 64 unit tests (parsers, planner refusals with numbers, shed order and hysteresis, admission, sampler thread, mlock/mincore/madvise over a descriptor, flatness check). Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 9 + Cargo.toml | 4 +- crates/leleka-memory/Cargo.toml | 24 + crates/leleka-memory/src/census.rs | 204 ++++++ crates/leleka-memory/src/governor.rs | 918 ++++++++++++++++++++++++++ crates/leleka-memory/src/host.rs | 277 ++++++++ crates/leleka-memory/src/inventory.rs | 307 +++++++++ crates/leleka-memory/src/ledger.rs | 180 +++++ crates/leleka-memory/src/lib.rs | 22 + crates/leleka-memory/src/lock.rs | 398 +++++++++++ crates/leleka-memory/src/plan.rs | 560 ++++++++++++++++ crates/leleka-memory/src/pressure.rs | 365 ++++++++++ crates/leleka-memory/src/procfs.rs | 408 ++++++++++++ 13 files changed, 3674 insertions(+), 2 deletions(-) create mode 100644 crates/leleka-memory/Cargo.toml create mode 100644 crates/leleka-memory/src/census.rs create mode 100644 crates/leleka-memory/src/governor.rs create mode 100644 crates/leleka-memory/src/host.rs create mode 100644 crates/leleka-memory/src/inventory.rs create mode 100644 crates/leleka-memory/src/ledger.rs create mode 100644 crates/leleka-memory/src/lib.rs create mode 100644 crates/leleka-memory/src/lock.rs create mode 100644 crates/leleka-memory/src/plan.rs create mode 100644 crates/leleka-memory/src/pressure.rs create mode 100644 crates/leleka-memory/src/procfs.rs diff --git a/Cargo.lock b/Cargo.lock index 44baf0e7..967feecd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1044,6 +1044,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "leleka-memory" +version = "0.1.0" +dependencies = [ + "libc", + "serde", + "serde_json", +] + [[package]] name = "leleka-model-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 42fbd853..2422d3c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/deploy", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/runtime-client", "crates/tokenizer", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/crates/leleka-memory/Cargo.toml b/crates/leleka-memory/Cargo.toml new file mode 100644 index 00000000..30f9b604 --- /dev/null +++ b/crates/leleka-memory/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "leleka-memory" +version = "0.1.0" +description = "Host and device memory inventory, budget governor, pressure monitor and residency guard for the Leleka runtime (model-free, no CUDA)" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["float_roundtrip"] } + +[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies] +libc = "=0.2.190" + +# The workspace forbids unsafe code. This crate denies it and lets exactly one module (`lock`: mmap/mlock/mincore/madvise +# over a file descriptor's pages, never dereferenced) opt in. Everything else (procfs parsing, planning, the pressure state +# machine, the inventory) is safe Rust and runs under Miri. +[lints.rust] +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "deny" + +[lints.clippy] +all = "warn" diff --git a/crates/leleka-memory/src/census.rs b/crates/leleka-memory/src/census.rs new file mode 100644 index 00000000..f61a4980 --- /dev/null +++ b/crates/leleka-memory/src/census.rs @@ -0,0 +1,204 @@ +//! The process census and the "flat after warm-up" check of the soak tests: RSS, swap, pinned and locked bytes, +//! threads, file descriptors and (when the runtime supplies it) device memory, sampled between requests. +//! +//! Growth is judged between the mean of the first and of the last quarter of the post-warm-up samples, so one noisy +//! reading (a request in flight, a freed block not yet returned to the OS) does not fail a run, while a leak of a few +//! kilobytes per request over hundreds of requests does. + +use crate::host::{HostFacts, ProcSource}; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Census { + pub rss: u64, + pub swap: u64, + pub pinned: u64, + pub locked: u64, + pub threads: u64, + pub fds: u64, + pub available: u64, + pub shmem: u64, + /// Used VRAM as the driver reports it (`total - free`), if known. + pub device_used: Option, + /// Bytes the context accounts as allocated, if known. + pub device_accounted: Option, +} + +impl Census { + pub fn take(src: &dyn ProcSource) -> Self { + let f = HostFacts::probe(src); + Self { + rss: f.status.vm_rss.unwrap_or(0), + swap: f.status.vm_swap.unwrap_or(0), + pinned: f.status.vm_pin.unwrap_or(0), + locked: f.status.vm_lck.unwrap_or(0), + threads: f.status.threads.unwrap_or(0), + fds: f.open_fds.unwrap_or(0) as u64, + available: f.effective_available().unwrap_or(0), + shmem: f.meminfo.shmem.unwrap_or(0), + device_used: None, + device_accounted: None, + } + } + pub fn with_device(mut self, used: u64, accounted: u64) -> Self { + self.device_used = Some(used); + self.device_accounted = Some(accounted); + self + } +} + +/// How much growth after warm-up is tolerated, per series. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Tolerances { + pub rss: u64, + pub swap: u64, + pub pinned: u64, + pub locked: u64, + pub threads: u64, + pub fds: u64, + pub device: u64, +} + +impl Default for Tolerances { + /// RSS may wander by 256 MiB (allocator fragmentation, a cache still filling toward its budget is NOT flat and must + /// be excluded by the caller's warm-up); pinned, locked, threads, descriptors and device bytes must not grow. + fn default() -> Self { + Self { rss: 256 << 20, swap: 64 << 20, pinned: 0, locked: 0, threads: 0, fds: 2, device: 64 << 20 } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Drift { + pub series: &'static str, + pub first_quarter_mean: f64, + pub last_quarter_mean: f64, + pub growth: f64, + pub tolerance: u64, + pub ok: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct FlatReport { + pub samples: usize, + pub warmup: usize, + pub drifts: Vec, + pub ok: bool, +} + +impl std::fmt::Display for FlatReport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + writeln!(f, "flatness over {} samples after {} warm-up: {}", self.samples - self.warmup.min(self.samples), self.warmup, if self.ok { "FLAT" } else { "GROWING" })?; + for d in &self.drifts { + writeln!( + f, + " {:<9} first-quarter {:>16.0} last-quarter {:>16.0} growth {:>14.0} (tolerance {}) {}", + d.series, + d.first_quarter_mean, + d.last_quarter_mean, + d.growth, + d.tolerance, + if d.ok { "ok" } else { "GROWTH" } + )?; + } + Ok(()) + } +} + +fn quarter_means(values: &[f64]) -> Option<(f64, f64)> { + if values.len() < 8 { + return None; + } + let q = values.len() / 4; + let mean = |s: &[f64]| s.iter().sum::() / s.len() as f64; + Some((mean(&values[..q]), mean(&values[values.len() - q..]))) +} + +/// Judge a series of censuses taken between requests. Fewer than 8 post-warm-up samples is not a judgement: not ok. +pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatReport { + let tail = series.get(warmup..).unwrap_or(&[]); + let mut drifts = Vec::new(); + let mut add = |name: &'static str, get: &dyn Fn(&Census) -> Option, tolerance: u64| { + let values: Vec = tail.iter().filter_map(get).collect(); + if values.is_empty() && name.starts_with("device") { + return; + } + let drift = match quarter_means(&values) { + Some((a, b)) => Drift { series: name, first_quarter_mean: a, last_quarter_mean: b, growth: b - a, tolerance, ok: b - a <= tolerance as f64 }, + None => Drift { series: name, first_quarter_mean: 0.0, last_quarter_mean: 0.0, growth: 0.0, tolerance, ok: false }, + }; + drifts.push(drift); + }; + add("rss", &|c| Some(c.rss as f64), tol.rss); + add("swap", &|c| Some(c.swap as f64), tol.swap); + add("pinned", &|c| Some(c.pinned as f64), tol.pinned); + add("locked", &|c| Some(c.locked as f64), tol.locked); + add("threads", &|c| Some(c.threads as f64), tol.threads); + add("fds", &|c| Some(c.fds as f64), tol.fds); + add("device", &|c| c.device_used.map(|v| v as f64), tol.device); + add("device_acct", &|c| c.device_accounted.map(|v| v as f64), tol.device); + let ok = drifts.iter().all(|d| d.ok); + FlatReport { samples: series.len(), warmup, drifts, ok } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn series(n: usize, f: impl Fn(usize) -> Census) -> Vec { + (0..n).map(f).collect() + } + fn base() -> Census { + Census { rss: 60 << 30, pinned: 50 << 30, threads: 41, fds: 30, ..Census::default() } + } + + #[test] + fn a_flat_run_after_warmup_passes_even_with_noise() { + let s = series(100, |i| Census { rss: (60 << 30) + (i as u64 * 7919 % 1000) * 1024, ..base() }); + let r = check_flat(&s, 20, &Tolerances::default()); + assert!(r.ok, "{r}"); + } + + #[test] + fn warmup_growth_is_ignored_but_later_growth_is_caught() { + // fills a cache for 20 requests, then leaks 1 MiB per request + let s = series(120, |i| Census { rss: (60 << 30) + (i.min(20) as u64) * (200 << 20) + (i.saturating_sub(20) as u64) * (4 << 20), ..base() }); + let r = check_flat(&s, 20, &Tolerances::default()); + assert!(!r.ok); + assert!(r.drifts.iter().any(|d| d.series == "rss" && !d.ok), "{r}"); + } + + #[test] + fn a_leaked_thread_or_descriptor_or_pinned_page_fails() { + for leak in 0..3 { + let s = series(80, |i| { + let mut c = base(); + match leak { + 0 => c.threads += (i / 10) as u64, + 1 => c.fds += (i / 4) as u64, + _ => c.pinned += (i as u64 / 10) * 4096, + } + c + }); + let r = check_flat(&s, 10, &Tolerances::default()); + assert!(!r.ok, "leak {leak} not caught: {r}"); + } + } + + #[test] + fn device_series_are_judged_only_when_present() { + let s = series(60, |_| base()); + let r = check_flat(&s, 10, &Tolerances::default()); + assert!(r.ok && r.drifts.iter().all(|d| !d.series.starts_with("device"))); + let g = series(60, |_| base().with_device(20 << 30, 18 << 30)); + assert!(check_flat(&g, 10, &Tolerances::default()).ok); + let l = series(60, |i| base().with_device((20 << 30) + (i as u64) * (16 << 20), 18 << 30)); + assert!(!check_flat(&l, 10, &Tolerances::default()).ok); + } + + #[test] + fn too_few_samples_is_not_a_pass() { + let r = check_flat(&series(12, |_| base()), 10, &Tolerances::default()); + assert!(!r.ok); + assert!(!check_flat(&[], 0, &Tolerances::default()).ok); + } +} diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs new file mode 100644 index 00000000..46357d9c --- /dev/null +++ b/crates/leleka-memory/src/governor.rs @@ -0,0 +1,918 @@ +//! The memory governor: one object that owns the budget plan, watches the host, decides the pressure level, answers +//! "may this request start?" and tells the cache owners how much to shed, and publishes everything as one JSON report. +//! +//! Threads: the engine's owner thread calls [`Governor::admit`], [`Governor::directive`] and the `note_*` methods +//! (cheap, lock-light); one sampler thread ([`Governor::spawn_sampler`]) reads the host every `sample_interval`, +//! updates the level and publishes the report; status queries read the published text from [`published_report`]. + +use crate::census::Census; +use crate::host::{HostFacts, ProcSource, RealProc}; +use crate::inventory::Inventory; +use crate::ledger::Ledger; +use crate::lock::{LockDecision, LockMode, LockOutcome, plan_lock, residency_from_smaps}; +use crate::plan::{GIB, MIB, Plan, Policy, Refusal, gib}; +use crate::pressure::{Level, Monitor, Sample, Transition}; +use serde::Serialize; +use serde_json::json; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +const NONE: u64 = u64::MAX; + +/// Operator-visible settings; every one has an environment override (`LELEKA_MEMORY_*`). +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct GovernorConfig { + pub policy: Policy, + pub sample_interval_ms: u64, + pub lock_mode: LockMode, + /// Pull swapped memfd pages back in (`MADV_POPULATE_READ`) when the host has the memory. + pub heal: bool, + /// Bytes a heal tick may populate. + pub heal_bytes_per_tick: u64, + /// How often the memfd residency is read from smaps. + pub residency_every_ms: u64, + pub log: bool, +} + +impl GovernorConfig { + pub fn new(policy: Policy) -> Self { + Self { policy, sample_interval_ms: 1000, lock_mode: LockMode::Try, heal: true, heal_bytes_per_tick: GIB, residency_every_ms: 30_000, log: true } + } + + /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the variable + /// (a typo must not silently keep the default of a safety setting). + pub fn from_env(mem_total: u64, laptop: bool, env: &dyn Fn(&str) -> Option) -> Result { + let mut cfg = Self::new(Policy::for_host(mem_total, laptop)); + let number = |name: &str| -> Result, String> { + match env(name) { + None => Ok(None), + Some(v) => v.trim().parse::().map(Some).map_err(|_| format!("{name}={v:?} is not a number")), + } + }; + if let Some(v) = number("LELEKA_MEMORY_SOFT_FLOOR_MIB")? { + cfg.policy.soft_floor = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_HARD_FLOOR_MIB")? { + cfg.policy.hard_floor = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_RESERVE_MIB")? { + cfg.policy.reserve = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_HYSTERESIS_MIB")? { + cfg.policy.hysteresis = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? { + if v == 0 || v > 100 { + return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100")); + } + cfg.policy.cache_share_percent = v; + } + if let Some(v) = number("LELEKA_MEMORY_ENFORCE")? { + cfg.policy.enforce = v != 0; + } + if let Some(v) = number("LELEKA_MEMORY_SAMPLE_MS")? { + cfg.sample_interval_ms = v.clamp(50, 60_000); + } + if let Some(v) = number("LELEKA_MEMORY_HEAL")? { + cfg.heal = v != 0; + } + if let Some(v) = number("LELEKA_MEMORY_RESIDENCY_S")? { + cfg.residency_every_ms = v.saturating_mul(1000).max(1000); + } + if let Some(v) = env("LELEKA_MEMORY_LOCK") { + cfg.lock_mode = LockMode::parse(v.trim()).ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; + } + if cfg.policy.hard_floor >= cfg.policy.soft_floor { + return Err(format!( + "hard floor {} MiB must be below the soft floor {} MiB (LELEKA_MEMORY_HARD_FLOOR_MIB / SOFT_FLOOR_MIB)", + cfg.policy.hard_floor >> 20, + cfg.policy.soft_floor >> 20 + )); + } + Ok(cfg) + } +} + +/// What a request needs from the governor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RequestShape { + pub prompt_tokens: u64, + pub max_new_tokens: u64, + /// The engine's context (cells of the pinned K/V image). + pub max_context: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Refuse { + /// HTTP status the control plane answers with. + pub status: u16, + /// Machine-readable error code: `memory_pressure` or `context_length_exceeded`. + pub code: &'static str, + pub message: String, + pub retry_after_secs: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Admission { + Admit, + Refuse(Refuse), +} + +/// What the cache owners must do now. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ShedDirective { + pub level: Level, + /// `Some(bytes)`: the prefix cache budget to enforce now (evict down to it); `None`: its configured budget. + pub prefix_budget: Option, + /// Drop the conversation checkpoints (keep the root). + pub drop_conversation: bool, +} + +/// Transitions kept for the report. +#[derive(Clone, Debug, Serialize)] +pub struct TransitionRecord { + pub at_ms: u64, + pub from: Level, + pub to: Level, + pub reason: String, +} + +#[derive(Default)] +struct Counters { + admitted: AtomicU64, + rejected_pressure: AtomicU64, + rejected_context: AtomicU64, + shed_steps: AtomicU64, + evicted_bytes: AtomicU64, + samples: AtomicU64, + heal_bytes: AtomicU64, + heal_runs: AtomicU64, + level_changes: AtomicU64, +} + +/// What a lock attempt on the KAR memfd did, for the report. +#[derive(Clone, Debug, Serialize)] +pub struct LockReport { + pub mode: LockMode, + pub decision: LockDecision, + pub outcome: LockOutcome, + pub mapping_bytes: u64, + pub memlock_soft: Option, + pub memlock_hard: Option, + pub millis: f64, +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +struct Guarded { + mapping: crate::lock::FdMapping, + report: LockReport, + cursor: u64, + last_swapped: u64, + warned_swapped: u64, + last_check: Option, + last: Option, +} + +struct Inner { + cfg: GovernorConfig, + src: Arc, + epoch: Instant, + plan: Mutex>, + monitor: Mutex, + level: AtomicU8, + reason: Mutex, + available: AtomicU64, + sampled_at_ms: AtomicU64, + prefix_planned: AtomicU64, + prefix_target: AtomicU64, + prefix_used: AtomicU64, + last_shed_ms: AtomicU64, + since_ms: AtomicU64, + transitions: Mutex>, + counters: Counters, + ledger: Ledger, + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + guarded: Mutex>, + stop: AtomicBool, +} + +/// The governor handle (cheap to clone). +#[derive(Clone)] +pub struct Governor { + inner: Arc, +} + +static GLOBAL: OnceLock = OnceLock::new(); +static PUBLISHED: Mutex> = Mutex::new(None); + +/// The last report the sampler published (JSON text), for the status surface. +pub fn published_report() -> Option { + PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()).clone() +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|p| p.into_inner()) +} + +impl Governor { + pub fn new(cfg: GovernorConfig, src: Arc) -> Self { + let monitor = Monitor::new(cfg.policy); + Self { + inner: Arc::new(Inner { + cfg, + src, + epoch: Instant::now(), + plan: Mutex::new(None), + monitor: Mutex::new(monitor), + level: AtomicU8::new(Level::Normal as u8), + reason: Mutex::new("startup".into()), + available: AtomicU64::new(NONE), + sampled_at_ms: AtomicU64::new(0), + prefix_planned: AtomicU64::new(0), + prefix_target: AtomicU64::new(NONE), + prefix_used: AtomicU64::new(0), + last_shed_ms: AtomicU64::new(0), + since_ms: AtomicU64::new(0), + transitions: Mutex::new(VecDeque::new()), + counters: Counters::default(), + ledger: Ledger::new(), + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + guarded: Mutex::new(None), + stop: AtomicBool::new(false), + }), + } + } + + /// A governor over the real `/proc`. + pub fn real(cfg: GovernorConfig) -> Self { + Self::new(cfg, Arc::new(RealProc)) + } + + /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). + pub fn install(self) -> &'static Governor { + GLOBAL.get_or_init(|| self) + } + pub fn global() -> Option<&'static Governor> { + GLOBAL.get() + } + + pub fn config(&self) -> &GovernorConfig { + &self.inner.cfg + } + pub fn policy(&self) -> Policy { + self.inner.cfg.policy + } + pub fn inventory(&self) -> &'static Inventory { + Inventory::global() + } + pub fn ledger(&self) -> &Ledger { + &self.inner.ledger + } + pub fn source(&self) -> &(dyn ProcSource + Send + Sync) { + &*self.inner.src + } + pub fn probe(&self) -> HostFacts { + HostFacts::probe(&*self.inner.src) + } + pub fn census(&self) -> Census { + Census::take(&*self.inner.src) + } + fn now_ms(&self) -> u64 { + self.inner.epoch.elapsed().as_millis() as u64 + } + pub fn log(&self, text: &str) { + if self.inner.cfg.log { + eprintln!("leleka-memory: {text}"); + } + } + + // ---- plan ------------------------------------------------------------------------------------------------- + + /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep + /// the plan for the report. + pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { + let plan = match crate::plan::plan(input) { + Ok(plan) => plan, + Err(refusal) => { + self.log(&format!("REFUSING TO START: {refusal}")); + return Err(refusal); + } + }; + let inv = self.inventory(); + for item in &plan.fixed { + inv.set( + crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) + .expected(item.bytes) + .swappable(false), + ); + } + self.log(&format!( + "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", + plan.available_before.map_or("unknown".into(), gib), + gib(plan.fixed_bytes), + gib(plan.kar_to_create), + plan.available_after_fixed.map_or("unknown".into(), gib), + gib(plan.soft_floor), + gib(plan.hard_floor), + gib(plan.elastic), + gib(plan.resident_complement_bytes), + gib(plan.prefix_bytes), + plan.conversation_checkpoints, + gib(plan.conversation_bytes), + if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } + )); + for note in &plan.notes { + self.log(&format!("note: {note}")); + } + self.set_plan(plan.clone()); + Ok(plan) + } + + pub fn set_plan(&self, plan: Plan) { + self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); + *lock(&self.inner.plan) = Some(plan); + } + pub fn plan(&self) -> Option { + lock(&self.inner.plan).clone() + } + /// The prefix budget decided at stack open (after the fixed items are resident); the shed target is relative to it. + pub fn set_prefix_budget(&self, bytes: u64) { + self.inner.prefix_planned.store(bytes, Ordering::Release); + } + + // ---- level ------------------------------------------------------------------------------------------------ + + pub fn level(&self) -> Level { + Level::from_u8(self.inner.level.load(Ordering::Acquire)) + } + /// A fresh reading of the effective available memory (one probe of a dozen small files). + pub fn available_now(&self) -> Option { + self.probe().effective_available() + } + /// The last sampled value (at most one sample interval old); `None` before the first sample or when unknown. + pub fn available_cached(&self) -> Option { + match self.inner.available.load(Ordering::Acquire) { + NONE => None, + v => Some(v), + } + } + + /// Take a sample now and apply it. Returns the transition, if any. + pub fn sample_now(&self) -> Option { + self.sample_at(self.now_ms()) + } + + pub fn sample_at(&self, at_ms: u64) -> Option { + let facts = self.probe(); + let sample = Sample { + at_ms, + available: facts.effective_available(), + psi: facts.psi, + events: facts.cgroup.as_ref().and_then(|c| c.events), + pswpout: facts.pswpout, + }; + self.inner.counters.samples.fetch_add(1, Ordering::Relaxed); + self.inner.available.store(sample.available.unwrap_or(NONE), Ordering::Release); + self.inner.sampled_at_ms.store(at_ms, Ordering::Release); + let transition = lock(&self.inner.monitor).update(&sample); + if let Some(t) = &transition { + self.inner.level.store(t.to as u8, Ordering::Release); + self.inner.since_ms.store(at_ms, Ordering::Release); + *lock(&self.inner.reason) = t.reason.0.clone(); + self.inner.counters.level_changes.fetch_add(1, Ordering::Relaxed); + let mut q = lock(&self.inner.transitions); + if q.len() >= 32 { + q.pop_front(); + } + q.push_back(TransitionRecord { at_ms, from: t.from, to: t.to, reason: t.reason.0.clone() }); + drop(q); + self.log(&format!("memory pressure {} -> {}: {}", t.from.as_str(), t.to.as_str(), t.reason.0)); + } + transition + } + + // ---- admission and shedding ------------------------------------------------------------------------------- + + /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, + /// then whether its own transient memory would take the host below the hard floor. + pub fn admit(&self, shape: &RequestShape) -> Admission { + let c = &self.inner.counters; + let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); + if needed > shape.max_context { + c.rejected_context.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 400, + code: "context_length_exceeded", + message: format!( + "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", + shape.prompt_tokens, shape.max_new_tokens, shape.max_context + ), + retry_after_secs: 0, + }); + } + let level = self.level(); + let retry = lock(&self.inner.monitor).retry_after_secs().max(1); + if level == Level::Reject { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), + retry_after_secs: retry, + }); + } + // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor + let transient = self.inner.cfg.policy.reserve / 4; + if let Some(available) = self.available_now() { + if available.saturating_sub(transient) < self.inner.cfg.policy.hard_floor { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!( + "{} available is within {} of the hard floor {}; retry shortly", + gib(available), + gib(transient), + gib(self.inner.cfg.policy.hard_floor) + ), + retry_after_secs: retry, + }); + } + } + c.admitted.fetch_add(1, Ordering::Relaxed); + Admission::Admit + } + + /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. + pub fn directive(&self, prefix_used: u64) -> ShedDirective { + let level = self.level(); + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + self.inner.prefix_used.store(prefix_used, Ordering::Release); + match level { + Level::Normal => { + self.inner.prefix_target.store(NONE, Ordering::Release); + ShedDirective { level, prefix_budget: None, drop_conversation: false } + } + Level::Shed => { + let now = self.now_ms(); + let last = self.inner.last_shed_ms.load(Ordering::Acquire); + let current = self.inner.prefix_target.load(Ordering::Acquire); + let target = if current == NONE || now.saturating_sub(last) >= 1000 { + let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; + let next = base / 4 * 3; + self.inner.prefix_target.store(next, Ordering::Release); + self.inner.last_shed_ms.store(now, Ordering::Release); + self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); + next + } else { + current + }; + ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } + } + Level::Reject => { + self.inner.prefix_target.store(0, Ordering::Release); + ShedDirective { level, prefix_budget: Some(0), drop_conversation: true } + } + } + } + + pub fn note_prefix_used(&self, bytes: u64) { + self.inner.prefix_used.store(bytes, Ordering::Release); + } + pub fn note_evicted(&self, bytes: u64) { + self.inner.counters.evicted_bytes.fetch_add(bytes, Ordering::Relaxed); + } + + // ---- the sealed memfd --------------------------------------------------------------------------------------- + + /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { + let started = Instant::now(); + let facts = self.probe(); + let mode = self.inner.cfg.lock_mode; + let decision = plan_lock(mode, len, facts.memlock, &facts.status); + let mut mapping = match crate::lock::FdMapping::map_readonly(fd, usize::try_from(len).unwrap_or(usize::MAX)) { + Ok(m) => m, + Err(e) => { + let report = LockReport { + mode, + decision, + outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, + mapping_bytes: 0, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); + if mode == LockMode::Require { + return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); + } + return Ok(report); + } + }; + let outcome = match &decision { + LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, + LockDecision::Insufficient { need, soft, hard, advice } => { + let why = format!( + "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", + soft >> 20, + if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, + need >> 20 + ); + self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(len), advice.join(" | "))); + LockOutcome::NotAttempted { why } + } + LockDecision::Attempt { raise_soft_to } => { + if let Some(to) = raise_soft_to { + if let Err(e) = crate::lock::raise_memlock_soft(*to) { + self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); + } + } + let policy = self.inner.cfg.policy; + let swapped = self.mapping_swapped(&mapping).unwrap_or(0); + let src = self.inner.src.clone(); + let outcome = mapping.lock(GIB, |n| { + // a swapped-out chunk is read back into RAM: keep the hard floor + reserve + let need = if swapped > 0 { n } else { 0 }; + HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) + }); + match &outcome { + LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), + LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), + LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), + } + outcome + } + }; + let report = LockReport { + mode, + decision: decision.clone(), + outcome: outcome.clone(), + mapping_bytes: len, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { + let (numbers, advice) = match &decision { + LockDecision::Insufficient { need, soft, hard, advice } => ( + vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], + advice.clone(), + ), + _ => (vec![("archive".to_owned(), len)], vec![]), + }; + return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); + } + *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); + Ok(report) + } + + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + fn mapping_swapped(&self, mapping: &crate::lock::FdMapping) -> Option { + let text = self.inner.src.read("/proc/self/smaps").ok()?; + residency_from_smaps(&text, mapping.start(), mapping.len()).map(|r| r.swapped_bytes) + } + + /// Read the swap state of the archive mapping; warn when pages are swapped; pull them back when allowed. + /// Returns the swapped bytes found (0 when no mapping is guarded). + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn residency_tick(&self) -> u64 { + let policy = self.inner.cfg.policy; + let mut slot = lock(&self.inner.guarded); + let Some(g) = slot.as_mut() else { return 0 }; + let started = Instant::now(); + let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; + let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; + let read_ms = started.elapsed().as_secs_f64() * 1e3; + g.last = Some(r); + g.last_check = Some(Instant::now()); + g.last_swapped = r.swapped_bytes; + if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { + g.warned_swapped = r.swapped_bytes; + self.log(&format!( + "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", + r.swapped_bytes >> 20, + gib(r.rss_bytes), + gib(r.mapping_bytes), + r.locked_bytes >> 20, + if self.inner.cfg.heal { "; healing" } else { "" } + )); + } else if r.swapped_bytes < 64 * MIB { + g.warned_swapped = 0; + } + if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { + let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); + let ok = HostFacts::probe(&*self.inner.src) + .effective_available() + .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); + if ok { + let total = g.mapping.len(); + let mut done = 0; + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; + if n == 0 { + break; + } + if g.mapping.populate(g.cursor, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); + self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); + } + } + r.swapped_bytes + } + + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + pub fn residency_tick(&self) -> u64 { + 0 + } + + // ---- report ----------------------------------------------------------------------------------------------- + + pub fn report(&self) -> serde_json::Value { + let facts = self.probe(); + let monitor = lock(&self.inner.monitor); + let policy = self.inner.cfg.policy; + let level = self.level(); + let c = &self.inner.counters; + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + let target = self.inner.prefix_target.load(Ordering::Acquire); + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + let archive: Option = None; + json!({ + "version": 1, + "uptime_ms": self.now_ms(), + "gate": { + "level": level.as_str(), + "since_ms": self.inner.since_ms.load(Ordering::Acquire), + "reason": &*lock(&self.inner.reason), + "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, + "available_bytes": self.available_cached(), + "soft_floor_bytes": policy.soft_floor, + "hard_floor_bytes": policy.hard_floor, + }, + "policy": policy, + "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, + "plan": self.plan(), + "host": { + "mem_total": facts.meminfo.mem_total, + "mem_available": facts.meminfo.mem_available, + "effective_available": facts.effective_available(), + "swap_total": facts.meminfo.swap_total, + "swap_free": facts.meminfo.swap_free, + "shmem": facts.meminfo.shmem, + "mlocked": facts.meminfo.mlocked, + "cgroup": facts.cgroup, + "psi": facts.psi, + "memlock": facts.memlock, + "wsl": facts.wsl, + "kernel": facts.kernel, + }, + "process": { + "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, + "threads": facts.status.threads, "fds": facts.open_fds, + }, + "observed": monitor.observed, + "caches": { + "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, + }, + "counters": { + "admitted": c.admitted.load(Ordering::Relaxed), + "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), + "rejected_context": c.rejected_context.load(Ordering::Relaxed), + "shed_steps": c.shed_steps.load(Ordering::Relaxed), + "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), + "samples": c.samples.load(Ordering::Relaxed), + "level_changes": c.level_changes.load(Ordering::Relaxed), + "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), + "heal_runs": c.heal_runs.load(Ordering::Relaxed), + }, + "archive": archive, + "inventory": self.inventory().to_json(), + "ledger": self.inner.ledger.to_json(), + "transitions": &*lock(&self.inner.transitions), + }) + } + + /// Render the report into the cell [`published_report`] reads. + pub fn publish(&self) { + if let Ok(text) = serde_json::to_string(&self.report()) { + *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); + } + } + + // ---- sampler ----------------------------------------------------------------------------------------------- + + /// Start the sampler thread. It samples every interval, ticks the residency guard, publishes the report, and stops when + /// the guard is dropped. + pub fn spawn_sampler(&self) -> SamplerGuard { + let me = self.clone(); + self.inner.stop.store(false, Ordering::Release); + let handle = std::thread::Builder::new() + .name("leleka-memory".into()) + .spawn(move || { + let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); + let residency_every = Duration::from_millis(me.inner.cfg.residency_every_ms); + let mut last_residency = Instant::now().checked_sub(residency_every).unwrap_or_else(Instant::now); + while !me.inner.stop.load(Ordering::Acquire) { + me.sample_now(); + if last_residency.elapsed() >= residency_every { + me.residency_tick(); + last_residency = Instant::now(); + } + me.publish(); + let mut slept = Duration::ZERO; + while slept < interval && !me.inner.stop.load(Ordering::Acquire) { + let step = Duration::from_millis(50).min(interval - slept); + std::thread::sleep(step); + slept += step; + } + } + }) + .ok(); + SamplerGuard { inner: self.inner.clone(), handle } + } +} + +/// Stops the sampler thread when dropped. +pub struct SamplerGuard { + inner: Arc, + handle: Option>, +} + +impl Drop for SamplerGuard { + fn drop(&mut self) { + self.inner.stop.store(true, Ordering::Release); + if let Some(h) = self.handle.take() { + let _ = h.join(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::FakeProc; + use std::sync::RwLock; + + /// A host whose meminfo the test can change under the governor. + struct Live(RwLock); + impl ProcSource for Live { + fn read(&self, path: &str) -> std::io::Result { + self.0.read().unwrap().read(path) + } + fn count_entries(&self, path: &str) -> std::io::Result { + self.0.read().unwrap().count_entries(path) + } + } + fn live(avail_gib: u64) -> Arc { + let mut p = FakeProc::default(); + p.set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_gib * 1024 * 1024)); + p.set("/proc/self/status", "VmRSS: 1000 kB\nThreads: 3\n"); + Arc::new(Live(RwLock::new(p))) + } + fn set_avail(h: &Live, avail_mib: u64) { + h.0.write().unwrap().set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_mib * 1024)); + } + fn governor(host: Arc) -> Governor { + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + let g = Governor::new(cfg, host); + g.set_prefix_budget(8 * GIB); + g + } + const SHAPE: RequestShape = RequestShape { prompt_tokens: 1000, max_new_tokens: 100, max_context: 262_144 }; + + #[test] + fn requests_are_admitted_with_room_and_context_errors_are_400s() { + let h = live(20); + let g = governor(h); + assert_eq!(g.admit(&SHAPE), Admission::Admit); + let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: 262_144, ..SHAPE }) else { panic!() }; + assert_eq!((r.status, r.code), (400, "context_length_exceeded")); + assert!(r.message.contains("262144"), "{}", r.message); + let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: u64::MAX, max_new_tokens: u64::MAX, ..SHAPE }) else { panic!() }; + assert_eq!(r.status, 400, "overflow must not wrap into an admit"); + } + + #[test] + fn shedding_runs_in_order_prefix_cache_first_then_reject_with_retry_after() { + let h = live(20); + let g = governor(h.clone()); + assert_eq!(g.directive(8 * GIB), ShedDirective { level: Level::Normal, prefix_budget: None, drop_conversation: false }); + // below the 4 GiB soft floor: shed in steps of a quarter, one step per second + set_avail(&h, 3 * 1024); + let t = g.sample_at(1000).unwrap(); + assert_eq!(t.to, Level::Shed); + let d = g.directive(8 * GIB); + assert_eq!(d.level, Level::Shed); + assert_eq!(d.prefix_budget, Some(6 * GIB)); + assert!(d.drop_conversation); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "no second step within the same second"); + // requests are still served while only shedding + assert_eq!(g.admit(&SHAPE), Admission::Admit); + // below the hard floor: everything goes, new requests are refused with Retry-After + set_avail(&h, 1024); + assert_eq!(g.sample_at(2000).unwrap().to, Level::Reject); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(0)); + let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; + assert_eq!((r.status, r.code), (503, "memory_pressure")); + assert!(r.retry_after_secs >= 5); + // memory comes back: three calm samples per step down, then the configured budget is restored + set_avail(&h, 30 * 1024); + for i in 0..3 { + g.sample_at(3000 + i * 1000); + } + assert_eq!(g.level(), Level::Shed); + for i in 0..3 { + g.sample_at(7000 + i * 1000); + } + assert_eq!(g.level(), Level::Normal); + assert_eq!(g.directive(0).prefix_budget, None, "the configured budget is restored"); + assert_eq!(g.admit(&SHAPE), Admission::Admit); + } + + #[test] + fn a_request_whose_own_transient_would_cross_the_hard_floor_is_refused_before_it_starts() { + // 2.1 GiB available: above the 2 GiB hard floor, but the 256 MiB transient of a request would cross it + let h = live(20); + let g = governor(h.clone()); + set_avail(&h, 2150); + let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; + assert_eq!(r.code, "memory_pressure"); + assert!(r.message.contains("hard floor"), "{}", r.message); + } + + #[test] + fn counters_and_report_json_describe_the_decisions() { + let h = live(20); + let g = governor(h.clone()); + g.admit(&SHAPE); + set_avail(&h, 1024); + g.sample_at(1000); + g.admit(&SHAPE); + g.admit(&RequestShape { prompt_tokens: 999_999, ..SHAPE }); + let j = g.report(); + assert_eq!(j["version"], 1); + assert_eq!(j["gate"]["level"], "reject"); + assert!(j["gate"]["retry_after_secs"].as_u64().unwrap() >= 5); + assert_eq!(j["counters"]["admitted"], 1); + assert_eq!(j["counters"]["rejected_memory_pressure"], 1); + assert_eq!(j["counters"]["rejected_context"], 1); + assert_eq!(j["transitions"].as_array().unwrap().len(), 1); + assert_eq!(j["policy"]["soft_floor"], 4 * GIB); + g.publish(); + assert!(published_report().unwrap().contains("\"gate\"")); + } + + #[test] + fn env_overrides_are_validated_not_ignored() { + let env = |pairs: &'static [(&'static str, &'static str)]| move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| (*v).to_owned()); + let cfg = GovernorConfig::from_env(121 * GIB, false, &env(&[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), ("LELEKA_MEMORY_LOCK", "require")])).unwrap(); + assert_eq!((cfg.policy.soft_floor, cfg.policy.hard_floor, cfg.lock_mode), (19000 * MIB, 16000 * MIB, LockMode::Require)); + for bad in [ + &[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots")][..], + &[("LELEKA_MEMORY_LOCK", "maybe")][..], + &[("LELEKA_MEMORY_CACHE_SHARE_PERCENT", "0")][..], + &[("LELEKA_MEMORY_HARD_FLOOR_MIB", "9000"), ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "8000")][..], + ] { + let pairs: &'static [(&'static str, &'static str)] = Box::leak(bad.to_vec().into_boxed_slice()); + assert!(GovernorConfig::from_env(121 * GIB, false, &env(pairs)).is_err(), "{bad:?}"); + } + assert!(GovernorConfig::from_env(121 * GIB, false, &|_| None).is_ok()); + } + + #[test] + fn the_sampler_thread_samples_publishes_and_stops_on_drop() { + let h = live(20); + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + cfg.sample_interval_ms = 50; + let g = Governor::new(cfg, h.clone()); + let guard = g.spawn_sampler(); + std::thread::sleep(Duration::from_millis(300)); + assert!(g.report()["counters"]["samples"].as_u64().unwrap() >= 2); + set_avail(&h, 1024); + let deadline = Instant::now() + Duration::from_secs(5); + while g.level() != Level::Reject && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(g.level(), Level::Reject, "the sampler thread must notice the drop on its own"); + drop(guard); + let n = g.report()["counters"]["samples"].as_u64().unwrap(); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(g.report()["counters"]["samples"].as_u64().unwrap(), n, "no sampling after drop"); + } +} diff --git a/crates/leleka-memory/src/host.rs b/crates/leleka-memory/src/host.rs new file mode 100644 index 00000000..fbe1dc06 --- /dev/null +++ b/crates/leleka-memory/src/host.rs @@ -0,0 +1,277 @@ +//! What the host says about memory: `MemAvailable`, swap, the tightest cgroup v2 limit above this process, PSI, the +//! `RLIMIT_MEMLOCK`, and whether this is WSL2. Read through [`ProcSource`] so every decision is testable on fixtures. + +use crate::procfs::{self, CgroupEvents, MemInfo, ProcStatus, Psi}; +use serde::Serialize; +use std::collections::BTreeMap; +use std::io; + +/// Where the kernel's text files come from. +pub trait ProcSource { + /// The whole file as text; an error is "unknown". + fn read(&self, path: &str) -> io::Result; + /// Number of entries of a directory (`/proc/self/fd`, `/proc/self/task`). + fn count_entries(&self, path: &str) -> io::Result; +} + +/// The real `/proc` and `/sys`. +#[derive(Clone, Copy, Debug, Default)] +pub struct RealProc; + +impl ProcSource for RealProc { + fn read(&self, path: &str) -> io::Result { + use std::io::Read; + // smaps of a process with a 55 GB mapping is a few KiB per mapping; bound it anyway + let mut text = String::new(); + std::fs::File::open(path)?.take(64 << 20).read_to_string(&mut text)?; + Ok(text) + } + fn count_entries(&self, path: &str) -> io::Result { + Ok(std::fs::read_dir(path)?.count()) + } +} + +/// A fixture: files by absolute path, directories by entry count. +#[derive(Clone, Debug, Default)] +pub struct FakeProc { + pub files: BTreeMap, + pub dirs: BTreeMap, +} + +impl FakeProc { + pub fn with(mut self, path: &str, text: &str) -> Self { + self.files.insert(path.to_owned(), text.to_owned()); + self + } + pub fn set(&mut self, path: &str, text: &str) { + self.files.insert(path.to_owned(), text.to_owned()); + } +} + +impl ProcSource for FakeProc { + fn read(&self, path: &str) -> io::Result { + self.files.get(path).cloned().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, path.to_owned())) + } + fn count_entries(&self, path: &str) -> io::Result { + self.dirs.get(path).copied().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, path.to_owned())) + } +} + +pub const CGROUP_ROOT: &str = "/sys/fs/cgroup"; + +/// One cgroup level between the process and the root. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct CgroupLevel { + pub path: String, + /// `memory.max`; `None` = `max`. + pub limit: Option, + pub current: Option, + /// File pages the kernel can give back first (`inactive_file`). + pub reclaimable: u64, + /// `limit - current + reclaimable` (None without a limit or a reading). + pub headroom: Option, +} + +/// The cgroup v2 view of this process. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct CgroupFacts { + pub path: String, + pub levels: Vec, + /// The tightest `memory.max` among the levels and where it is. + pub limit: Option<(u64, String)>, + /// The smallest headroom among the limited levels. + pub headroom: Option, + /// `memory.swap.max` of the process's own cgroup (None = max or unreadable). + pub swap_max: Option, + pub events: Option, +} + +/// Everything the governor needs to know about the host at one instant. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct HostFacts { + pub meminfo: MemInfo, + pub status: ProcStatus, + pub psi: Option, + pub cgroup: Option, + /// (soft, hard) `RLIMIT_MEMLOCK`, `u64::MAX` = unlimited. + pub memlock: Option<(u64, u64)>, + pub wsl: bool, + pub kernel: Option, + /// `pswpin` / `pswpout` pages since boot (system wide). + pub pswpin: Option, + pub pswpout: Option, + pub open_fds: Option, +} + +impl HostFacts { + /// `MemAvailable` limited by the cgroup headroom: what this process can still take before the kernel reclaims hard + /// or kills. `None` = unknown (callers fail closed). + pub fn effective_available(&self) -> Option { + let host = self.meminfo.mem_available?; + Some(match self.cgroup.as_ref().and_then(|c| c.headroom) { + Some(h) => host.min(h), + None => host, + }) + } + /// `MemTotal` limited by a cgroup limit. + pub fn effective_total(&self) -> Option { + let host = self.meminfo.mem_total?; + Some(match self.cgroup.as_ref().and_then(|c| c.limit.as_ref()) { + Some((l, _)) => host.min(*l), + None => host, + }) + } + /// Free swap in bytes (0 when the host has none). + pub fn swap_free(&self) -> u64 { + self.meminfo.swap_free.unwrap_or(0) + } + pub fn probe(src: &dyn ProcSource) -> Self { + let text = |p: &str| src.read(p).ok(); + let meminfo = text("/proc/meminfo").map(|t| procfs::parse_meminfo(&t)).unwrap_or_default(); + let status = text("/proc/self/status").map(|t| procfs::parse_status(&t)).unwrap_or_default(); + let psi = text("/proc/pressure/memory").and_then(|t| procfs::parse_psi(&t)); + let memlock = text("/proc/self/limits").and_then(|t| procfs::parse_memlock_limit(&t)); + let kernel = text("/proc/sys/kernel/osrelease").map(|t| t.trim().to_owned()); + let wsl = kernel.as_deref().is_some_and(|k| { + let k = k.to_ascii_lowercase(); + k.contains("microsoft") || k.contains("wsl") + }); + let vmstat = text("/proc/vmstat"); + let pswp = |key: &str| vmstat.as_deref().and_then(|t| procfs::flat_keyed(t, key)); + Self { + meminfo, + status, + psi, + cgroup: probe_cgroup(src), + memlock, + wsl, + kernel, + pswpin: pswp("pswpin"), + pswpout: pswp("pswpout"), + open_fds: src.count_entries("/proc/self/fd").ok(), + } + } +} + +/// The cgroup levels of this process, innermost first, ending at the root. `None` when cgroup v2 is not mounted or +/// `/proc/self/cgroup` is not the unified hierarchy. +fn probe_cgroup(src: &dyn ProcSource) -> Option { + let rel = procfs::parse_cgroup_path(&src.read("/proc/self/cgroup").ok()?)?; + // Refuse anything that could leave the cgroup root. + if rel.split('/').any(|c| c == ".." || c == ".") { + return None; + } + let mut dir = format!("{CGROUP_ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); + let mut levels = Vec::new(); + loop { + let limit = src.read(&format!("{dir}/memory.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)); + let current = src.read(&format!("{dir}/memory.current")).ok().and_then(|t| t.trim().parse::().ok()); + let stat = src.read(&format!("{dir}/memory.stat")).ok(); + let reclaimable = stat.as_deref().and_then(|t| procfs::flat_keyed(t, "inactive_file")).unwrap_or(0); + // limit: Some(Some(n)) = a limit, Some(None) = "max", None = unreadable (a level without the controller) + let (limit_bytes, readable) = match limit { + Some(l) => (l, true), + None => (None, false), + }; + if readable || current.is_some() { + let headroom = match (limit_bytes, current) { + (Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))), + _ => None, + }; + levels.push(CgroupLevel { path: dir.clone(), limit: limit_bytes, current, reclaimable, headroom }); + } + if dir == CGROUP_ROOT { + break; + } + match dir.rfind('/') { + Some(i) if i >= CGROUP_ROOT.len() => dir.truncate(i), + _ => break, + } + } + let tightest = levels.iter().filter_map(|l| l.limit.map(|v| (v, l.path.clone()))).min_by_key(|(v, _)| *v); + let headroom = levels.iter().filter_map(|l| l.headroom).min(); + let own = format!("{CGROUP_ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); + let swap_max = src.read(&format!("{own}/memory.swap.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)).flatten(); + let events = src.read(&format!("{own}/memory.events")).ok().and_then(|t| procfs::parse_cgroup_events(&t)); + Some(CgroupFacts { path: rel, levels, limit: tightest, headroom, swap_max, events }) +} + +/// Advice text for the WSL2 case, appended to refusals. +pub fn wsl_advice() -> &'static str { + "WSL2: raise the VM limit in %UserProfile%\\.wslconfig ([wsl2] memory=48GB, swap=16GB) and run `wsl --shutdown`; \ + MemTotal inside the VM is that limit, so the governor budgets against it" +} + +#[cfg(test)] +mod tests { + use super::*; + + fn server() -> FakeProc { + FakeProc::default() + .with("/proc/meminfo", "MemTotal: 127091644 kB\nMemAvailable: 20699384 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n") + .with("/proc/self/status", "VmRSS: 100 kB\nVmPin: 52428800 kB\nThreads: 40\n") + .with("/proc/pressure/memory", "some avg10=0.00 avg60=0.01 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.01 avg300=0.00 total=1\n") + .with("/proc/self/limits", "Max locked memory 8388608 8388608 bytes \n") + .with("/proc/sys/kernel/osrelease", "7.0.0-38-generic\n") + .with("/proc/vmstat", "pswpin 10\npswpout 20\n") + .with("/proc/self/cgroup", "0::/user.slice/user-1000.slice/session-578.scope\n") + } + + #[test] + fn a_host_without_a_cgroup_limit_reports_meminfo() { + let f = HostFacts::probe(&server()); + assert_eq!(f.effective_available(), Some(20_699_384 * 1024)); + assert_eq!(f.effective_total(), Some(127_091_644 * 1024)); + assert_eq!(f.memlock, Some((8 << 20, 8 << 20))); + assert!(!f.wsl); + assert_eq!((f.pswpin, f.pswpout), (Some(10), Some(20))); + assert_eq!(f.status.vm_pin, Some(52_428_800 * 1024)); + assert!(f.cgroup.is_none() || f.cgroup.as_ref().unwrap().limit.is_none()); + } + + #[test] + fn the_tightest_cgroup_ancestor_bounds_what_is_available() { + let mut p = server(); + let base = "/sys/fs/cgroup/user.slice/user-1000.slice/session-578.scope"; + p.set(&format!("{base}/memory.max"), "max\n"); + p.set(&format!("{base}/memory.current"), "1000000\n"); + // the parent slice is limited to 30 GiB with 28 GiB used and 1 GiB of inactive file pages + let parent = "/sys/fs/cgroup/user.slice/user-1000.slice"; + p.set(&format!("{parent}/memory.max"), &format!("{}\n", 30u64 << 30)); + p.set(&format!("{parent}/memory.current"), &format!("{}\n", 28u64 << 30)); + p.set(&format!("{parent}/memory.stat"), &format!("inactive_file {}\nanon 1\n", 1u64 << 30)); + p.set("/sys/fs/cgroup/memory.max", "max\n"); + p.set("/sys/fs/cgroup/memory.current", "5\n"); + p.set(&format!("{base}/memory.events"), "low 0\nhigh 0\nmax 2\noom 0\noom_kill 0\n"); + let f = HostFacts::probe(&p); + let cg = f.cgroup.as_ref().unwrap(); + assert_eq!(cg.limit, Some((30 << 30, parent.to_owned()))); + assert_eq!(cg.headroom, Some(3 << 30)); + assert_eq!(f.effective_available(), Some(3 << 30), "cgroup headroom is below MemAvailable"); + assert_eq!(f.effective_total(), Some(30 << 30)); + assert_eq!(cg.events.unwrap().max, 2); + assert_eq!(cg.levels.len(), 3); + } + + #[test] + fn a_path_that_climbs_out_of_the_cgroup_root_is_not_followed() { + let mut p = server(); + p.set("/proc/self/cgroup", "0::/../../etc\n"); + assert!(HostFacts::probe(&p).cgroup.is_none()); + } + + #[test] + fn wsl_is_recognised_from_the_kernel_release() { + let mut p = server(); + p.set("/proc/sys/kernel/osrelease", "6.6.87.2-microsoft-standard-WSL2\n"); + assert!(HostFacts::probe(&p).wsl); + } + + #[test] + fn unknown_telemetry_stays_unknown() { + let f = HostFacts::probe(&FakeProc::default()); + assert_eq!(f.effective_available(), None); + assert_eq!(f.effective_total(), None); + assert_eq!(f.swap_free(), 0); + } +} diff --git a/crates/leleka-memory/src/inventory.rs b/crates/leleka-memory/src/inventory.rs new file mode 100644 index 00000000..f18a30d7 --- /dev/null +++ b/crates/leleka-memory/src/inventory.rs @@ -0,0 +1,307 @@ +//! The allocation inventory: every host and device allocation class of the runtime with its size formula, when it is +//! allocated, and its current and peak bytes. Components register their classes (`set`), update them while they grow +//! (`add`/`set_bytes`) and release them; the governor renders the table once at startup and serves it as JSON. +//! +//! Two kinds of numbers live side by side and are never mixed: the *accounted* bytes a component reports for its own +//! class (an exact formula or the owner's counter), and the *measured* stage deltas of the load ledger +//! ([`crate::ledger`]), which come from the kernel (`VmRSS`, `VmPin`, `Shmem`) and the driver (`cuMemGetInfo`) and so +//! include allocations nobody registered (cuBLAS workspaces, graphs, the CUDA context itself). + +use serde::Serialize; +use std::collections::BTreeMap; +use std::sync::{Mutex, MutexGuard, OnceLock}; + +/// Where the bytes live. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Space { + /// Ordinary anonymous host memory (swappable). + HostPageable, + /// Host memory the CUDA driver pinned (`cuMemHostAlloc`/`cuMemHostRegister`): not swappable, counted in `VmPin`. + HostPinned, + /// Shared memory (memfd): swappable unless locked. + HostShmem, + /// A file mapping (the OS file cache holds the pages; reclaimable). + HostMapped, + /// Device memory (VRAM). + Device, +} + +impl Space { + pub fn is_host(self) -> bool { + self != Space::Device + } + pub fn label(self) -> &'static str { + match self { + Space::HostPageable => "host pageable", + Space::HostPinned => "host pinned", + Space::HostShmem => "host shmem", + Space::HostMapped => "host file-mapped", + Space::Device => "device", + } + } +} + +/// When the class is allocated. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum When { + /// Once, before the first request (fixed footprint). + Startup, + /// On first use, then kept (graphs, workspaces). + Lazy, + /// Grows and shrinks with traffic under a budget (caches). + Elastic, + /// Allocated and freed within one request. + PerRequest, +} + +impl When { + pub fn label(self) -> &'static str { + match self { + When::Startup => "startup", + When::Lazy => "lazy", + When::Elastic => "elastic", + When::PerRequest => "per request", + } + } +} + +/// One allocation class. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Entry { + pub component: String, + pub class: String, + pub space: Space, + pub when: When, + /// Current accounted bytes. + pub bytes: u64, + /// Highest accounted bytes seen. + pub peak: u64, + /// What the planner expected before the allocation (None = not predicted). + pub expected: Option, + /// The size formula in words and numbers. + pub formula: String, + /// Whether the pages can be swapped out (false for pinned, locked). + pub swappable: bool, +} + +impl Entry { + pub fn new(component: &str, class: &str, space: Space, when: When, formula: &str) -> Self { + Self { + component: component.to_owned(), + class: class.to_owned(), + space, + when, + bytes: 0, + peak: 0, + expected: None, + formula: formula.to_owned(), + swappable: matches!(space, Space::HostPageable | Space::HostShmem | Space::HostMapped), + } + } + pub fn bytes(mut self, bytes: u64) -> Self { + self.bytes = bytes; + self.peak = bytes; + self + } + pub fn expected(mut self, bytes: u64) -> Self { + self.expected = Some(bytes); + self + } + pub fn swappable(mut self, swappable: bool) -> Self { + self.swappable = swappable; + self + } + pub fn id(&self) -> String { + format!("{}.{}", self.component, self.class) + } +} + +/// The registry. `Inventory::global()` is the process-wide one; tests make their own. +#[derive(Debug, Default)] +pub struct Inventory { + entries: Mutex>, +} + +impl Inventory { + pub fn new() -> Self { + Self::default() + } + pub fn global() -> &'static Inventory { + static GLOBAL: OnceLock = OnceLock::new(); + GLOBAL.get_or_init(Inventory::new) + } + fn lock(&self) -> MutexGuard<'_, BTreeMap> { + // A panic while holding the lock cannot leave a half-written entry (each update is one assignment). + self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + /// Insert or replace a class (keeping the peak of the previous registration). + pub fn set(&self, mut entry: Entry) { + let id = entry.id(); + let mut map = self.lock(); + if let Some(old) = map.get(&id) { + entry.peak = entry.peak.max(old.peak); + if entry.expected.is_none() { + entry.expected = old.expected; + } + } + entry.peak = entry.peak.max(entry.bytes); + map.insert(id, entry); + } + /// Update the accounted bytes of a registered class; an unknown id is ignored (a component that did not register + /// must not be able to fabricate a row). + pub fn set_bytes(&self, id: &str, bytes: u64) { + if let Some(e) = self.lock().get_mut(id) { + e.bytes = bytes; + e.peak = e.peak.max(bytes); + } + } + /// Grow (or shrink, with `sub`) a registered class. + pub fn add(&self, id: &str, bytes: u64) { + if let Some(e) = self.lock().get_mut(id) { + e.bytes = e.bytes.saturating_add(bytes); + e.peak = e.peak.max(e.bytes); + } + } + pub fn sub(&self, id: &str, bytes: u64) { + if let Some(e) = self.lock().get_mut(id) { + e.bytes = e.bytes.saturating_sub(bytes); + } + } + /// The class is gone (bytes 0, row kept so the peak stays visible). + pub fn release(&self, id: &str) { + self.set_bytes(id, 0); + } + pub fn get(&self, id: &str) -> Option { + self.lock().get(id).cloned() + } + pub fn entries(&self) -> Vec { + self.lock().values().cloned().collect() + } + pub fn clear(&self) { + self.lock().clear(); + } + /// Current accounted bytes per space. + pub fn totals(&self) -> BTreeMap { + let mut totals = BTreeMap::new(); + for e in self.lock().values() { + *totals.entry(e.space).or_insert(0u64) += e.bytes; + } + totals + } + pub fn total_host(&self) -> u64 { + self.lock().values().filter(|e| e.space.is_host()).map(|e| e.bytes).sum() + } + pub fn total_device(&self) -> u64 { + self.lock().values().filter(|e| !e.space.is_host()).map(|e| e.bytes).sum() + } + pub fn to_json(&self) -> serde_json::Value { + let entries = self.entries(); + let totals = self.totals(); + serde_json::json!({ + "entries": entries, + "totals": totals.iter().map(|(k, v)| (k.label().to_owned(), *v)).collect::>(), + "host_bytes": self.total_host(), + "device_bytes": self.total_device(), + }) + } + /// The startup table: one row per class, grouped by space, fixed-width. + pub fn table(&self) -> String { + let mut rows = self.entries(); + rows.sort_by(|a, b| (a.space, a.when, a.component.as_str(), a.class.as_str()).cmp(&(b.space, b.when, b.component.as_str(), b.class.as_str()))); + let mut out = String::new(); + out.push_str(&format!( + "{:<15} {:<11} {:<26} {:>12} {:>12} {:>5} {}\n", + "space", "when", "component.class", "MiB", "peak MiB", "swap", "size formula" + )); + let mib = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0); + for e in &rows { + out.push_str(&format!( + "{:<15} {:<11} {:<26} {:>12} {:>12} {:>5} {}\n", + e.space.label(), + e.when.label(), + e.id(), + mib(e.bytes), + mib(e.peak), + if e.swappable { "yes" } else { "no" }, + e.formula + )); + } + out.push_str(&format!( + "{:<15} {:<11} {:<26} {:>12}\n{:<15} {:<11} {:<26} {:>12}\n", + "total", + "", + "host (accounted)", + mib(self.total_host()), + "total", + "", + "device (accounted)", + mib(self.total_device()) + )); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kv() -> Entry { + Entry::new("kv", "host_pinned", Space::HostPinned, When::Startup, "12 layers x cells x 1056 B").bytes(3_321_901_056) + } + + #[test] + fn classes_are_registered_updated_and_keep_their_peak() { + let inv = Inventory::new(); + inv.set(kv()); + inv.set(Entry::new("prefix", "store", Space::HostPageable, When::Elastic, "blocks + states").expected(8 << 30)); + inv.add("prefix.store", 100); + inv.add("prefix.store", 50); + inv.sub("prefix.store", 120); + let e = inv.get("prefix.store").unwrap(); + assert_eq!((e.bytes, e.peak, e.expected), (30, 150, Some(8 << 30))); + inv.release("prefix.store"); + assert_eq!(inv.get("prefix.store").unwrap().peak, 150, "the peak survives a release"); + assert_eq!(inv.total_host(), 3_321_901_056); + assert_eq!(inv.total_device(), 0); + } + + #[test] + fn unknown_ids_cannot_fabricate_rows() { + let inv = Inventory::new(); + inv.add("ghost.row", 5); + inv.set_bytes("ghost.row", 5); + inv.sub("ghost.row", 1); + assert!(inv.entries().is_empty()); + } + + #[test] + fn re_registering_a_class_keeps_the_peak_and_the_prediction() { + let inv = Inventory::new(); + inv.set(Entry::new("a", "b", Space::Device, When::Lazy, "f").expected(10).bytes(500)); + inv.set(Entry::new("a", "b", Space::Device, When::Lazy, "f").bytes(20)); + let e = inv.get("a.b").unwrap(); + assert_eq!((e.bytes, e.peak, e.expected), (20, 500, Some(10))); + } + + #[test] + fn pinned_and_locked_classes_are_not_swappable_by_default() { + assert!(!kv().swappable); + assert!(Entry::new("c", "d", Space::HostShmem, When::Startup, "").swappable); + assert!(!Entry::new("c", "d", Space::HostShmem, When::Startup, "").swappable(false).swappable); + } + + #[test] + fn table_and_json_carry_every_class_and_the_totals() { + let inv = Inventory::new(); + inv.set(kv()); + inv.set(Entry::new("vram", "kv_resident", Space::Device, When::Startup, "slots x 4244 B").bytes(1 << 30)); + let t = inv.table(); + assert!(t.contains("kv.host_pinned") && t.contains("vram.kv_resident") && t.contains("host (accounted)"), "{t}"); + let j = inv.to_json(); + assert_eq!(j["device_bytes"], 1u64 << 30); + assert_eq!(j["entries"].as_array().unwrap().len(), 2); + assert_eq!(j["entries"][0]["space"], "host_pinned"); + } +} diff --git a/crates/leleka-memory/src/ledger.rs b/crates/leleka-memory/src/ledger.rs new file mode 100644 index 00000000..8a6ac6f7 --- /dev/null +++ b/crates/leleka-memory/src/ledger.rs @@ -0,0 +1,180 @@ +//! The load ledger: what each startup stage really cost, measured from the kernel and the driver rather than +//! predicted. A stage is a bracket around one step of opening the stack (embedding table, dense weights, MoE arena, +//! KV, expert tier, ...): the ledger records the change of the process's `VmRSS`/`VmPin`, of system `Shmem` and +//! `MemAvailable`, and of the device (the context's accounted bytes and the driver's free VRAM). Allocations nobody +//! registered with the inventory (cuBLAS workspaces, graphs, the CUDA context) show up here. + +use crate::host::{HostFacts, ProcSource}; +use serde::Serialize; +use std::sync::Mutex; +use std::time::Instant; + +/// A device reading, supplied by the runtime (the driver crate is not a dependency of this one). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct DeviceSample { + /// Bytes the context's own budget accounts as allocated. + pub accounted: u64, + /// `cuMemGetInfo` free. + pub free: u64, + pub total: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct HostSample { + pub rss: u64, + pub pinned: u64, + pub locked: u64, + pub swap: u64, + pub shmem: u64, + pub available: u64, +} + +impl HostSample { + pub fn take(src: &dyn ProcSource) -> Self { + let f = HostFacts::probe(src); + Self { + rss: f.status.vm_rss.unwrap_or(0), + pinned: f.status.vm_pin.unwrap_or(0), + locked: f.status.vm_lck.unwrap_or(0), + swap: f.status.vm_swap.unwrap_or(0), + shmem: f.meminfo.shmem.unwrap_or(0), + available: f.effective_available().unwrap_or(0), + } + } +} + +/// One measured stage. Deltas are signed: a stage may free memory. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Stage { + pub name: String, + pub millis: f64, + pub rss: i64, + pub pinned: i64, + pub shmem: i64, + /// Change of `MemAvailable` (negative = the stage consumed host memory). + pub available: i64, + /// Change of the context's accounted device bytes. + pub device_accounted: Option, + /// Change of used VRAM as the driver sees it (`-Δ free`): includes what the context does not account. + pub device_driver: Option, + pub host_after: HostSample, + pub device_after: Option, +} + +fn delta(after: u64, before: u64) -> i64 { + i64::try_from(i128::from(after) - i128::from(before)).unwrap_or(if after > before { i64::MAX } else { i64::MIN }) +} + +/// A stage in progress. +pub struct OpenStage { + name: String, + started: Instant, + host: HostSample, + device: Option, +} + +#[derive(Debug, Default)] +pub struct Ledger { + stages: Mutex>, +} + +impl Ledger { + pub fn new() -> Self { + Self::default() + } + pub fn begin(&self, name: &str, src: &dyn ProcSource, device: Option) -> OpenStage { + OpenStage { name: name.to_owned(), started: Instant::now(), host: HostSample::take(src), device } + } + pub fn end(&self, open: OpenStage, src: &dyn ProcSource, device: Option) -> Stage { + let after = HostSample::take(src); + let stage = Stage { + name: open.name, + millis: open.started.elapsed().as_secs_f64() * 1e3, + rss: delta(after.rss, open.host.rss), + pinned: delta(after.pinned, open.host.pinned), + shmem: delta(after.shmem, open.host.shmem), + available: delta(after.available, open.host.available), + device_accounted: open.device.zip(device).map(|(a, b)| delta(b.accounted, a.accounted)), + device_driver: open.device.zip(device).map(|(a, b)| delta(a.free, b.free)), + host_after: after, + device_after: device, + }; + self.stages.lock().unwrap_or_else(|p| p.into_inner()).push(stage.clone()); + stage + } + pub fn stages(&self) -> Vec { + self.stages.lock().unwrap_or_else(|p| p.into_inner()).clone() + } + pub fn clear(&self) { + self.stages.lock().unwrap_or_else(|p| p.into_inner()).clear(); + } + /// Fixed-width rendering for the startup log. + pub fn table(&self) -> String { + let mib = |v: i64| format!("{:+.1}", v as f64 / 1_048_576.0); + let opt = |v: Option| v.map_or("-".to_owned(), mib); + let mut out = format!( + "{:<34} {:>9} {:>11} {:>11} {:>11} {:>11} {:>11} {:>11}\n", + "stage", "ms", "rss MiB", "pinned MiB", "shmem MiB", "avail MiB", "dev acct", "dev driver" + ); + for s in self.stages() { + out.push_str(&format!( + "{:<34} {:>9.0} {:>11} {:>11} {:>11} {:>11} {:>11} {:>11}\n", + s.name, + s.millis, + mib(s.rss), + mib(s.pinned), + mib(s.shmem), + mib(s.available), + opt(s.device_accounted), + opt(s.device_driver) + )); + } + out + } + pub fn to_json(&self) -> serde_json::Value { + serde_json::to_value(self.stages()).unwrap_or(serde_json::Value::Null) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::FakeProc; + + fn proc(rss_kib: u64, pin_kib: u64, avail_kib: u64, shmem_kib: u64) -> FakeProc { + FakeProc::default() + .with("/proc/self/status", &format!("VmRSS: {rss_kib} kB\nVmPin: {pin_kib} kB\n")) + .with("/proc/meminfo", &format!("MemTotal: 100000000 kB\nMemAvailable: {avail_kib} kB\nShmem: {shmem_kib} kB\n")) + } + + #[test] + fn a_stage_records_signed_deltas_of_host_and_device() { + let led = Ledger::new(); + let open = led.begin("expert bank", &proc(1000, 0, 90_000_000, 5000), Some(DeviceSample { accounted: 100, free: 1000, total: 2000 })); + let stage = led.end(open, &proc(51_000, 50_000, 40_000_000, 5000), Some(DeviceSample { accounted: 300, free: 700, total: 2000 })); + assert_eq!(stage.rss, 50_000 * 1024); + assert_eq!(stage.pinned, 50_000 * 1024); + assert_eq!(stage.available, -50_000_000 * 1024); + assert_eq!(stage.shmem, 0); + assert_eq!(stage.device_accounted, Some(200)); + assert_eq!(stage.device_driver, Some(300), "driver-seen use grows by more than the context accounts"); + assert_eq!(led.stages().len(), 1); + assert!(led.table().contains("expert bank")); + assert_eq!(led.to_json()[0]["name"], "expert bank"); + } + + #[test] + fn a_stage_without_a_device_reading_has_no_device_delta() { + let led = Ledger::new(); + let open = led.begin("tokenizer", &proc(1, 1, 1, 1), None); + let stage = led.end(open, &proc(1, 1, 1, 1), Some(DeviceSample::default())); + assert_eq!((stage.device_accounted, stage.device_driver), (None, None)); + } + + #[test] + fn delta_saturates_instead_of_wrapping() { + assert_eq!(delta(u64::MAX, 0), i64::MAX); + assert_eq!(delta(0, u64::MAX), i64::MIN); + assert_eq!(delta(5, 7), -2); + } +} diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs new file mode 100644 index 00000000..e1386695 --- /dev/null +++ b/crates/leleka-memory/src/lib.rs @@ -0,0 +1,22 @@ +//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and +//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the +//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests. +//! +//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and +//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`. + +pub mod census; +pub mod governor; +pub mod host; +pub mod inventory; +pub mod ledger; +pub mod lock; +pub mod plan; +pub mod pressure; +pub mod procfs; + +pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report}; +pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; +pub use inventory::{Entry, Inventory, Space, When}; +pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts}; +pub use pressure::Level; diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs new file mode 100644 index 00000000..0245f7fa --- /dev/null +++ b/crates/leleka-memory/src/lock.rs @@ -0,0 +1,398 @@ +//! Keeping the sealed KAR memfd resident. +//! +//! A sealed memfd is shmem: its 55 GB are charged to `Shmem`, are NOT counted by `MemAvailable`, and are swappable. +//! Page-cache pressure (the Original reading the same KAR file next to the memfd, a shard read, a `cat`) can push +//! them to swap, which turns every PLE row read into a major fault. Three layers defend against it: +//! +//! 1. **Lock** the pages: `mmap` the descriptor read-only and `mlock` it in chunks. Needs `RLIMIT_MEMLOCK` >= the +//! archive or `CAP_IPC_LOCK`; the plan is decided from the limits first (`plan_lock`) so a host that cannot lock does not +//! fault 55 GB in for nothing, and the refusal carries the fix (`LimitMEMLOCK=infinity`, `ulimit -l`, `setcap`). +//! 2. **Detect** swapped pages: the swap of the mapping from `/proc/self/smaps` (exact) and `mincore` (which pages). +//! 3. **Heal**: when pages are found swapped out and the host has the memory, `MADV_POPULATE_READ` brings them back, +//! rate limited and guarded by the same floors as everything else. +//! +//! The mapping is never dereferenced: it exists only as an address range for `mlock`/`mincore`/`madvise`, so no +//! reference into it can dangle, race with the GPU or fault (a sealed memfd cannot shrink either). + +use crate::procfs::{self, ProcStatus}; +use serde::Serialize; + +pub const CAP_IPC_LOCK_BIT: u64 = 1 << 14; +const PAGE: u64 = 4096; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LockMode { + /// Do not lock; still detect and report. + Off, + /// Lock when the limits allow it, otherwise report why and fall back to detect + heal (default). + Try, + /// Refuse to start without the lock. + Require, +} + +impl LockMode { + pub fn parse(text: &str) -> Option { + match text { + "off" | "0" => Some(Self::Off), + "try" | "auto" => Some(Self::Try), + "require" | "on" | "1" => Some(Self::Require), + _ => None, + } + } +} + +/// What to do about locking, decided from the numbers alone. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "decision", rename_all = "snake_case")] +pub enum LockDecision { + /// Lock now; `raise_soft_to` first lifts the soft limit to the hard one when that is what it takes. + Attempt { raise_soft_to: Option }, + /// Locking is switched off. + Off, + /// The limits cannot cover the archive. + Insufficient { need: u64, soft: u64, hard: u64, advice: Vec }, +} + +/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the capabilities? +pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status: &ProcStatus) -> LockDecision { + if mode == LockMode::Off { + return LockDecision::Off; + } + if status.cap_eff.is_some_and(|c| c & CAP_IPC_LOCK_BIT != 0) { + return LockDecision::Attempt { raise_soft_to: None }; + } + let already = status.vm_lck.unwrap_or(0); + let need = len.saturating_add(already); + match memlock { + Some((soft, _)) if soft >= need => LockDecision::Attempt { raise_soft_to: None }, + Some((_, hard)) if hard >= need => LockDecision::Attempt { raise_soft_to: Some(need) }, + Some((soft, hard)) => LockDecision::Insufficient { + need, + soft, + hard, + advice: vec![ + format!("raise RLIMIT_MEMLOCK to at least {} MiB: systemd `LimitMEMLOCK=infinity` in the service unit (the leleka unit sets it), or `ulimit -l unlimited` / /etc/security/limits.conf `memlock` for the user", need >> 20), + "or grant the binary CAP_IPC_LOCK (`setcap cap_ipc_lock+ep` / systemd `AmbientCapabilities=CAP_IPC_LOCK`)".into(), + "without the lock the guard still detects swapped pages and pulls them back (MADV_POPULATE_READ); lower vm.swappiness and `MemoryLow=` on the service cgroup also keep the memfd out of swap".into(), + ], + }, + None => LockDecision::Attempt { raise_soft_to: None }, + } +} + +/// How a lock attempt ended. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "outcome", rename_all = "snake_case")] +pub enum LockOutcome { + Locked { bytes: u64 }, + /// Some chunks locked before the kernel (or the guard) said stop. + Partial { locked: u64, wanted: u64, why: String }, + NotAttempted { why: String }, +} + +impl LockOutcome { + pub fn locked_bytes(&self) -> u64 { + match self { + LockOutcome::Locked { bytes } => *bytes, + LockOutcome::Partial { locked, .. } => *locked, + LockOutcome::NotAttempted { .. } => 0, + } + } +} + +/// The swap state of the mapping. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Residency { + pub mapping_bytes: u64, + /// `Swap:` of the mapping in `/proc/self/smaps` (shmem pages in swap). + pub swapped_bytes: u64, + /// `Rss:` of the mapping (pages in this process's page tables; grows when the lock/populate runs). + pub rss_bytes: u64, + /// `Locked:` of the mapping. + pub locked_bytes: u64, +} + +/// Find the mapping that starts at `start` in `smaps` text and report its swap. +pub fn residency_from_smaps(smaps: &str, start: u64, len: u64) -> Option { + procfs::parse_smaps(smaps) + .into_iter() + .find(|e| e.start == start && e.end - e.start >= len) + .map(|e| Residency { mapping_bytes: e.end - e.start, swapped_bytes: e.swap, rss_bytes: e.rss, locked_bytes: e.locked }) +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +pub use sys::{FdMapping, raise_memlock_soft}; + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +#[allow(unsafe_code)] +mod sys { + use super::{LockOutcome, PAGE}; + use std::io; + use std::os::fd::{AsRawFd, BorrowedFd}; + + /// A read-only `MAP_SHARED` mapping of a descriptor, held only for `mlock`, `mincore` and `madvise`. + /// + /// Invariants (the whole safety argument of this module): + /// * `addr..addr+len` is a live mapping created by `mmap` in `map_readonly` and unmapped exactly once, in `Drop`; + /// * no reference or slice into it is ever created: the pointer is only passed to system calls, so there is + /// nothing to dangle, alias or fault on (and the sealed memfd cannot shrink under it); + /// * every range handed to a syscall is checked `offset + n <= len` and page aligned first. + pub struct FdMapping { + addr: *mut libc::c_void, + len: usize, + locked: u64, + } + + // SAFETY: the pointer is an address-space handle used only by thread-safe system calls on an immutable mapping; it + // is never dereferenced, so sharing it between threads cannot race. + unsafe impl Send for FdMapping {} + // SAFETY: see `Send`; all methods take `&self` and only issue syscalls, or `&mut self` for the lock counter. + unsafe impl Sync for FdMapping {} + + /// Raise the soft `RLIMIT_MEMLOCK` to `to` (never above the hard limit). + pub fn raise_memlock_soft(to: u64) -> io::Result<()> { + let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; + // SAFETY: `lim` is a valid, writable rlimit for the duration of the call. + if unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, &mut lim) } != 0 { + return Err(io::Error::last_os_error()); + } + lim.rlim_cur = to.min(lim.rlim_max); + // SAFETY: `lim` is a valid, initialized rlimit. + if unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &lim) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + + impl FdMapping { + /// Map `len` bytes of `fd` read-only. `len` must be non-zero and the descriptor at least that long. + pub fn map_readonly(fd: BorrowedFd<'_>, len: usize) -> io::Result { + if len == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty mapping")); + } + // SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing + // mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED. + let addr = unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) }; + if addr == libc::MAP_FAILED { + return Err(io::Error::last_os_error()); + } + Ok(Self { addr, len, locked: 0 }) + } + pub fn start(&self) -> u64 { + self.addr as usize as u64 + } + pub fn len(&self) -> u64 { + self.len as u64 + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn locked_bytes(&self) -> u64 { + self.locked + } + fn range(&self, offset: u64, n: u64) -> io::Result<(*mut libc::c_void, usize)> { + if offset % PAGE != 0 + || n == 0 + || offset.checked_add(n).is_none_or(|end| end > self.len as u64) + || usize::try_from(offset).is_err() + || usize::try_from(n).is_err() + { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "range outside the mapping")); + } + // SAFETY: `offset <= len` was checked, so the result stays inside (or one past) the mapping. + Ok((unsafe { self.addr.cast::().add(offset as usize) }.cast(), n as usize)) + } + /// Lock `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. + /// A chunk that is swapped out must be read back from swap (host memory), which is why the guard exists. + pub fn lock(&mut self, chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { + let chunk = chunk.max(PAGE) / PAGE * PAGE; + let total = self.len as u64; + let mut offset = self.locked; + while offset < total { + let n = chunk.min(total - offset); + if !allow(n) { + return LockOutcome::Partial { locked: self.locked, wanted: total, why: "host memory guard refused the next chunk".into() }; + } + let (ptr, n_usize) = match self.range(offset, n) { + Ok(r) => r, + Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() }, + }; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + if unsafe { libc::mlock(ptr, n_usize) } != 0 { + let e = io::Error::last_os_error(); + return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") }; + } + offset += n; + self.locked = offset; + } + LockOutcome::Locked { bytes: self.locked } + } + /// Unlock everything this mapping locked. + pub fn unlock(&mut self) { + if self.locked > 0 { + // SAFETY: the locked prefix `addr..addr+locked` lies inside our live mapping. + let _ = unsafe { libc::munlock(self.addr, self.locked as usize) }; + self.locked = 0; + } + } + /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the caller + /// may not write, newer kernels report every page resident: use the smaps number for totals. + pub fn incore(&self, offset: u64, n: u64) -> io::Result> { + let (ptr, n_usize) = self.range(offset, n)?; + let pages = n_usize.div_ceil(PAGE as usize); + let mut vec = vec![0u8; pages]; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; `vec` has one byte per page of the range. + if unsafe { libc::mincore(ptr, n_usize, vec.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(vec.into_iter().map(|b| b & 1 == 1).collect()) + } + /// Bring `offset..offset+n` into memory (read faults, including from swap) without touching the bytes. + pub fn populate(&self, offset: u64, n: u64) -> io::Result<()> { + let (ptr, n_usize) = self.range(offset, n)?; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; MADV_POPULATE_READ changes no contents. + if unsafe { libc::madvise(ptr, n_usize, libc::MADV_POPULATE_READ) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + } + + impl Drop for FdMapping { + fn drop(&mut self) { + // SAFETY: `addr`/`len` are exactly what `mmap` returned/was given, and `drop` runs once; nothing borrows + // the mapping (no references are ever created into it). munlock is implied by munmap. + unsafe { + libc::munmap(self.addr, self.len); + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use std::io::Write; + use std::os::fd::AsFd; + + fn file(len: usize) -> std::fs::File { + let mut f = tempfile_in_target(); + f.write_all(&vec![7u8; len]).unwrap(); + f.flush().unwrap(); + f + } + fn tempfile_in_target() -> std::fs::File { + // an unlinked file under the system temp dir + let path = std::env::temp_dir().join(format!("leleka-memory-lock-{}-{:?}", std::process::id(), std::thread::current().id())); + let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap(); + let _ = std::fs::remove_file(&path); + f + } + + #[test] + fn maps_locks_inside_the_limit_and_reports_incore() { + let f = file(64 * 4096); + let mut m = FdMapping::map_readonly(f.as_fd(), 64 * 4096).unwrap(); + assert_eq!(m.len(), 64 * 4096); + let mut asked = Vec::new(); + let outcome = m.lock(16 * 4096, |n| { + asked.push(n); + true + }); + // 64 pages = 256 KiB: inside any RLIMIT_MEMLOCK of 8 MiB + assert_eq!(outcome, LockOutcome::Locked { bytes: 64 * 4096 }, "{outcome:?}"); + assert_eq!(asked, vec![16 * 4096; 4]); + let pages = m.incore(0, 64 * 4096).unwrap(); + assert_eq!(pages.len(), 64); + assert!(pages.iter().all(|&p| p)); + m.populate(0, 64 * 4096).unwrap(); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + } + + #[test] + fn the_guard_stops_the_lock_between_chunks() { + let f = file(32 * 4096); + let mut m = FdMapping::map_readonly(f.as_fd(), 32 * 4096).unwrap(); + let mut calls = 0; + let outcome = m.lock(8 * 4096, |_| { + calls += 1; + calls <= 2 + }); + assert!(matches!(outcome, LockOutcome::Partial { locked, .. } if locked == 16 * 4096), "{outcome:?}"); + assert_eq!(m.locked_bytes(), 16 * 4096); + } + + #[test] + fn ranges_outside_the_mapping_or_unaligned_are_refused_before_any_syscall() { + let f = file(8 * 4096); + let m = FdMapping::map_readonly(f.as_fd(), 8 * 4096).unwrap(); + assert!(m.incore(4096, 8 * 4096).is_err()); + assert!(m.incore(1, 4096).is_err()); + assert!(m.populate(0, 0).is_err()); + assert!(m.populate(u64::MAX - 100, 4096).is_err()); + assert!(m.incore(0, 8 * 4096).is_ok()); + } + + #[test] + fn an_empty_mapping_is_refused() { + let f = file(4096); + assert!(FdMapping::map_readonly(f.as_fd(), 0).is_err()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn status(cap: Option, lck: u64) -> ProcStatus { + ProcStatus { cap_eff: cap, vm_lck: Some(lck), ..ProcStatus::default() } + } + const G: u64 = 1 << 30; + + #[test] + fn the_5090_server_default_limit_cannot_lock_the_55gb_archive_and_says_how_to() { + // para@homelab: soft = hard = 8 MiB, no CAP_IPC_LOCK + let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(0), 8 << 10)); + let LockDecision::Insufficient { need, soft, hard, advice } = d else { panic!("{d:?}") }; + assert!(need > 55 * G && soft == 8 << 20 && hard == 8 << 20); + let text = advice.join("\n"); + assert!(text.contains("LimitMEMLOCK=infinity") && text.contains("CAP_IPC_LOCK") && text.contains("MADV_POPULATE_READ"), "{text}"); + } + + #[test] + fn unlimited_limits_or_the_capability_allow_the_lock() { + assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((u64::MAX, u64::MAX)), &status(Some(0), 0)), LockDecision::Attempt { raise_soft_to: None }); + assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(CAP_IPC_LOCK_BIT), 0)), LockDecision::Attempt { raise_soft_to: None }); + assert_eq!(plan_lock(LockMode::Try, 55 * G, None, &status(None, 0)), LockDecision::Attempt { raise_soft_to: None }, "unknown limits: try and see"); + } + + #[test] + fn a_hard_limit_that_covers_it_lifts_the_soft_one_first() { + let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, u64::MAX)), &status(Some(0), 0)); + assert_eq!(d, LockDecision::Attempt { raise_soft_to: Some(55 * G) }); + } + + #[test] + fn off_never_locks() { + assert_eq!(plan_lock(LockMode::Off, 1, Some((u64::MAX, u64::MAX)), &status(None, 0)), LockDecision::Off); + assert_eq!(LockMode::parse("require"), Some(LockMode::Require)); + assert_eq!(LockMode::parse("nope"), None); + } + + #[test] + fn already_locked_pages_count_against_the_limit() { + let d = plan_lock(LockMode::Try, 4 * G, Some((6 * G, 6 * G)), &status(Some(0), 3 * G)); + assert!(matches!(d, LockDecision::Insufficient { .. }), "{d:?}"); + } + + #[test] + fn residency_is_read_from_the_mapping_that_starts_at_our_address() { + let smaps = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\nSize: 4194304 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n"; + let r = residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 30).unwrap(); + assert_eq!((r.swapped_bytes, r.rss_bytes), (194_304 * 1024, 4_000_000 * 1024)); + assert!(residency_from_smaps(smaps, 0x1000, 1).is_none()); + assert!(residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 40).is_none(), "a smaller mapping is not ours"); + } +} diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs new file mode 100644 index 00000000..fd049567 --- /dev/null +++ b/crates/leleka-memory/src/plan.rs @@ -0,0 +1,560 @@ +//! The startup budget: one pure function from what the host has and what the runtime will allocate to either a plan +//! (cache budgets sized from what is left) or a refusal with the numbers and what to change. +//! +//! ```text +//! available (MemAvailable, cgroup headroom) A +//! - sealed KAR memfd still to be created (0 when inherited: already resident) +//! - fixed host items still to be allocated F expert bank, pinned K/V image, staging rings, pool scratch +//! = after the fixed footprint R = A - F +//! refuse when R < soft_floor + reserve +//! elastic = R - soft_floor - reserve what the caches may grow into +//! resident complement (explicit) <= elastic +//! prefix cache (auto: share% of the rest, capped) or conversation checkpoints (when no prefix cache) +//! ``` +//! The two floors then drive the runtime monitor ([`crate::pressure`]): below `soft_floor` the caches shed, below +//! `hard_floor` new requests are refused. + +use crate::host::{HostFacts, wsl_advice}; +use crate::inventory::Space; +use serde::Serialize; + +pub const MIB: u64 = 1 << 20; +pub const GIB: u64 = 1 << 30; + +/// Thresholds and shares. `for_host` derives them from the machine; every field is an operator override point. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Policy { + /// Below this much available memory the caches shed. + pub soft_floor: u64, + /// Below this new requests are refused with 503 `memory_pressure`. + pub hard_floor: u64, + /// Slack kept on top of `soft_floor` after the fixed footprint for the transients of one request + /// (a conversation checkpoint is ~118 MB, a prefix node state ~127 MB, import staging). + pub reserve: u64, + /// Leaving a level needs this much margin above its threshold. + pub hysteresis: u64, + /// Share of the elastic memory an `auto` prefix cache takes, percent. + pub cache_share_percent: u64, + /// Ceiling of an `auto` prefix cache. + pub prefix_cap: u64, + /// An `auto` cache smaller than this is off. + pub min_useful_cache: u64, + /// PSI `some avg10` (percent of time stalled) that starts shedding. + pub psi_some_shed: f64, + /// PSI `full avg10` that starts refusing requests. + pub psi_full_reject: f64, + /// Swap-out rate (pages/s, system wide) that starts shedding. + pub swapout_pages_per_s_shed: u64, + /// VRAM kept free for what the context does not account (cuBLAS workspaces, graphs, driver). + pub vram_headroom: u64, + /// Refuse to start when the fixed footprint does not fit (false: log it and go on). + pub enforce: bool, +} + +impl Policy { + /// 4 GiB soft / 2 GiB hard floors (more on very large hosts), 75% of the elastic memory to an auto cache. + pub fn for_host(mem_total: u64, laptop: bool) -> Self { + Self { + soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB), + hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB), + reserve: GIB, + hysteresis: GIB, + cache_share_percent: 75, + prefix_cap: if laptop { 24 * GIB } else { 96 * GIB }, + min_useful_cache: GIB, + psi_some_shed: 20.0, + psi_full_reject: 5.0, + swapout_pages_per_s_shed: 25_000, + vram_headroom: 512 * MIB, + enforce: true, + } + } +} + +/// What the operator asked of a cache. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CacheWish { + Off, + Auto, + Bytes(u64), +} + +/// How the sealed KAR archive is held. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum KarForm { + /// Inherited sealed memfd, already resident (already out of `MemAvailable`). + MemfdInherited { bytes: u64 }, + /// This process creates the memfd: its bytes are still to be taken from `MemAvailable`. + MemfdToCreate { bytes: u64 }, + /// A read-only file (laptop profile): the OS file cache holds what is read. + File { bytes: u64 }, +} + +/// A host allocation the runtime has yet to make. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct FixedItem { + pub name: String, + pub bytes: u64, + pub space: Space, + pub formula: String, +} + +impl FixedItem { + pub fn new(name: &str, bytes: u64, space: Space, formula: &str) -> Self { + Self { name: name.to_owned(), bytes, space, formula: formula.to_owned() } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct VramFacts { + pub free: u64, + pub total: u64, +} + +#[derive(Clone, Debug, Serialize)] +pub struct PlanInput { + pub host: HostFacts, + pub policy: Policy, + pub kar: KarForm, + pub fixed: Vec, + pub prefix: CacheWish, + /// Conversation checkpoints (`--prompt-cache N`), used only when there is no prefix cache. + pub conversation_checkpoints: u64, + pub checkpoint_bytes: u64, + /// `--resident-budget-gib` in bytes (pinned complement of the expert bank), if asked. + pub resident_complement: Option, + pub vram: Option, + /// The context's declared device budget (`--gpu-budget`). + pub vram_budget: u64, + /// A measured lower bound of the device footprint; `None` = only warn. + pub vram_fixed_estimate: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct VramPlan { + pub free: u64, + pub total: u64, + pub budget: u64, + pub headroom: u64, +} + +/// A granted budget. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Plan { + pub available_before: Option, + pub kar_to_create: u64, + pub fixed_bytes: u64, + pub fixed: Vec, + pub available_after_fixed: Option, + pub elastic: u64, + pub resident_complement_bytes: u64, + pub prefix_bytes: u64, + pub conversation_checkpoints: u64, + pub conversation_bytes: u64, + pub soft_floor: u64, + pub hard_floor: u64, + pub policy: Policy, + /// Telemetry was missing: caches are off, the monitor sheds. + pub blind: bool, + pub vram: Option, + /// Everything the plan changed from what was asked, and every warning. + pub notes: Vec, +} + +/// A refusal to start. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Refusal { + pub code: &'static str, + pub message: String, + pub numbers: Vec<(String, u64)>, + pub advice: Vec, +} + +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "memory budget refused ({}): {}", self.code, self.message)?; + for (name, bytes) in &self.numbers { + write!(f, "; {name} = {}", gib(*bytes))?; + } + for a in &self.advice { + write!(f, "; change: {a}")?; + } + Ok(()) + } +} + +impl std::error::Error for Refusal {} + +pub fn gib(bytes: u64) -> String { + format!("{:.2} GiB", bytes as f64 / GIB as f64) +} + +/// The budget. Pure: no file system, no clock. +pub fn plan(input: &PlanInput) -> Result { + let policy = input.policy; + let mut notes: Vec = Vec::new(); + let fixed_bytes: u64 = input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum(); + let kar_to_create = match input.kar { + KarForm::MemfdToCreate { bytes } => bytes, + KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0, + }; + let vram = input.vram.map(|v| VramPlan { free: v.free, total: v.total, budget: input.vram_budget, headroom: policy.vram_headroom }); + if let (Some(v), Some(estimate)) = (&vram, input.vram_fixed_estimate) { + if v.free < estimate.saturating_add(v.headroom) && policy.enforce { + return Err(Refusal { + code: "vram", + message: format!("the device footprint does not fit: {} free of {} total", gib(v.free), gib(v.total)), + numbers: vec![ + ("vram free".into(), v.free), + ("vram fixed footprint".into(), estimate), + ("vram headroom".into(), v.headroom), + ], + advice: vec![ + "stop the other GPU processes (nvidia-smi)".into(), + "lower --gpu-budget / the expert slots / --kv-resident".into(), + ], + }); + } + } + if let Some(v) = &vram { + if v.free < v.budget { + notes.push(format!( + "VRAM free {} is below the declared --gpu-budget {}: the stack may run out of device memory while it opens", + gib(v.free), + gib(v.budget) + )); + } + } + let Some(available) = input.host.effective_available() else { + notes.push("host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)".into()); + return Ok(Plan { + available_before: None, + kar_to_create, + fixed_bytes, + fixed: input.fixed.clone(), + available_after_fixed: None, + elastic: 0, + resident_complement_bytes: 0, + prefix_bytes: 0, + conversation_checkpoints: 0, + conversation_bytes: 0, + soft_floor: policy.soft_floor, + hard_floor: policy.hard_floor, + policy, + blind: true, + vram, + notes, + }); + }; + let needs = fixed_bytes.saturating_add(kar_to_create); + let required_after = policy.soft_floor.saturating_add(policy.reserve); + let after = available.checked_sub(needs); + if after.is_none_or(|r| r < required_after) { + let mut advice = vec![ + "free host memory (stop other processes; `free -g` and the MemAvailable line of /proc/meminfo)".into(), + "use `--expert-source mapped` (read-only mappings of shard 0) instead of the ~50 GB resident copy".into(), + "use `--kar-archive-file` (read-only file) instead of a sealed memfd on small hosts".into(), + "lower --context-tokens (the pinned K/V image is sized by the serving context)".into(), + ]; + if input.host.wsl { + advice.push(wsl_advice().into()); + } + if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { + advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); + } + let mut numbers = vec![ + ("available".to_owned(), available), + ("fixed host footprint".to_owned(), fixed_bytes), + ]; + if kar_to_create > 0 { + numbers.push(("sealed KAR memfd to create".to_owned(), kar_to_create)); + } + numbers.push(("soft floor + reserve".to_owned(), required_after)); + numbers.push(("short by".to_owned(), required_after.saturating_add(needs).saturating_sub(available))); + let refusal = Refusal { + code: "host_ram", + message: format!( + "the fixed host footprint ({}) leaves {} of {} available, below the {} the runtime needs to stay out of swap and the OOM killer", + gib(needs), + after.map_or("nothing".to_owned(), gib), + gib(available), + gib(required_after) + ), + numbers, + advice, + }; + if policy.enforce { + return Err(refusal); + } + notes.push(format!("ENFORCEMENT OFF: {refusal}")); + } + let after = after.unwrap_or(0); + let mut elastic = after.saturating_sub(required_after); + + // 1. the resident complement (explicit, pinned at open) + let mut complement = 0; + if let Some(wish) = input.resident_complement { + complement = wish.min(elastic); + if complement < wish { + notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement))); + } + elastic -= complement; + } + // 2. the prefix cache, or the conversation checkpoints it replaces + let (mut prefix_bytes, mut checkpoints, mut conversation_bytes) = (0, 0, 0); + match input.prefix { + CacheWish::Off => { + let each = input.checkpoint_bytes.max(1); + checkpoints = input.conversation_checkpoints.min(elastic / each); + if checkpoints < input.conversation_checkpoints { + notes.push(format!( + "conversation checkpoints reduced from {} to {checkpoints} ({} each, elastic memory {})", + input.conversation_checkpoints, + gib(input.checkpoint_bytes), + gib(elastic) + )); + } + conversation_bytes = checkpoints * input.checkpoint_bytes; + } + CacheWish::Auto => { + let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; + let bytes = share.min(policy.prefix_cap) / MIB * MIB; + if bytes < policy.min_useful_cache { + notes.push(format!( + "prefix cache off: auto budget {} is below the useful minimum {}", + gib(bytes), + gib(policy.min_useful_cache) + )); + } else { + prefix_bytes = bytes; + } + } + CacheWish::Bytes(wish) => { + prefix_bytes = wish.min(elastic) / MIB * MIB; + if prefix_bytes < wish { + notes.push(format!( + "prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory", + gib(wish), + gib(prefix_bytes), + gib(elastic) + )); + } + } + } + Ok(Plan { + available_before: Some(available), + kar_to_create, + fixed_bytes, + fixed: input.fixed.clone(), + available_after_fixed: Some(after), + elastic: elastic + complement, + resident_complement_bytes: complement, + prefix_bytes, + conversation_checkpoints: checkpoints, + conversation_bytes, + soft_floor: policy.soft_floor, + hard_floor: policy.hard_floor, + policy, + blind: false, + vram, + notes, + }) +} + +/// The `auto` prefix budget recomputed from the memory available when the stack opens (after the expert bank and the +/// other fixed items are really resident): the same rule as [`plan`] with `fixed = 0`. +pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pinned: u64) -> u64 { + let Some(available) = available else { return 0 }; + let required = policy.soft_floor.saturating_add(policy.reserve); + let elastic = available.saturating_sub(required).saturating_sub(complement_pinned.min(available)); + let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; + let bytes = share.min(policy.prefix_cap) / MIB * MIB; + if bytes < policy.min_useful_cache { 0 } else { bytes } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::FakeProc; + + fn host(total_kib: u64, avail_kib: u64) -> HostFacts { + HostFacts::probe(&FakeProc::default().with( + "/proc/meminfo", + &format!("MemTotal: {total_kib} kB\nMemAvailable: {avail_kib} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), + )) + } + const fn g(n: u64) -> u64 { + n * GIB + } + + /// The 5090 server before the engine allocates: 121 GiB, the sealed memfd resident, ~67 GB available. + fn server_input(available_gib: u64) -> PlanInput { + PlanInput { + host: host(124_112_000, available_gib * 1024 * 1024), + policy: Policy::for_host(g(121), false), + kar: KarForm::MemfdInherited { bytes: 55_295_529_472 }, + fixed: vec![ + FixedItem::new("expert_bank", 54_000_000_000, Space::HostPinned, "routed experts of shard 0"), + FixedItem::new("kv_host", 3_321_901_056, Space::HostPinned, "12 layers x 262144 cells x 1056 B"), + FixedItem::new("rings", 2 * g(1), Space::HostPinned, "staging rings"), + ], + prefix: CacheWish::Auto, + conversation_checkpoints: 6, + checkpoint_bytes: 118 * MIB, + resident_complement: None, + vram: Some(VramFacts { free: g(31), total: g(32) }), + vram_budget: g(24), + vram_fixed_estimate: None, + } + } + + #[test] + fn the_5090_server_gets_an_auto_prefix_cache_from_what_is_left() { + let plan = plan(&server_input(75)).unwrap(); + // 75 GiB - (54e9 + 3.32e9 + 2 GiB) = ~19.3 GiB left; soft 4 + reserve 1 -> 14.3 GiB elastic; 75% -> ~10.7 GiB + assert!(plan.available_after_fixed.unwrap() > g(19) && plan.available_after_fixed.unwrap() < g(20), "{plan:?}"); + assert!(plan.prefix_bytes > g(10) && plan.prefix_bytes < g(11), "{}", plan.prefix_bytes); + assert_eq!(plan.prefix_bytes % MIB, 0); + assert_eq!(plan.soft_floor, g(4)); + assert_eq!(plan.hard_floor, g(2)); + assert!(!plan.blind); + } + + #[test] + fn a_host_that_cannot_hold_the_fixed_footprint_is_refused_with_numbers_and_advice() { + let refusal = plan(&server_input(58)).unwrap_err(); + assert_eq!(refusal.code, "host_ram"); + let text = refusal.to_string(); + assert!(text.contains("available = 58.00 GiB"), "{text}"); + assert!(text.contains("fixed host footprint = 55.") || text.contains("fixed host footprint = 56."), "{text}"); + assert!(text.contains("--expert-source mapped") && text.contains("--kar-archive-file"), "{text}"); + assert!(refusal.numbers.iter().any(|(n, v)| n == "short by" && *v > 0)); + } + + #[test] + fn a_second_model_process_beside_the_holder_is_refused() { + // history (1): the 55 GB memfd is resident and a second process asks for its own 54 GB bank with ~20 GiB available + let refusal = plan(&server_input(20)).unwrap_err(); + assert_eq!(refusal.code, "host_ram"); + assert!(refusal.message.contains("below the")); + } + + #[test] + fn creating_the_memfd_ourselves_counts_against_available() { + let mut input = server_input(75); + input.kar = KarForm::MemfdToCreate { bytes: 55_295_529_472 }; + assert_eq!(plan(&input).unwrap_err().code, "host_ram"); + input.host = host(124_112_000, 140 * 1024 * 1024); + let ok = plan(&input).unwrap(); + assert_eq!(ok.kar_to_create, 55_295_529_472); + assert!(ok.prefix_bytes > 0); + } + + #[test] + fn an_explicit_cache_larger_than_the_elastic_memory_is_clamped_and_reported() { + let mut input = server_input(75); + input.prefix = CacheWish::Bytes(g(40)); + let p = plan(&input).unwrap(); + assert!(p.prefix_bytes < g(15), "{}", p.prefix_bytes); + assert!(p.notes.iter().any(|n| n.contains("clamped")), "{:?}", p.notes); + input.prefix = CacheWish::Bytes(g(2)); + assert_eq!(plan(&input).unwrap().prefix_bytes, g(2)); + } + + #[test] + fn the_resident_complement_is_served_first_and_the_prefix_cache_gets_the_rest() { + let mut input = server_input(75); + input.resident_complement = Some(g(8)); + let p = plan(&input).unwrap(); + assert_eq!(p.resident_complement_bytes, g(8)); + let without = plan(&server_input(75)).unwrap(); + assert!(p.prefix_bytes < without.prefix_bytes); + input.resident_complement = Some(g(100)); + let p = plan(&input).unwrap(); + assert!(p.resident_complement_bytes < g(15) && p.prefix_bytes == 0, "{p:?}"); + } + + #[test] + fn the_conversation_cache_shrinks_instead_of_overrunning() { + let mut input = server_input(75); + input.prefix = CacheWish::Off; + assert_eq!(plan(&input).unwrap().conversation_checkpoints, 6); + input.checkpoint_bytes = g(4); + let p = plan(&input).unwrap(); + assert_eq!(p.conversation_checkpoints, 3, "14.3 GiB elastic / 4 GiB"); + assert!(p.notes.iter().any(|n| n.contains("reduced"))); + } + + #[test] + fn missing_telemetry_turns_the_caches_off_and_marks_the_plan_blind() { + let mut input = server_input(75); + input.host = HostFacts::probe(&FakeProc::default()); + let p = plan(&input).unwrap(); + assert!(p.blind); + assert_eq!((p.prefix_bytes, p.conversation_checkpoints), (0, 0)); + } + + #[test] + fn the_laptop_profile_with_a_file_archive_and_mapped_experts_fits_in_wsl() { + // RTX 3080 laptop, WSL2 with ~38 GiB, mapped experts: only the pinned K/V image and the rings are fixed + let mut input = server_input(35); + input.host = host(39_800_000, 35 * 1024 * 1024); + input.policy = Policy::for_host(g(38), true); + input.kar = KarForm::File { bytes: 55_295_529_472 }; + input.fixed = vec![FixedItem::new("kv_host", 2 * g(1), Space::HostPinned, "12 x cells x 1056")]; + let p = plan(&input).unwrap(); + assert!(p.prefix_bytes > g(15) && p.prefix_bytes <= g(24), "{}", p.prefix_bytes); + } + + #[test] + fn wsl_refusals_carry_the_wslconfig_advice() { + let mut input = server_input(40); + input.host.wsl = true; + let text = plan(&input).unwrap_err().to_string(); + assert!(text.contains(".wslconfig"), "{text}"); + } + + #[test] + fn enforcement_off_turns_a_refusal_into_a_logged_note() { + let mut input = server_input(58); + input.policy.enforce = false; + let p = plan(&input).unwrap(); + assert!(p.notes.iter().any(|n| n.contains("ENFORCEMENT OFF"))); + assert_eq!(p.prefix_bytes, 0); + } + + #[test] + fn a_vram_estimate_that_does_not_fit_refuses_and_a_missing_one_only_warns() { + let mut input = server_input(75); + input.vram = Some(VramFacts { free: g(10), total: g(32) }); + let p = plan(&input).unwrap(); + assert!(p.notes.iter().any(|n| n.contains("--gpu-budget")), "{:?}", p.notes); + input.vram_fixed_estimate = Some(g(20)); + let r = plan(&input).unwrap_err(); + assert_eq!(r.code, "vram"); + assert!(r.to_string().contains("vram free = 10.00 GiB")); + } + + #[test] + fn auto_budget_at_open_follows_the_same_rule_and_fails_closed() { + let p = Policy::for_host(g(121), false); + assert_eq!(auto_prefix_budget(None, &p, 0), 0); + assert_eq!(auto_prefix_budget(Some(g(5)), &p, 0), 0); + // job 922: 22 GiB available at open + let b = auto_prefix_budget(Some(g(22)), &p, 0); + assert!(b > g(12) && b < g(13), "{b}"); + assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b); + assert_eq!(auto_prefix_budget(Some(g(1000)), &p, 0), g(96)); + } + + #[test] + fn floors_scale_with_very_large_hosts_only() { + let small = Policy::for_host(g(38), true); + assert_eq!((small.soft_floor, small.hard_floor), (g(4), g(2))); + let big = Policy::for_host(g(1024), false); + assert_eq!(big.soft_floor, g(32)); + assert_eq!(big.hard_floor, g(16)); + } +} diff --git a/crates/leleka-memory/src/pressure.rs b/crates/leleka-memory/src/pressure.rs new file mode 100644 index 00000000..f25254c3 --- /dev/null +++ b/crates/leleka-memory/src/pressure.rs @@ -0,0 +1,365 @@ +//! The runtime pressure state machine: from periodic samples of `MemAvailable`, PSI, the cgroup event counters and +//! the swap-out rate to one of three levels, with hysteresis so a reading on a threshold does not flap. +//! +//! * [`Level::Normal`]: caches grow under their budgets. +//! * [`Level::Shed`]: the caches stop admitting and give memory back (prefix cache evicted, conversation checkpoints +//! dropped); requests are still served. +//! * [`Level::Reject`]: new requests are refused with 503 `memory_pressure` and `Retry-After`; everything sheddable is shed. +//! +//! Unknown telemetry never reads as "plenty": a missing `MemAvailable` holds the level at `Shed`. + +use crate::plan::Policy; +use crate::procfs::{CgroupEvents, Psi}; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Level { + Normal = 0, + Shed = 1, + Reject = 2, +} + +impl Level { + pub fn from_u8(v: u8) -> Level { + match v { + 0 => Level::Normal, + 1 => Level::Shed, + _ => Level::Reject, + } + } + pub fn as_str(self) -> &'static str { + match self { + Level::Normal => "normal", + Level::Shed => "shed", + Level::Reject => "reject", + } + } +} + +/// One reading. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Sample { + /// Milliseconds since an arbitrary epoch (monotonic). + pub at_ms: u64, + /// Effective available bytes (`MemAvailable` limited by the cgroup headroom). + pub available: Option, + pub psi: Option, + pub events: Option, + /// System-wide `pswpout` counter. + pub pswpout: Option, +} + +/// Why a level was chosen (for the log and the report). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Reason(pub String); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Transition { + pub from: Level, + pub to: Level, + pub reason: Reason, +} + +/// What the level was last evaluated from, for the report. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] +pub struct Observed { + pub available: Option, + pub psi_some_avg10: Option, + pub psi_full_avg10: Option, + pub swapout_pages_per_s: Option, + pub cgroup_high_delta: u64, + pub cgroup_max_delta: u64, + pub cgroup_oom_delta: u64, +} + +#[derive(Clone, Debug)] +pub struct Monitor { + policy: Policy, + level: Level, + /// Consecutive samples that would allow a lower level. + calm: u32, + prev_events: Option, + prev_swap: Option<(u64, u64)>, + pub observed: Observed, +} + +/// Calm samples needed to step down one level. +pub const CALM_SAMPLES: u32 = 3; + +impl Monitor { + pub fn new(policy: Policy) -> Self { + Self { policy, level: Level::Normal, calm: 0, prev_events: None, prev_swap: None, observed: Observed::default() } + } + pub fn level(&self) -> Level { + self.level + } + pub fn policy(&self) -> &Policy { + &self.policy + } + + /// The level the sample asks for, with the margin added to every threshold when `relaxed` (stepping down). + fn target(&mut self, s: &Sample) -> (Level, String, Level) { + let p = &self.policy; + let mut level = Level::Normal; + let mut why = String::from("within budget"); + // the level the sample asks for if the hysteresis margin is applied (to decide a step down) + let mut relaxed_level = Level::Normal; + let mut raise = |l: Level, relaxed: Level, reason: String, level: &mut Level, why: &mut String, rl: &mut Level| { + if l > *level { + *level = l; + *why = reason; + } + if relaxed > *rl { + *rl = relaxed; + } + }; + match s.available { + None => raise( + Level::Shed, + Level::Shed, + "available memory unknown (fail closed)".into(), + &mut level, + &mut why, + &mut relaxed_level, + ), + Some(a) => { + let (hard, soft, h) = (p.hard_floor, p.soft_floor, p.hysteresis); + let at = |floor: u64| a < floor; + let at_relaxed = |floor: u64| a < floor.saturating_add(h); + if at(hard) { + raise(Level::Reject, Level::Reject, format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20), &mut level, &mut why, &mut relaxed_level); + } else if at(soft) { + raise(Level::Shed, Level::Shed, format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20), &mut level, &mut why, &mut relaxed_level); + } + // what the relaxed (stepping-down) view still holds + let r = if at_relaxed(hard) { + Level::Reject + } else if at_relaxed(soft) { + Level::Shed + } else { + Level::Normal + }; + if r > relaxed_level { + relaxed_level = r; + } + } + } + if let Some(psi) = s.psi { + self.observed.psi_some_avg10 = Some(psi.some.avg10); + self.observed.psi_full_avg10 = Some(psi.full.avg10); + if psi.full.avg10 >= p.psi_full_reject { + raise(Level::Reject, Level::Reject, format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject), &mut level, &mut why, &mut relaxed_level); + } else if psi.some.avg10 >= p.psi_some_shed { + raise(Level::Shed, Level::Shed, format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed), &mut level, &mut why, &mut relaxed_level); + } + // PSI avg10 decays smoothly; stepping down needs it clearly below the limit + if psi.full.avg10 >= p.psi_full_reject / 2.0 { + relaxed_level = relaxed_level.max(Level::Shed); + } + if psi.some.avg10 >= p.psi_some_shed / 2.0 { + relaxed_level = relaxed_level.max(Level::Shed); + } + } else { + self.observed.psi_some_avg10 = None; + self.observed.psi_full_avg10 = None; + } + if let (Some(now), Some(before)) = (s.events, self.prev_events) { + let d = |a: u64, b: u64| a.saturating_sub(b); + self.observed.cgroup_high_delta = d(now.high, before.high); + self.observed.cgroup_max_delta = d(now.max, before.max); + self.observed.cgroup_oom_delta = d(now.oom, before.oom).max(d(now.oom_kill, before.oom_kill)); + if self.observed.cgroup_oom_delta > 0 { + raise(Level::Reject, Level::Reject, format!("cgroup oom events +{}", self.observed.cgroup_oom_delta), &mut level, &mut why, &mut relaxed_level); + } else if self.observed.cgroup_max_delta > 0 || self.observed.cgroup_high_delta > 0 { + raise( + Level::Shed, + Level::Shed, + format!("cgroup memory.high +{} / memory.max +{} events", self.observed.cgroup_high_delta, self.observed.cgroup_max_delta), + &mut level, + &mut why, + &mut relaxed_level, + ); + } + } + if s.events.is_some() { + self.prev_events = s.events; + } + if let Some(out) = s.pswpout { + if let Some((t0, o0)) = self.prev_swap { + let dt = s.at_ms.saturating_sub(t0); + if dt >= 500 { + let rate = out.saturating_sub(o0) * 1000 / dt; + self.observed.swapout_pages_per_s = Some(rate); + if rate >= p.swapout_pages_per_s_shed { + raise(Level::Shed, Level::Shed, format!("swap-out {rate} pages/s (limit {})", p.swapout_pages_per_s_shed), &mut level, &mut why, &mut relaxed_level); + } + if rate >= p.swapout_pages_per_s_shed / 2 { + relaxed_level = relaxed_level.max(Level::Shed); + } + self.prev_swap = Some((s.at_ms, out)); + } + } else { + self.prev_swap = Some((s.at_ms, out)); + } + } + self.observed.available = s.available; + (level, why, relaxed_level) + } + + /// Feed one sample. Escalation is immediate; stepping down one level needs [`CALM_SAMPLES`] calm samples. + pub fn update(&mut self, s: &Sample) -> Option { + let (wanted, why, relaxed) = self.target(s); + let from = self.level; + if wanted > from { + self.level = wanted; + self.calm = 0; + return Some(Transition { from, to: wanted, reason: Reason(why) }); + } + if wanted == from && relaxed >= from { + self.calm = 0; + return None; + } + // the sample would allow a lower level than the current one (wanted < from), but only count it as calm when + // the margin-adjusted view also allows it + if relaxed < from { + self.calm += 1; + if self.calm >= CALM_SAMPLES { + self.calm = 0; + let to = if from == Level::Reject { Level::Shed.max(relaxed) } else { relaxed }; + self.level = to; + return Some(Transition { from, to, reason: Reason(format!("recovered: {why}")) }); + } + } else { + self.calm = 0; + } + None + } + + /// Retry-After for a refusal at this level, seconds. + pub fn retry_after_secs(&self) -> u64 { + match self.level { + Level::Normal => 0, + Level::Shed => 5, + Level::Reject => 15, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plan::GIB; + use crate::procfs::PsiLine; + + fn monitor() -> Monitor { + Monitor::new(Policy::for_host(121 * GIB, false)) + } + fn avail(m: &mut Monitor, at_ms: u64, bytes: u64) -> Option { + m.update(&Sample { at_ms, available: Some(bytes), ..Sample::default() }) + } + + #[test] + fn plenty_of_memory_stays_normal() { + let mut m = monitor(); + for i in 0..10 { + assert!(avail(&mut m, i * 1000, 20 * GIB).is_none()); + } + assert_eq!(m.level(), Level::Normal); + } + + #[test] + fn dropping_below_the_floors_escalates_at_once() { + let mut m = monitor(); + let t = avail(&mut m, 0, 3 * GIB).unwrap(); + assert_eq!((t.from, t.to), (Level::Normal, Level::Shed)); + assert!(t.reason.0.contains("soft floor"), "{:?}", t.reason); + let t = avail(&mut m, 1000, GIB).unwrap(); + assert_eq!((t.from, t.to), (Level::Shed, Level::Reject)); + assert_eq!(m.retry_after_secs(), 15); + } + + #[test] + fn stepping_down_needs_calm_samples_and_the_hysteresis_margin() { + let mut m = monitor(); + avail(&mut m, 0, GIB); + assert_eq!(m.level(), Level::Reject); + // just above the hard floor but inside the hysteresis band: stays + for i in 1..10 { + assert!(avail(&mut m, i * 1000, 2 * GIB + GIB / 2).is_none(), "inside the band at sample {i}"); + } + assert_eq!(m.level(), Level::Reject); + // clearly above hard + margin, below soft: steps down to Shed after 3 calm samples + assert!(avail(&mut m, 20_000, 3 * GIB + GIB / 2).is_none()); + assert!(avail(&mut m, 21_000, 3 * GIB + GIB / 2).is_none()); + let t = avail(&mut m, 22_000, 3 * GIB + GIB / 2).unwrap(); + assert_eq!((t.from, t.to), (Level::Reject, Level::Shed)); + // and to Normal only well above the soft floor + margin + for i in 0..2 { + assert!(avail(&mut m, 30_000 + i * 1000, 6 * GIB).is_none()); + } + let t = avail(&mut m, 33_000, 6 * GIB).unwrap(); + assert_eq!(t.to, Level::Normal); + } + + #[test] + fn one_calm_sample_between_bad_ones_does_not_step_down() { + let mut m = monitor(); + avail(&mut m, 0, 3 * GIB); + for i in 0..6u64 { + let a = if i % 2 == 0 { 20 * GIB } else { 3 * GIB }; + avail(&mut m, 1000 * (i + 1), a); + } + assert_eq!(m.level(), Level::Shed); + } + + #[test] + fn unknown_available_memory_holds_shed() { + let mut m = monitor(); + let t = m.update(&Sample::default()).unwrap(); + assert_eq!(t.to, Level::Shed); + assert!(t.reason.0.contains("unknown")); + for i in 1..10 { + assert!(m.update(&Sample { at_ms: i * 1000, ..Sample::default() }).is_none()); + } + assert_eq!(m.level(), Level::Shed); + } + + #[test] + fn psi_stalls_shed_and_reject_independent_of_available_memory() { + let mut m = monitor(); + let psi = |some: f64, full: f64| Some(Psi { some: PsiLine { avg10: some, ..Default::default() }, full: PsiLine { avg10: full, ..Default::default() } }); + let t = m.update(&Sample { at_ms: 0, available: Some(30 * GIB), psi: psi(30.0, 0.0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Shed); + assert!(t.reason.0.contains("PSI some")); + let t = m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), psi: psi(40.0, 9.0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Reject); + // a quiet PSI with plenty of memory recovers after the calm samples + for i in 0..3 { + m.update(&Sample { at_ms: 2000 + i * 1000, available: Some(30 * GIB), psi: psi(0.0, 0.0), ..Sample::default() }); + } + assert_eq!(m.level(), Level::Shed); + } + + #[test] + fn cgroup_oom_and_high_events_escalate_by_their_delta() { + let mut m = monitor(); + let ev = |high, max, oom, kill| Some(CgroupEvents { low: 0, high, max, oom, oom_kill: kill }); + assert!(m.update(&Sample { at_ms: 0, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }).is_none(), "the first reading is the baseline"); + assert!(m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }).is_none()); + let t = m.update(&Sample { at_ms: 2000, available: Some(30 * GIB), events: ev(6, 5, 0, 0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Shed); + let t = m.update(&Sample { at_ms: 3000, available: Some(30 * GIB), events: ev(6, 5, 1, 0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Reject); + assert_eq!(m.observed.cgroup_oom_delta, 1); + } + + #[test] + fn a_swap_out_storm_sheds() { + let mut m = monitor(); + m.update(&Sample { at_ms: 0, available: Some(30 * GIB), pswpout: Some(1000), ..Sample::default() }); + let t = m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), pswpout: Some(1000 + 100_000), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Shed); + assert_eq!(m.observed.swapout_pages_per_s, Some(100_000)); + } +} diff --git a/crates/leleka-memory/src/procfs.rs b/crates/leleka-memory/src/procfs.rs new file mode 100644 index 00000000..437d55e0 --- /dev/null +++ b/crates/leleka-memory/src/procfs.rs @@ -0,0 +1,408 @@ +//! Pure parsers for the kernel text interfaces the memory governor reads: `/proc/meminfo`, `/proc/self/status`, +//! `/proc/self/limits`, `/proc/self/smaps`, `/proc/vmstat`, `/proc/pressure/memory` and the cgroup v2 files. +//! +//! Every parser takes text, never touches the file system, allocates only what it returns and treats malformed input +//! as "unknown" (`None`) rather than as zero: a governor that read a missing number as 0 would either shed everything +//! or admit everything. They are the part of the crate that runs under Miri. + +const KIB: u64 = 1024; + +fn kib(value: &str, unit: Option<&str>) -> Option { + let n: u64 = value.parse().ok()?; + match unit { + Some("kB") => n.checked_mul(KIB), + None => Some(n), + Some(_) => None, + } +} + +/// `/proc/meminfo`, in bytes. A field the kernel did not print is `None`. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct MemInfo { + pub mem_total: Option, + pub mem_free: Option, + pub mem_available: Option, + pub buffers: Option, + pub cached: Option, + pub swap_cached: Option, + pub swap_total: Option, + pub swap_free: Option, + pub shmem: Option, + pub mlocked: Option, + pub unevictable: Option, + pub anon_pages: Option, + pub active_file: Option, + pub inactive_file: Option, + pub hugetlb: Option, + pub hugepages_total: Option, + pub hugepage_size: Option, +} + +/// Parse `/proc/meminfo` text. A duplicated key makes that field unknown (never "the last one wins"). +pub fn parse_meminfo(text: &str) -> MemInfo { + let mut info = MemInfo::default(); + let mut seen: Vec<&str> = Vec::new(); + let mut poisoned: Vec<&str> = Vec::new(); + for line in text.lines() { + let Some((key, rest)) = line.split_once(':') else { continue }; + let mut fields = rest.split_ascii_whitespace(); + let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; + if fields.next().is_some() { + poisoned.push(key); + continue; + } + if seen.contains(&key) { + poisoned.push(key); + continue; + } + seen.push(key); + let parsed = if key == "HugePages_Total" { value.parse().ok() } else { kib(value, unit) }; + let slot = match key { + "MemTotal" => &mut info.mem_total, + "MemFree" => &mut info.mem_free, + "MemAvailable" => &mut info.mem_available, + "Buffers" => &mut info.buffers, + "Cached" => &mut info.cached, + "SwapCached" => &mut info.swap_cached, + "SwapTotal" => &mut info.swap_total, + "SwapFree" => &mut info.swap_free, + "Shmem" => &mut info.shmem, + "Mlocked" => &mut info.mlocked, + "Unevictable" => &mut info.unevictable, + "AnonPages" => &mut info.anon_pages, + "Active(file)" => &mut info.active_file, + "Inactive(file)" => &mut info.inactive_file, + "Hugetlb" => &mut info.hugetlb, + "HugePages_Total" => &mut info.hugepages_total, + "Hugepagesize" => &mut info.hugepage_size, + _ => continue, + }; + *slot = parsed; + } + for key in poisoned { + match key { + "MemTotal" => info.mem_total = None, + "MemFree" => info.mem_free = None, + "MemAvailable" => info.mem_available = None, + "SwapTotal" => info.swap_total = None, + "SwapFree" => info.swap_free = None, + "Shmem" => info.shmem = None, + _ => {} + } + } + info +} + +/// `/proc/self/status` memory and task fields, in bytes (counts for threads). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct ProcStatus { + pub vm_rss: Option, + pub vm_hwm: Option, + pub vm_swap: Option, + /// Locked with `mlock` (`VmLck`). + pub vm_lck: Option, + /// Long-term pinned by drivers (`VmPin`, `cuMemHostRegister`/`cuMemHostAlloc` pages). + pub vm_pin: Option, + pub rss_anon: Option, + pub rss_file: Option, + pub rss_shmem: Option, + pub threads: Option, + /// `CapEff` bitmask (bit 14 is CAP_IPC_LOCK: mlock without the RLIMIT_MEMLOCK ceiling). + pub cap_eff: Option, +} + +pub fn parse_status(text: &str) -> ProcStatus { + let mut status = ProcStatus::default(); + for line in text.lines() { + let Some((key, rest)) = line.split_once(':') else { continue }; + let mut fields = rest.split_ascii_whitespace(); + let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; + let slot = match key { + "VmRSS" => &mut status.vm_rss, + "VmHWM" => &mut status.vm_hwm, + "VmSwap" => &mut status.vm_swap, + "VmLck" => &mut status.vm_lck, + "VmPin" => &mut status.vm_pin, + "RssAnon" => &mut status.rss_anon, + "RssFile" => &mut status.rss_file, + "RssShmem" => &mut status.rss_shmem, + "Threads" => { + status.threads = value.parse().ok(); + continue; + } + "CapEff" => { + status.cap_eff = u64::from_str_radix(value, 16).ok(); + continue; + } + _ => continue, + }; + *slot = kib(value, unit); + } + status +} + +/// `Max locked memory` of `/proc/self/limits`: (soft, hard), `u64::MAX` = unlimited. +pub fn parse_memlock_limit(text: &str) -> Option<(u64, u64)> { + let line = text.lines().find(|l| l.starts_with("Max locked memory"))?; + let rest = line["Max locked memory".len()..].split_ascii_whitespace().collect::>(); + let value = |s: &str| if s == "unlimited" { Some(u64::MAX) } else { s.parse::().ok() }; + let (soft, hard) = (value(rest.first()?)?, value(rest.get(1)?)?); + Some((soft, hard)) +} + +/// One `some`/`full` line of a PSI file. +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] +pub struct PsiLine { + pub avg10: f64, + pub avg60: f64, + pub avg300: f64, + pub total_us: u64, +} + +/// `/proc/pressure/memory` (or a cgroup's `memory.pressure`). +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] +pub struct Psi { + pub some: PsiLine, + pub full: PsiLine, +} + +pub fn parse_psi(text: &str) -> Option { + let mut psi = Psi::default(); + let (mut some, mut full) = (false, false); + for line in text.lines() { + let mut fields = line.split_ascii_whitespace(); + let kind = fields.next()?; + let mut parsed = PsiLine::default(); + let mut complete = 0; + for field in fields { + let (key, value) = field.split_once('=')?; + match key { + "avg10" => (parsed.avg10, complete) = (value.parse().ok()?, complete + 1), + "avg60" => (parsed.avg60, complete) = (value.parse().ok()?, complete + 1), + "avg300" => (parsed.avg300, complete) = (value.parse().ok()?, complete + 1), + "total" => (parsed.total_us, complete) = (value.parse().ok()?, complete + 1), + _ => {} + } + } + if complete != 4 || !parsed.avg10.is_finite() || !parsed.avg60.is_finite() || !parsed.avg300.is_finite() { + return None; + } + match kind { + "some" => (psi.some, some) = (parsed, true), + "full" => (psi.full, full) = (parsed, true), + _ => return None, + } + } + (some && full).then_some(psi) +} + +/// `key value` files (`memory.stat`, `memory.events`, `/proc/vmstat`): the value of `wanted`, if printed exactly once. +pub fn flat_keyed(text: &str, wanted: &str) -> Option { + let mut found = None; + for line in text.lines() { + let mut fields = line.split_ascii_whitespace(); + if fields.next() == Some(wanted) { + if found.is_some() { + return None; + } + let value = fields.next()?.parse::().ok()?; + if fields.next().is_some() { + return None; + } + found = Some(value); + } + } + found +} + +/// A cgroup v2 limit file: `max` = no limit (`None` inside `Some`), a number, or unreadable (`None`). +pub fn parse_cgroup_limit(text: &str) -> Option> { + let t = text.trim(); + if t == "max" { + return Some(None); + } + t.parse::().ok().map(Some) +} + +/// The unified (v2) hierarchy path of `/proc/self/cgroup`: the line `0::/path`. +pub fn parse_cgroup_path(text: &str) -> Option { + text.lines().find_map(|l| l.strip_prefix("0::")).map(|p| p.trim().to_owned()) +} + +/// `memory.events` counters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct CgroupEvents { + pub low: u64, + pub high: u64, + pub max: u64, + pub oom: u64, + pub oom_kill: u64, +} + +pub fn parse_cgroup_events(text: &str) -> Option { + Some(CgroupEvents { + low: flat_keyed(text, "low")?, + high: flat_keyed(text, "high")?, + max: flat_keyed(text, "max")?, + oom: flat_keyed(text, "oom")?, + oom_kill: flat_keyed(text, "oom_kill")?, + }) +} + +/// One mapping of `/proc/self/smaps`, bytes. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct SmapsEntry { + pub start: u64, + pub end: u64, + pub perms: String, + pub path: String, + pub size: u64, + pub rss: u64, + pub swap: u64, + pub locked: u64, + pub shmem_pmd_mapped: u64, +} + +/// Parse `/proc/self/smaps`. A malformed header or counter line stops the entry (never fabricates numbers). +pub fn parse_smaps(text: &str) -> Vec { + let mut entries: Vec = Vec::new(); + for line in text.lines() { + let first = line.split_ascii_whitespace().next().unwrap_or(""); + let is_header = first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':'); + if is_header { + let mut fields = line.split_ascii_whitespace(); + let range = fields.next().unwrap_or(""); + let perms = fields.next().unwrap_or("").to_owned(); + // offset dev inode [path...] + let _offset = fields.next(); + let _dev = fields.next(); + let _inode = fields.next(); + let path = fields.collect::>().join(" "); + let Some((a, b)) = range.split_once('-') else { continue }; + let (Ok(start), Ok(end)) = (u64::from_str_radix(a, 16), u64::from_str_radix(b, 16)) else { continue }; + entries.push(SmapsEntry { start, end, perms, path, ..SmapsEntry::default() }); + } else if let Some(entry) = entries.last_mut() { + let Some((key, rest)) = line.split_once(':') else { continue }; + let mut fields = rest.split_ascii_whitespace(); + let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; + let Some(bytes) = kib(value, unit) else { continue }; + match key { + "Size" => entry.size = bytes, + "Rss" => entry.rss = bytes, + "Swap" => entry.swap = bytes, + "Locked" => entry.locked = bytes, + "ShmemPmdMapped" => entry.shmem_pmd_mapped = bytes, + _ => {} + } + } + } + entries +} + +#[cfg(test)] +mod tests { + use super::*; + + const MEMINFO: &str = "MemTotal: 127091644 kB\nMemFree: 2612464 kB\nMemAvailable: 20699384 kB\nBuffers: 37200 kB\n\ +Cached: 73044620 kB\nSwapCached: 22052 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n\ +Mlocked: 8724 kB\nUnevictable: 8724 kB\nHugePages_Total: 0\nHugepagesize: 2048 kB\nHugetlb: 0 kB\n"; + + #[test] + fn meminfo_reads_the_5090_server_snapshot() { + let m = parse_meminfo(MEMINFO); + assert_eq!(m.mem_total, Some(127_091_644 * 1024)); + assert_eq!(m.mem_available, Some(20_699_384 * 1024)); + assert_eq!(m.swap_total, Some(65_535_996 * 1024)); + assert_eq!(m.shmem, Some(54_338_244 * 1024)); + assert_eq!(m.hugepages_total, Some(0)); + assert_eq!(m.hugepage_size, Some(2048 * 1024)); + assert_eq!(m.hugetlb, Some(0)); + } + + #[test] + fn meminfo_never_turns_a_malformed_or_duplicated_number_into_a_value() { + for bad in [ + "MemAvailable: -1 kB\n", + "MemAvailable: 1 MB\n", + "MemAvailable: x kB\n", + "MemAvailable: 18446744073709551615 kB\n", + "MemAvailable: 1 kB extra\n", + "MemAvailable: 1 kB\nMemAvailable: 2 kB\n", + ] { + assert_eq!(parse_meminfo(bad).mem_available, None, "{bad:?}"); + } + assert_eq!(parse_meminfo("").mem_total, None); + assert_eq!(parse_meminfo("MemAvailableX: 5 kB\n").mem_available, None); + assert_eq!(parse_meminfo("MemAvailable:\t7\tkB\r\n").mem_available, Some(7 * 1024)); + } + + #[test] + fn status_reads_pinned_locked_and_swap() { + let t = "Name:\tleleka\nVmPeak:\t 1 kB\nVmPin:\t 52428800 kB\nVmHWM:\t 70000000 kB\nVmRSS:\t 61000000 kB\nRssAnon:\t 1000 kB\nRssFile:\t 2000 kB\n\ +RssShmem:\t 3000 kB\nVmSwap:\t 12 kB\nVmLck:\t 8 kB\nThreads:\t 41\nCapEff:\t0000000000004000\n"; + let s = parse_status(t); + assert_eq!(s.vm_pin, Some(52_428_800 * 1024)); + assert_eq!(s.vm_rss, Some(61_000_000 * 1024)); + assert_eq!(s.vm_swap, Some(12 * 1024)); + assert_eq!(s.vm_lck, Some(8 * 1024)); + assert_eq!(s.threads, Some(41)); + assert_eq!(s.cap_eff.map(|c| c & (1 << 14) != 0), Some(true)); + assert_eq!(parse_status("VmRSS: 5 MB\n").vm_rss, None); + } + + #[test] + fn memlock_limit_reads_numbers_and_unlimited() { + let t = "Limit Soft Limit Hard Limit Units \nMax locked memory 8388608 8388608 bytes \nMax address space unlimited unlimited bytes \n"; + assert_eq!(parse_memlock_limit(t), Some((8 << 20, 8 << 20))); + let u = "Max locked memory unlimited unlimited bytes \n"; + assert_eq!(parse_memlock_limit(u), Some((u64::MAX, u64::MAX))); + assert_eq!(parse_memlock_limit("Max stack size 1 2 bytes\n"), None); + } + + #[test] + fn psi_needs_both_lines_and_all_fields() { + let t = "some avg10=0.00 avg60=0.01 avg300=0.00 total=2586497190\nfull avg10=1.50 avg60=0.01 avg300=0.00 total=2572226352\n"; + let p = parse_psi(t).unwrap(); + assert_eq!(p.some.total_us, 2_586_497_190); + assert!((p.full.avg10 - 1.5).abs() < 1e-9); + assert!(parse_psi("some avg10=0.00 avg60=0.01 avg300=0.00 total=1\n").is_none()); + assert!(parse_psi("some avg10=nan avg60=0 avg300=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); + assert!(parse_psi("some avg10=0 avg60=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); + } + + #[test] + fn keyed_files_reject_duplicates_and_trailing_fields() { + assert_eq!(flat_keyed("pswpout 12\npswpin 3\n", "pswpout"), Some(12)); + assert_eq!(flat_keyed("a 1\na 2\n", "a"), None); + assert_eq!(flat_keyed("a 1 2\n", "a"), None); + assert_eq!(flat_keyed("a x\n", "a"), None); + assert_eq!(flat_keyed("", "a"), None); + } + + #[test] + fn cgroup_files() { + assert_eq!(parse_cgroup_limit("max\n"), Some(None)); + assert_eq!(parse_cgroup_limit("1073741824\n"), Some(Some(1 << 30))); + assert_eq!(parse_cgroup_limit("lots"), None); + assert_eq!(parse_cgroup_path("0::/user.slice/user-1000.slice/session-578.scope\n").as_deref(), Some("/user.slice/user-1000.slice/session-578.scope")); + assert_eq!(parse_cgroup_path("12:memory:/x\n"), None); + let e = parse_cgroup_events("low 0\nhigh 3\nmax 4\noom 1\noom_kill 1\n").unwrap(); + assert_eq!((e.high, e.max, e.oom, e.oom_kill), (3, 4, 1, 1)); + assert!(parse_cgroup_events("low 0\nhigh 3\n").is_none()); + } + + #[test] + fn smaps_finds_the_memfd_mapping_with_its_swap() { + let t = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\n\ +Size: 4194304 kB\nKernelPageSize: 4 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n\ +55e0-55e1 r-xp 00000000 08:01 1 /usr/bin/x\nSize: 4 kB\nRss: 4 kB\nSwap: 0 kB\nLocked: 0 kB\n"; + let e = parse_smaps(t); + assert_eq!(e.len(), 2); + assert_eq!(e[0].path, "/memfd:kar-archive (deleted)"); + assert_eq!(e[0].swap, 194_304 * 1024); + assert_eq!(e[0].rss, 4_000_000 * 1024); + assert_eq!(e[0].end - e[0].start, 0x1_0000_0000); + assert_eq!(e[1].path, "/usr/bin/x"); + assert!(parse_smaps("garbage\nSwap: 1 kB\n").is_empty()); + } +}