STRA-338 size: leleka-memory: split guard_archive_extents/residency_tick, plan, pressure target, config env, procfs parsers, cgroup probes, report, sampler; wrap strings and comments; move host tests out (fn_lines 24->0, complexity 11->0, nesting 1->0, width 97->0; context: restore doc-comment slashes)
This commit is contained in:
@@ -155,7 +155,7 @@ pub struct EffectiveContext {
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
//// Refuse a request that cannot be served before any arithmetic runs.
|
||||
/// Refuse a request that cannot be served before any arithmetic runs.
|
||||
fn check_request(req: &ContextRequest) -> Result<(), PolicyError> {
|
||||
if req.slots == 0 {
|
||||
return Err(PolicyError::ZeroSlots);
|
||||
@@ -287,7 +287,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
|
||||
})
|
||||
}
|
||||
|
||||
// The two mandatory charter profiles plus the local one: `(slots, ctx_per_slot)`.
|
||||
/// The two mandatory charter profiles plus the local one: `(slots, ctx_per_slot)`.
|
||||
pub const CHARTER_PROFILES: [(u64, u64); 3] = [(1, 524_288), (2, 262_144), (1, 262_144)];
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! A/B of the memfd residency guard under real memory pressure, model-free. Run it inside a cgroup v2 with `memory.max`
|
||||
//! below `memfd + hog` (the harness script `scripts/memory/swap_ab.sh` does that and restricts the damage to the cgroup): a
|
||||
//! sealed memfd stands in for the 55 GB KAR archive, an anonymous "hog" for the expert bank, and a reader streams a big
|
||||
//! file through the page cache like the Original did next to the memfd.
|
||||
//! below `memfd + hog` (the harness script `scripts/memory/swap_ab.sh` does that and restricts the damage to the
|
||||
//! cgroup): a sealed memfd stands in for the 55 GB KAR archive, an anonymous "hog" for the expert bank, and a reader
|
||||
//! streams a big file through the page cache like the Original did next to the memfd.
|
||||
//!
|
||||
//! ```text
|
||||
//! swap_ab --memfd-mib 6144 --hog-mib 5120 --secs 60 [--reader FILE] [--lock off|try|require] [--heal 0|1] [--hog-release SECS]
|
||||
//! swap_ab --memfd-mib 6144 --hog-mib 5120 --secs 60 [--reader FILE] [--lock off|try|require] [--heal 0|1]
|
||||
//! [--hog-release SECS]
|
||||
//! ```
|
||||
//! Prints one line per second (`AB t=.. memfd_swapped_mib=.. ...`) and a final `AB-RESULT` line.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
@@ -11,7 +11,8 @@ use serde::Serialize;
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct Census {
|
||||
pub rss: u64,
|
||||
/// `RssAnon` / `RssFile` / `RssShmem` of `/proc/self/status`: a leak is an anonymous or shmem slope; file pages are reclaimable.
|
||||
/// `RssAnon` / `RssFile` / `RssShmem` of `/proc/self/status`: a leak is an anonymous or shmem slope; file pages are
|
||||
/// reclaimable.
|
||||
pub rss_anon: u64,
|
||||
pub rss_file: u64,
|
||||
pub rss_shmem: u64,
|
||||
@@ -126,34 +127,34 @@ fn quarter_means(values: &[f64]) -> Option<(f64, f64)> {
|
||||
Some((mean(&values[..q]), mean(&values[values.len() - q..])))
|
||||
}
|
||||
|
||||
/// How a series drifted: the means of its first and last quarter; a series too short to judge is not ok. `None` for a
|
||||
/// device series that is absent (no GPU).
|
||||
fn drift_of(name: &'static str, values: &[f64], tolerance: u64) -> Option<Drift> {
|
||||
if values.is_empty() && name.starts_with("device") {
|
||||
return None;
|
||||
}
|
||||
Some(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 }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<f64>, tolerance: u64| {
|
||||
let values: Vec<f64> = 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);
|
||||
drifts.extend(drift_of(name, &values, tolerance));
|
||||
};
|
||||
add("rss", &|c| Some(c.rss as f64), tol.rss);
|
||||
add("swap", &|c| Some(c.swap as f64), tol.swap);
|
||||
@@ -167,8 +168,9 @@ pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatRep
|
||||
FlatReport { samples: series.len(), warmup, drifts, ok }
|
||||
}
|
||||
|
||||
/// An ordinary-least-squares line through `(x, y)` with its 95% confidence interval, and the Theil-Sen slope (the median of the
|
||||
/// pairwise slopes: robust against the steps a cache filling or a request in flight puts into a memory series).
|
||||
/// An ordinary-least-squares line through `(x, y)` with its 95% confidence interval, and the Theil-Sen slope (the
|
||||
/// median of the pairwise slopes: robust against the steps a cache filling or a request in flight puts into a memory
|
||||
/// series).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
|
||||
pub struct SlopeFit {
|
||||
pub n: usize,
|
||||
@@ -187,9 +189,25 @@ impl SlopeFit {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit `y` against `x`; `None` with fewer than 8 points or no spread in `x`. The interval uses the normal quantile 1.96 (n is in the
|
||||
/// hundreds) and treats samples as independent, which a slowly drifting series is not: read it as a lower bound of the uncertainty and
|
||||
/// look at `theil_sen` next to it.
|
||||
/// The Theil-Sen slope: the median of the pairwise slopes (robust against steps in the series).
|
||||
fn theil_sen(points: &[(f64, f64)]) -> f64 {
|
||||
let n = points.len();
|
||||
let mut slopes = Vec::with_capacity(n * (n - 1) / 2);
|
||||
for i in 0..n {
|
||||
for j in i + 1..n {
|
||||
let dx = points[j].0 - points[i].0;
|
||||
if dx != 0.0 {
|
||||
slopes.push((points[j].1 - points[i].1) / dx);
|
||||
}
|
||||
}
|
||||
}
|
||||
slopes.sort_by(f64::total_cmp);
|
||||
slopes.get(slopes.len() / 2).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Fit `y` against `x`; `None` with fewer than 8 points or no spread in `x`. The interval uses the normal quantile 1.96
|
||||
/// (n is in the hundreds) and treats samples as independent, which a slowly drifting series is not: read it as a lower
|
||||
/// bound of the uncertainty and look at `theil_sen` next to it.
|
||||
pub fn fit_slope(points: &[(f64, f64)]) -> Option<SlopeFit> {
|
||||
let n = points.len();
|
||||
if n < 8 {
|
||||
@@ -207,23 +225,12 @@ pub fn fit_slope(points: &[(f64, f64)]) -> Option<SlopeFit> {
|
||||
let sse: f64 = points.iter().map(|p| (p.1 - intercept - slope * p.0).powi(2)).sum();
|
||||
let syy: f64 = points.iter().map(|p| (p.1 - my).powi(2)).sum();
|
||||
let se = (sse / (nf - 2.0) / sxx).sqrt();
|
||||
let mut slopes = Vec::with_capacity(n * (n - 1) / 2);
|
||||
for i in 0..n {
|
||||
for j in i + 1..n {
|
||||
let dx = points[j].0 - points[i].0;
|
||||
if dx != 0.0 {
|
||||
slopes.push((points[j].1 - points[i].1) / dx);
|
||||
}
|
||||
}
|
||||
}
|
||||
slopes.sort_by(f64::total_cmp);
|
||||
let theil_sen = slopes.get(slopes.len() / 2).copied().unwrap_or(0.0);
|
||||
Some(SlopeFit {
|
||||
n,
|
||||
slope,
|
||||
ci95_low: slope - 1.96 * se,
|
||||
ci95_high: slope + 1.96 * se,
|
||||
theil_sen,
|
||||
theil_sen: theil_sen(points),
|
||||
r2: if syy > 0.0 { 1.0 - sse / syy } else { 0.0 },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -106,8 +106,8 @@ pub struct LockReport {
|
||||
pub decision: LockDecision,
|
||||
pub outcome: LockOutcome,
|
||||
pub mapping_bytes: u64,
|
||||
/// A sparse archive (a memfd that holds only the extents the serve path reads): the bytes of those extents, which is what is
|
||||
/// locked, healed and counted; `None` for a full archive, where it is `mapping_bytes`.
|
||||
/// A sparse archive (a memfd that holds only the extents the serve path reads): the bytes of those extents, which
|
||||
/// is what is locked, healed and counted; `None` for a full archive, where it is `mapping_bytes`.
|
||||
pub extent_bytes: Option<u64>,
|
||||
pub memlock_soft: Option<u64>,
|
||||
pub memlock_hard: Option<u64>,
|
||||
@@ -118,7 +118,8 @@ pub struct LockReport {
|
||||
struct Guarded {
|
||||
mapping: crate::lock::FdMapping,
|
||||
report: LockReport,
|
||||
/// The extents of a sparse archive; `None` = the whole mapping is data. The heal cursor then walks their concatenation.
|
||||
/// The extents of a sparse archive; `None` = the whole mapping is data. The heal cursor then walks their
|
||||
/// concatenation.
|
||||
extents: Option<Vec<crate::lock::Span>>,
|
||||
cursor: u64,
|
||||
last_swapped: u64,
|
||||
@@ -127,6 +128,20 @@ struct Guarded {
|
||||
last: Option<crate::lock::Residency>,
|
||||
}
|
||||
|
||||
/// Windows: when the working set was last trimmed (`NONE` = never), when that was last logged, and how many trims
|
||||
/// happened.
|
||||
struct TrimStats {
|
||||
last_ms: AtomicU64,
|
||||
last_log_ms: AtomicU64,
|
||||
count: AtomicU64,
|
||||
}
|
||||
|
||||
impl TrimStats {
|
||||
fn new() -> Self {
|
||||
Self { last_ms: AtomicU64::new(NONE), last_log_ms: AtomicU64::new(0), count: AtomicU64::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
cfg: GovernorConfig,
|
||||
src: Arc<dyn MemoryPressure>,
|
||||
@@ -143,10 +158,7 @@ struct Inner {
|
||||
prefix_target: AtomicU64,
|
||||
prefix_used: AtomicU64,
|
||||
last_shed_ms: AtomicU64,
|
||||
/// Windows: when the working set was last trimmed (`NONE` = never), when that was last logged, and how many trims happened.
|
||||
last_trim_ms: AtomicU64,
|
||||
last_trim_log_ms: AtomicU64,
|
||||
trims: AtomicU64,
|
||||
trim: TrimStats,
|
||||
since_ms: AtomicU64,
|
||||
transitions: Mutex<VecDeque<TransitionRecord>>,
|
||||
counters: Counters,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
mod archive_guard;
|
||||
mod impl_governor_2;
|
||||
mod impl_governor_2_2;
|
||||
mod impl_governor_3;
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! The steps of guarding a sealed KAR memfd (map it, decide and attempt the lock, report; read the swap state and heal
|
||||
//! it), split out of [`Governor::guard_archive_extents`] and [`Governor::residency_tick`].
|
||||
#![cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::lock::{FdMapping, Residency, Span, compact_piece, raise_memlock_soft, spans_bytes};
|
||||
|
||||
/// What every lock report of one `guard_archive_extents` call shares.
|
||||
pub(super) struct ReportBase {
|
||||
pub(super) mode: LockMode,
|
||||
pub(super) started: Instant,
|
||||
pub(super) memlock: Option<(u64, u64)>,
|
||||
pub(super) extent_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// A refusal with the `memlock` code.
|
||||
fn memlock_refusal(message: String, numbers: Vec<(String, u64)>, advice: Vec<String>) -> Refusal {
|
||||
Refusal { code: "memlock", message, numbers, advice }
|
||||
}
|
||||
|
||||
/// The extents of a sparse archive must lie inside the `len`-byte descriptor.
|
||||
pub(super) fn check_extents(extents: Option<&[Span]>, len: u64) -> Result<(), Refusal> {
|
||||
if let Some(spans) = extents
|
||||
&& let Err(why) = crate::lock::check_spans(spans, len)
|
||||
{
|
||||
let message = format!("the sparse archive extents are invalid: {why}");
|
||||
return Err(memlock_refusal(message, vec![("archive".to_owned(), len)], vec![]));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a
|
||||
/// shared mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a
|
||||
/// read-only description can never become writable, so the mapping is allowed everywhere and is immutable by
|
||||
/// construction.
|
||||
pub(super) fn map_readonly_archive(fd: std::os::fd::BorrowedFd<'_>, len: u64) -> std::io::Result<FdMapping> {
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _};
|
||||
let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.open(path)
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}")))?;
|
||||
FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX))
|
||||
}
|
||||
|
||||
/// The refusal of `LELEKA_MEMORY_LOCK=require` when the archive could not be locked.
|
||||
pub(super) fn require_refusal(decision: &LockDecision, outcome: &LockOutcome, resident: u64) -> Refusal {
|
||||
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(), resident)], vec![]),
|
||||
};
|
||||
let message = format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})");
|
||||
memlock_refusal(message, numbers, advice)
|
||||
}
|
||||
|
||||
impl Guarded {
|
||||
/// The guard of a freshly locked archive: nothing swapped, nothing healed yet.
|
||||
pub(super) fn new(mapping: FdMapping, report: LockReport, extents: Option<&[Span]>) -> Self {
|
||||
Self {
|
||||
mapping,
|
||||
report,
|
||||
extents: extents.map(<[_]>::to_vec),
|
||||
cursor: 0,
|
||||
last_swapped: 0,
|
||||
warned_swapped: 0,
|
||||
last_check: None,
|
||||
last: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Governor {
|
||||
/// The report of a lock attempt that mapped `mapping_bytes` of the archive.
|
||||
pub(super) fn lock_report(
|
||||
&self,
|
||||
base: &ReportBase,
|
||||
decision: LockDecision,
|
||||
outcome: LockOutcome,
|
||||
mapping_bytes: u64,
|
||||
) -> LockReport {
|
||||
LockReport {
|
||||
mode: base.mode,
|
||||
decision,
|
||||
outcome,
|
||||
mapping_bytes,
|
||||
extent_bytes: base.extent_bytes,
|
||||
memlock_soft: base.memlock.map(|m| m.0),
|
||||
memlock_hard: base.memlock.map(|m| m.1),
|
||||
millis: self.inner.clock.since(base.started).as_secs_f64() * 1e3,
|
||||
}
|
||||
}
|
||||
|
||||
/// The archive could not be mapped: report it, and refuse when the lock is required.
|
||||
pub(super) fn unmapped_archive(
|
||||
&self,
|
||||
base: &ReportBase,
|
||||
decision: LockDecision,
|
||||
e: &std::io::Error,
|
||||
) -> Result<LockReport, Refusal> {
|
||||
let outcome = LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") };
|
||||
let report = self.lock_report(base, decision, outcome, 0);
|
||||
self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}"));
|
||||
if base.mode == LockMode::Require {
|
||||
return Err(memlock_refusal(format!("mmap of the archive failed: {e}"), vec![], vec![]));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Act on the lock decision: do nothing, say why the lock cannot cover the archive, or lock it.
|
||||
pub(super) fn apply_decision(
|
||||
&self,
|
||||
decision: &LockDecision,
|
||||
mapping: &mut FdMapping,
|
||||
extents: Option<&[Span]>,
|
||||
resident: u64,
|
||||
) -> LockOutcome {
|
||||
match decision {
|
||||
LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() },
|
||||
LockDecision::Insufficient { need, soft, hard, advice } => {
|
||||
self.insufficient_outcome(resident, (*need, *soft, *hard), advice)
|
||||
}
|
||||
LockDecision::Attempt { raise_soft_to } => self.attempt_lock(mapping, extents, *raise_soft_to, resident),
|
||||
}
|
||||
}
|
||||
|
||||
/// `RLIMIT_MEMLOCK` cannot cover the archive: the archive stays swappable, and the log says how to change that.
|
||||
fn insufficient_outcome(&self, resident: u64, limits: (u64, u64, u64), advice: &[String]) -> LockOutcome {
|
||||
let (need, soft, hard) = limits;
|
||||
let hard_text = if hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() };
|
||||
let why =
|
||||
format!("RLIMIT_MEMLOCK soft {} MiB / hard {hard_text} MiB cannot cover {} MiB", soft >> 20, need >> 20);
|
||||
self.log(&format!(
|
||||
"WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}",
|
||||
gib(resident),
|
||||
advice.join(" | ")
|
||||
));
|
||||
LockOutcome::NotAttempted { why }
|
||||
}
|
||||
|
||||
/// `mlock` the archive (or only its extents) chunk by chunk and log the outcome.
|
||||
fn attempt_lock(
|
||||
&self,
|
||||
mapping: &mut FdMapping,
|
||||
extents: Option<&[Span]>,
|
||||
raise_soft_to: Option<u64>,
|
||||
len: u64,
|
||||
) -> LockOutcome {
|
||||
if let Some(to) = raise_soft_to
|
||||
&& let Err(e) = raise_memlock_soft(to)
|
||||
{
|
||||
self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20));
|
||||
}
|
||||
let policy = self.policy();
|
||||
let swapped = self.mapping_swapped(mapping).unwrap_or(0);
|
||||
let src = self.inner.src.clone();
|
||||
let allow = |n: u64| {
|
||||
// a swapped-out chunk is read back into RAM: keep the hard floor + reserve
|
||||
let need = if swapped > 0 { n } else { 0 };
|
||||
let floor = policy.hard_floor + policy.reserve;
|
||||
src.facts().effective_available().is_none_or(|a| a.saturating_sub(need) >= floor)
|
||||
};
|
||||
let outcome = match extents {
|
||||
Some(spans) => mapping.lock_ranges(spans, GIB, allow),
|
||||
None => mapping.lock(GIB, allow),
|
||||
};
|
||||
self.log_lock_outcome(&outcome, len);
|
||||
outcome
|
||||
}
|
||||
|
||||
fn log_lock_outcome(&self, outcome: &LockOutcome, len: u64) {
|
||||
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}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Warn (at most once per 64 MiB step) while pages of the archive are swapped out.
|
||||
pub(super) fn warn_swapped(&self, g: &mut Guarded, r: &Residency, read_ms: f64) {
|
||||
if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB {
|
||||
g.warned_swapped = r.swapped_bytes;
|
||||
let healing = if self.inner.cfg.heal { "; healing" } else { "" };
|
||||
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{healing}",
|
||||
r.swapped_bytes >> 20,
|
||||
gib(r.rss_bytes),
|
||||
gib(r.mapping_bytes),
|
||||
r.locked_bytes >> 20,
|
||||
));
|
||||
} else if r.swapped_bytes < 64 * MIB {
|
||||
g.warned_swapped = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull swapped pages back in, up to one tick's budget, when the host has the memory for it.
|
||||
pub(super) fn heal(&self, g: &mut Guarded, r: &Residency, policy: &Policy) {
|
||||
let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB));
|
||||
let has_room = self
|
||||
.inner
|
||||
.src
|
||||
.facts()
|
||||
.effective_available()
|
||||
.is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve);
|
||||
if !has_room {
|
||||
return;
|
||||
}
|
||||
let done = match g.extents.clone() {
|
||||
Some(spans) => heal_extents(g, &spans, budget),
|
||||
None => heal_whole(g, budget),
|
||||
};
|
||||
self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed);
|
||||
self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Populate a sparse archive: walk the concatenation of the extents, never a hole. Returns the bytes populated.
|
||||
fn heal_extents(g: &mut Guarded, spans: &[Span], budget: u64) -> u64 {
|
||||
let total = spans_bytes(spans);
|
||||
let mut done = 0;
|
||||
while done < budget && done < total {
|
||||
if g.cursor >= total {
|
||||
g.cursor = 0;
|
||||
}
|
||||
let want = (256 * MIB).min(budget - done);
|
||||
let Some((offset, piece)) = compact_piece(spans, g.cursor, want) else {
|
||||
break;
|
||||
};
|
||||
// whole pages; the last page of the last extent may be partial and is rounded up by the kernel
|
||||
let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 };
|
||||
if g.mapping.populate(offset, n).is_err() {
|
||||
break;
|
||||
}
|
||||
g.cursor += n;
|
||||
done += n;
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Populate a full archive page by page from the cursor. Returns the bytes populated.
|
||||
fn heal_whole(g: &mut Guarded, budget: u64) -> u64 {
|
||||
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 || g.mapping.populate(g.cursor, n).is_err() {
|
||||
break;
|
||||
}
|
||||
g.cursor += n;
|
||||
done += n;
|
||||
}
|
||||
done
|
||||
}
|
||||
@@ -3,6 +3,39 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl Inner {
|
||||
fn new(cfg: GovernorConfig, src: impl MemoryPressure + 'static, clock: AnyClock) -> Self {
|
||||
let policy0 = cfg.policy;
|
||||
Self {
|
||||
monitor: Mutex::new(Monitor::new(policy0)),
|
||||
policy: Mutex::new(policy0),
|
||||
cfg,
|
||||
src: Arc::new(src),
|
||||
epoch: clock.now(),
|
||||
ledger: Ledger::with_clock(clock.clone()),
|
||||
clock,
|
||||
plan: Mutex::new(None),
|
||||
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),
|
||||
trim: TrimStats::new(),
|
||||
since_ms: AtomicU64::new(0),
|
||||
transitions: Mutex::new(VecDeque::new()),
|
||||
counters: Counters::default(),
|
||||
vram: Mutex::new(None),
|
||||
post_load: Mutex::new(None),
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
guarded: Mutex::new(None),
|
||||
stop: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Governor {
|
||||
pub fn new(cfg: GovernorConfig, src: Arc<dyn ProcSource + Send + Sync>) -> Self {
|
||||
Self::with_parts(cfg, ProcPressure(src), AnyClock::System)
|
||||
@@ -15,39 +48,7 @@ impl Governor {
|
||||
|
||||
/// A governor over any [`MemoryPressure`] and any clock: the composition root, and the way a test scripts both.
|
||||
pub fn with_parts(cfg: GovernorConfig, pressure: impl MemoryPressure + 'static, clock: AnyClock) -> Self {
|
||||
let policy0 = cfg.policy;
|
||||
let monitor = Monitor::new(policy0);
|
||||
Self {
|
||||
inner: Arc::new(Inner {
|
||||
cfg,
|
||||
src: Arc::new(pressure),
|
||||
epoch: clock.now(),
|
||||
ledger: Ledger::with_clock(clock.clone()),
|
||||
clock,
|
||||
plan: Mutex::new(None),
|
||||
monitor: Mutex::new(monitor),
|
||||
policy: Mutex::new(policy0),
|
||||
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),
|
||||
last_trim_ms: AtomicU64::new(NONE),
|
||||
last_trim_log_ms: AtomicU64::new(0),
|
||||
trims: AtomicU64::new(0),
|
||||
since_ms: AtomicU64::new(0),
|
||||
transitions: Mutex::new(VecDeque::new()),
|
||||
counters: Counters::default(),
|
||||
vram: Mutex::new(None),
|
||||
post_load: Mutex::new(None),
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
guarded: Mutex::new(None),
|
||||
stop: AtomicBool::new(false),
|
||||
}),
|
||||
}
|
||||
Self { inner: Arc::new(Inner::new(cfg, pressure, clock)) }
|
||||
}
|
||||
|
||||
/// A governor over the real `/proc`.
|
||||
@@ -64,7 +65,8 @@ impl Governor {
|
||||
}
|
||||
|
||||
/// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory
|
||||
/// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required.
|
||||
/// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is
|
||||
/// required.
|
||||
pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> {
|
||||
if hard_floor >= soft_floor {
|
||||
return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}"));
|
||||
@@ -115,8 +117,8 @@ impl Governor {
|
||||
|
||||
// ---- 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.
|
||||
/// 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<Plan, Refusal> {
|
||||
let plan = match crate::plan::plan(input) {
|
||||
Ok(plan) => plan,
|
||||
@@ -125,22 +127,29 @@ impl Governor {
|
||||
return Err(refusal);
|
||||
}
|
||||
};
|
||||
self.register_planned_items(&plan);
|
||||
self.log_budget(&plan);
|
||||
for note in &plan.notes {
|
||||
self.log(&format!("note: {note}"));
|
||||
}
|
||||
self.set_plan(plan.clone());
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Every fixed item of the plan goes into the inventory with its expected size.
|
||||
fn register_planned_items(&self, plan: &Plan) {
|
||||
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),
|
||||
);
|
||||
let when = crate::inventory::When::Startup;
|
||||
let entry = crate::inventory::Entry::new("planned", &item.name, item.space, when, &item.formula);
|
||||
inv.set(entry.expected(item.bytes).swappable(false));
|
||||
}
|
||||
}
|
||||
|
||||
fn log_budget(&self, plan: &Plan) {
|
||||
self.log(&format!(
|
||||
"budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}",
|
||||
"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),
|
||||
@@ -154,14 +163,10 @@ impl Governor {
|
||||
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)
|
||||
}
|
||||
|
||||
/// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report.
|
||||
/// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the
|
||||
/// report.
|
||||
pub fn check_vram(
|
||||
&self,
|
||||
vram: crate::plan::VramFacts,
|
||||
@@ -183,8 +188,9 @@ impl Governor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the
|
||||
/// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned).
|
||||
/// Compare the plan's prediction with what the host really has after the stack opened, log the error when it
|
||||
/// matters and keep it for the report (`plan_check`). Returns `actual - predicted` in bytes (negative: the
|
||||
/// footprint was bigger than planned).
|
||||
pub fn note_post_load(&self, actual_available: Option<u64>) -> Option<i64> {
|
||||
let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?;
|
||||
let actual = actual_available?;
|
||||
@@ -193,7 +199,9 @@ impl Governor {
|
||||
let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX });
|
||||
if error.unsigned_abs() > 512 * MIB {
|
||||
self.log(&format!(
|
||||
"WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value",
|
||||
"WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after \
|
||||
the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured \
|
||||
value",
|
||||
gib(predicted),
|
||||
gib(actual),
|
||||
error >> 20
|
||||
@@ -220,8 +228,9 @@ impl Governor {
|
||||
Level::from_u8(self.inner.level.load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
/// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started):
|
||||
/// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself.
|
||||
/// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never
|
||||
/// started): a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the
|
||||
/// monitor itself.
|
||||
pub(in super::super) fn ensure_fresh(&self) {
|
||||
let interval = self.inner.cfg.sample_interval_ms.max(50);
|
||||
let now = self.now_ms();
|
||||
|
||||
@@ -6,84 +6,89 @@ use super::*;
|
||||
impl Governor {
|
||||
// ---- 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.
|
||||
/// The refusal of a request whose prompt and completion can never fit the pinned K/V image (a 400, not a retry).
|
||||
fn refuse_context(&self, shape: &RequestShape, needed: u64) -> Admission {
|
||||
self.inner.counters.rejected_context.fetch_add(1, Ordering::Relaxed);
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// The refusal while the pressure level is `reject`, or when one request's own transient would take the host
|
||||
/// below the hard floor (503 `memory_pressure` with a retry hint).
|
||||
fn refuse_pressure(&self, message: String, retry_after_secs: u64) -> Admission {
|
||||
self.inner.counters.rejected_pressure.fetch_add(1, Ordering::Relaxed);
|
||||
Admission::Refuse(Refuse { status: 503, code: "memory_pressure", message, retry_after_secs })
|
||||
}
|
||||
|
||||
/// 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,
|
||||
});
|
||||
return self.refuse_context(shape, needed);
|
||||
}
|
||||
self.ensure_fresh();
|
||||
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,
|
||||
});
|
||||
let message = format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason));
|
||||
return self.refuse_pressure(message, retry);
|
||||
}
|
||||
// the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor
|
||||
// the transient of one request (checkpoint / node state / import staging) must not take the host below the
|
||||
// hard floor
|
||||
let transient = self.policy().reserve / 4;
|
||||
if let Some(available) = self.available_now()
|
||||
&& available.saturating_sub(transient) < self.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.policy().hard_floor)
|
||||
),
|
||||
retry_after_secs: retry,
|
||||
});
|
||||
let floor = gib(self.policy().hard_floor);
|
||||
let message = format!(
|
||||
"{} available is within {} of the hard floor {floor}; retry shortly",
|
||||
gib(available),
|
||||
gib(transient)
|
||||
);
|
||||
return self.refuse_pressure(message, retry);
|
||||
}
|
||||
c.admitted.fetch_add(1, Ordering::Relaxed);
|
||||
self.inner.counters.admitted.fetch_add(1, Ordering::Relaxed);
|
||||
Admission::Admit
|
||||
}
|
||||
|
||||
/// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to
|
||||
/// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor:
|
||||
/// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks
|
||||
/// evicted, the fourth turn re-read 223k tokens in 32 minutes).
|
||||
/// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the
|
||||
/// soft floor, hand them back to the standby list (at most every 250 ms) and read the host again, so that a dip
|
||||
/// caused only by trimmable mapped pages never reaches the monitor: a shed evicts prefix-cache blocks, and live
|
||||
/// runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks evicted, the
|
||||
/// fourth turn re-read 223k tokens in 32 minutes).
|
||||
pub(in super::super) fn relieve_working_set(&self, facts: HostFacts) -> HostFacts {
|
||||
self.relieve_working_set_below(facts, self.policy().soft_floor)
|
||||
}
|
||||
|
||||
/// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it
|
||||
/// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint
|
||||
/// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms.
|
||||
/// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs
|
||||
/// `needed` bytes of it (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a
|
||||
/// floor of 9.2 GiB refused a 0.2 GiB checkpoint that the very next trim would have admitted, because the periodic
|
||||
/// trim only runs below the soft floor). At most one trim per 250 ms.
|
||||
pub fn available_after_relief(&self, needed: u64) -> Option<u64> {
|
||||
let facts = self.probe();
|
||||
self.relieve_working_set_below(facts, needed).effective_available()
|
||||
}
|
||||
|
||||
pub(in super::super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts {
|
||||
if !cfg!(windows) {
|
||||
return facts;
|
||||
}
|
||||
// A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists
|
||||
/// A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists.
|
||||
fn trim_disabled() -> bool {
|
||||
static NO_TRIM_FILE: OnceLock<Option<std::path::PathBuf>> = OnceLock::new();
|
||||
if NO_TRIM_FILE
|
||||
NO_TRIM_FILE
|
||||
.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from))
|
||||
.as_ref()
|
||||
.is_some_and(|f| f.exists())
|
||||
{
|
||||
}
|
||||
|
||||
pub(in super::super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts {
|
||||
if !cfg!(windows) || Self::trim_disabled() {
|
||||
return facts;
|
||||
}
|
||||
let Some(available) = facts.effective_available() else { return facts };
|
||||
@@ -91,32 +96,37 @@ impl Governor {
|
||||
return facts;
|
||||
}
|
||||
let now = self.now_ms();
|
||||
let last = self.inner.last_trim_ms.load(Ordering::Acquire);
|
||||
let last = self.inner.trim.last_ms.load(Ordering::Acquire);
|
||||
if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 {
|
||||
return facts;
|
||||
}
|
||||
self.inner.last_trim_ms.store(now, Ordering::Release);
|
||||
self.inner.trim.last_ms.store(now, Ordering::Release);
|
||||
if !crate::winproc::trim_working_set() {
|
||||
return facts;
|
||||
}
|
||||
let after = self.probe();
|
||||
let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 {
|
||||
self.inner.last_trim_log_ms.store(now, Ordering::Relaxed);
|
||||
self.log(&format!(
|
||||
"working set trimmed (#{trims}): available {} -> {} MiB",
|
||||
available >> 20,
|
||||
after.effective_available().unwrap_or(0) >> 20
|
||||
));
|
||||
}
|
||||
self.log_trim(now, available, &after);
|
||||
after
|
||||
}
|
||||
|
||||
/// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding.
|
||||
/// Log the first trim and then at most one in ten seconds.
|
||||
fn log_trim(&self, now: u64, available_before: u64, after: &HostFacts) {
|
||||
let trims = self.inner.trim.count.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if trims == 1 || now.saturating_sub(self.inner.trim.last_log_ms.load(Ordering::Relaxed)) >= 10_000 {
|
||||
self.inner.trim.last_log_ms.store(now, Ordering::Relaxed);
|
||||
self.log(&format!(
|
||||
"working set trimmed (#{trims}): available {} -> {} MiB",
|
||||
available_before >> 20,
|
||||
after.effective_available().unwrap_or(0) >> 20
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
self.ensure_fresh();
|
||||
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 => {
|
||||
@@ -124,20 +134,7 @@ impl Governor {
|
||||
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 }
|
||||
ShedDirective { level, prefix_budget: Some(self.shed_target(prefix_used)), drop_conversation: true }
|
||||
}
|
||||
Level::Reject => {
|
||||
self.inner.prefix_target.store(0, Ordering::Release);
|
||||
@@ -146,6 +143,23 @@ impl Governor {
|
||||
}
|
||||
}
|
||||
|
||||
/// The prefix budget to enforce while shedding: a quarter less than the current target, at most once a second.
|
||||
fn shed_target(&self, prefix_used: u64) -> u64 {
|
||||
let planned = self.inner.prefix_planned.load(Ordering::Acquire);
|
||||
let now = self.now_ms();
|
||||
let last = self.inner.last_shed_ms.load(Ordering::Acquire);
|
||||
let current = self.inner.prefix_target.load(Ordering::Acquire);
|
||||
if current != NONE && now.saturating_sub(last) < 1000 {
|
||||
return current;
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
pub fn note_prefix_used(&self, bytes: u64) {
|
||||
self.inner.prefix_used.store(bytes, Ordering::Release);
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
use super::*;
|
||||
|
||||
impl Governor {
|
||||
/// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the
|
||||
/// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero
|
||||
/// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their
|
||||
/// size, and the report says so. `None` is the whole archive.
|
||||
/// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything
|
||||
/// else of the `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a
|
||||
/// hole allocates zero pages for it, which would turn the sparse copy back into the full archive), the lock limit
|
||||
/// is judged against their size, and the report says so. `None` is the whole archive.
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pub fn guard_archive_extents(
|
||||
&self,
|
||||
@@ -18,151 +18,22 @@ impl Governor {
|
||||
let started = self.inner.clock.now();
|
||||
let facts = self.probe();
|
||||
let mode = self.inner.cfg.lock_mode;
|
||||
if let Some(spans) = extents
|
||||
&& let Err(why) = crate::lock::check_spans(spans, len)
|
||||
{
|
||||
return Err(Refusal {
|
||||
code: "memlock",
|
||||
message: format!("the sparse archive extents are invalid: {why}"),
|
||||
numbers: vec![("archive".to_owned(), len)],
|
||||
advice: vec![],
|
||||
});
|
||||
}
|
||||
archive_guard::check_extents(extents, len)?;
|
||||
// the bytes that are resident and have to be locked
|
||||
let resident = extents.map_or(len, crate::lock::spans_bytes);
|
||||
let extent_bytes = extents.map(crate::lock::spans_bytes);
|
||||
let base = archive_guard::ReportBase { mode, started, memlock: facts.memlock, extent_bytes };
|
||||
let decision = plan_lock(mode, resident, facts.memlock, &facts.status);
|
||||
// Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared
|
||||
// mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only
|
||||
// description can never become writable, so the mapping is allowed everywhere and is immutable by construction.
|
||||
let readonly = {
|
||||
use std::os::fd::AsRawFd;
|
||||
std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd()))
|
||||
};
|
||||
let mapped = match &readonly {
|
||||
Ok(file) => {
|
||||
use std::os::fd::AsFd as _;
|
||||
crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX))
|
||||
}
|
||||
Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))),
|
||||
};
|
||||
let mut mapping = match mapped {
|
||||
let mut mapping = match archive_guard::map_readonly_archive(fd, len) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
let report = LockReport {
|
||||
mode,
|
||||
decision,
|
||||
outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") },
|
||||
mapping_bytes: 0,
|
||||
extent_bytes,
|
||||
memlock_soft: facts.memlock.map(|m| m.0),
|
||||
memlock_hard: facts.memlock.map(|m| m.1),
|
||||
millis: self.inner.clock.since(started).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(resident),
|
||||
advice.join(" | ")
|
||||
));
|
||||
LockOutcome::NotAttempted { why }
|
||||
}
|
||||
LockDecision::Attempt { raise_soft_to } => {
|
||||
if let Some(to) = raise_soft_to
|
||||
&& 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.policy();
|
||||
let swapped = self.mapping_swapped(&mapping).unwrap_or(0);
|
||||
let src = self.inner.src.clone();
|
||||
let allow = |n: u64| {
|
||||
// a swapped-out chunk is read back into RAM: keep the hard floor + reserve
|
||||
let need = if swapped > 0 { n } else { 0 };
|
||||
let floor = policy.hard_floor + policy.reserve;
|
||||
src.facts().effective_available().is_none_or(|a| a.saturating_sub(need) >= floor)
|
||||
};
|
||||
let outcome = match extents {
|
||||
Some(spans) => mapping.lock_ranges(spans, GIB, allow),
|
||||
None => mapping.lock(GIB, allow),
|
||||
};
|
||||
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,
|
||||
extent_bytes,
|
||||
memlock_soft: facts.memlock.map(|m| m.0),
|
||||
memlock_hard: facts.memlock.map(|m| m.1),
|
||||
millis: self.inner.clock.since(started).as_secs_f64() * 1e3,
|
||||
Err(e) => return self.unmapped_archive(&base, decision, &e),
|
||||
};
|
||||
let outcome = self.apply_decision(&decision, &mut mapping, extents, resident);
|
||||
let report = self.lock_report(&base, decision.clone(), outcome.clone(), len);
|
||||
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(), resident)], vec![]),
|
||||
};
|
||||
return Err(Refusal {
|
||||
code: "memlock",
|
||||
message: format!(
|
||||
"LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"
|
||||
),
|
||||
numbers,
|
||||
advice,
|
||||
});
|
||||
return Err(archive_guard::require_refusal(&decision, &outcome, resident));
|
||||
}
|
||||
*lock(&self.inner.guarded) = Some(Guarded {
|
||||
mapping,
|
||||
report: report.clone(),
|
||||
extents: extents.map(<[_]>::to_vec),
|
||||
cursor: 0,
|
||||
last_swapped: 0,
|
||||
warned_swapped: 0,
|
||||
last_check: None,
|
||||
last: None,
|
||||
});
|
||||
*lock(&self.inner.guarded) = Some(Guarded::new(mapping, report.clone(), extents));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -186,69 +57,9 @@ impl Governor {
|
||||
g.last = Some(r);
|
||||
g.last_check = Some(self.inner.clock.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;
|
||||
}
|
||||
self.warn_swapped(g, &r, read_ms);
|
||||
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 =
|
||||
self.inner.src.facts().effective_available().is_some_and(|a| {
|
||||
a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve
|
||||
});
|
||||
if ok {
|
||||
let mut done = 0;
|
||||
match g.extents.clone() {
|
||||
// a sparse archive: walk the concatenation of the extents, never a hole
|
||||
Some(spans) => {
|
||||
let total = crate::lock::spans_bytes(&spans);
|
||||
while done < budget && done < total {
|
||||
if g.cursor >= total {
|
||||
g.cursor = 0;
|
||||
}
|
||||
let want = (256 * MIB).min(budget - done);
|
||||
let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else {
|
||||
break;
|
||||
};
|
||||
// whole pages; the last page of the last extent may be partial and is rounded up by the kernel
|
||||
let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 };
|
||||
if g.mapping.populate(offset, n).is_err() {
|
||||
break;
|
||||
}
|
||||
g.cursor += n;
|
||||
done += n;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let total = g.mapping.len();
|
||||
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);
|
||||
}
|
||||
self.heal(g, &r, &policy);
|
||||
}
|
||||
r.swapped_bytes
|
||||
}
|
||||
|
||||
@@ -11,72 +11,76 @@ impl Governor {
|
||||
let monitor = lock(&self.inner.monitor);
|
||||
let policy = self.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<serde_json::Value> = 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,
|
||||
},
|
||||
"gate": self.gate_json(level, &monitor, &policy),
|
||||
"policy": policy,
|
||||
"config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal},
|
||||
"config": self.config_json(),
|
||||
"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,
|
||||
},
|
||||
"host": host_json(&facts),
|
||||
"process": process_json(&facts),
|
||||
"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,
|
||||
"caches": self.caches_json(),
|
||||
"counters": counters_json(&self.inner.counters),
|
||||
"archive": self.archive_json(),
|
||||
"inventory": self.inventory().to_json(),
|
||||
"ledger": self.inner.ledger.to_json(),
|
||||
"vram": &*lock(&self.inner.vram),
|
||||
"plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})),
|
||||
"plan_check": self.plan_check_json(),
|
||||
"transitions": &*lock(&self.inner.transitions),
|
||||
})
|
||||
}
|
||||
|
||||
/// The level, why, since when, and the floors it is judged against.
|
||||
fn gate_json(&self, level: Level, monitor: &Monitor, policy: &Policy) -> serde_json::Value {
|
||||
json!({
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
fn config_json(&self) -> serde_json::Value {
|
||||
let cfg = &self.inner.cfg;
|
||||
json!({"sample_interval_ms": cfg.sample_interval_ms, "lock_mode": cfg.lock_mode, "heal": cfg.heal})
|
||||
}
|
||||
|
||||
fn caches_json(&self) -> serde_json::Value {
|
||||
let planned = self.inner.prefix_planned.load(Ordering::Acquire);
|
||||
let target = self.inner.prefix_target.load(Ordering::Acquire);
|
||||
let shed_target = if target == NONE { serde_json::Value::Null } else { json!(target) };
|
||||
let used = self.inner.prefix_used.load(Ordering::Acquire);
|
||||
json!({"prefix": {"planned_bytes": planned, "shed_target_bytes": shed_target, "used_bytes": used}})
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
fn archive_json(&self) -> Option<serde_json::Value> {
|
||||
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")))]
|
||||
fn archive_json(&self) -> Option<serde_json::Value> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The error of the startup plan's prediction against what the host really had after the stack opened.
|
||||
fn plan_check_json(&self) -> Option<serde_json::Value> {
|
||||
lock(&self.inner.post_load).map(|(p, a)| {
|
||||
json!({
|
||||
"predicted_available_after_fixed": p,
|
||||
"actual_available_after_open": a,
|
||||
"error_bytes": i128::from(a) - i128::from(p),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Render the report into the cell [`published_report`] reads.
|
||||
pub fn publish(&self) {
|
||||
if let Ok(text) = serde_json::to_string(&self.report()) {
|
||||
@@ -86,51 +90,98 @@ impl Governor {
|
||||
|
||||
// ---- sampler -----------------------------------------------------------------------------------------------
|
||||
|
||||
/// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of
|
||||
/// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is
|
||||
/// dropped.
|
||||
pub fn spawn_sampler(&self) -> SamplerGuard {
|
||||
fn nap(inner: &Inner, total: Duration) {
|
||||
let mut slept = Duration::ZERO;
|
||||
while slept < total && !inner.stop.load(Ordering::Acquire) {
|
||||
let step = Duration::from_millis(50).min(total - slept);
|
||||
std::thread::sleep(step);
|
||||
slept += step;
|
||||
}
|
||||
}
|
||||
self.inner.stop.store(false, Ordering::Release);
|
||||
/// Run `round` every `every` on a named thread until the governor is told to stop. A panic in one round (a
|
||||
/// malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level: it is logged.
|
||||
fn spawn_rounds(
|
||||
&self,
|
||||
name: &str,
|
||||
every: Duration,
|
||||
panicked: &'static str,
|
||||
round: fn(&Governor),
|
||||
) -> Option<std::thread::JoinHandle<()>> {
|
||||
let me = self.clone();
|
||||
let sampler = std::thread::Builder::new()
|
||||
.name("leleka-memory".into())
|
||||
std::thread::Builder::new()
|
||||
.name(name.into())
|
||||
.spawn(move || {
|
||||
let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms);
|
||||
while !me.inner.stop.load(Ordering::Acquire) {
|
||||
// a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level
|
||||
let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
me.sample_now();
|
||||
me.publish();
|
||||
}));
|
||||
if round.is_err() {
|
||||
me.log("WARNING: the memory sampler round panicked; continuing");
|
||||
}
|
||||
nap(&me.inner, interval);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
let me = self.clone();
|
||||
let guard = std::thread::Builder::new()
|
||||
.name("leleka-memory-guard".into())
|
||||
.spawn(move || {
|
||||
let every = Duration::from_millis(me.inner.cfg.residency_every_ms);
|
||||
while !me.inner.stop.load(Ordering::Acquire) {
|
||||
let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick()));
|
||||
if round.is_err() {
|
||||
me.log("WARNING: the memfd residency round panicked; continuing");
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| round(&me)));
|
||||
if outcome.is_err() {
|
||||
me.log(panicked);
|
||||
}
|
||||
nap(&me.inner, every);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps
|
||||
/// read of the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop
|
||||
/// when the guard is dropped.
|
||||
pub fn spawn_sampler(&self) -> SamplerGuard {
|
||||
self.inner.stop.store(false, Ordering::Release);
|
||||
let interval = Duration::from_millis(self.inner.cfg.sample_interval_ms);
|
||||
let sampler = self.spawn_rounds(
|
||||
"leleka-memory",
|
||||
interval,
|
||||
"WARNING: the memory sampler round panicked; continuing",
|
||||
|g| {
|
||||
g.sample_now();
|
||||
g.publish();
|
||||
},
|
||||
);
|
||||
let every = Duration::from_millis(self.inner.cfg.residency_every_ms);
|
||||
let panicked = "WARNING: the memfd residency round panicked; continuing";
|
||||
let guard = self.spawn_rounds("leleka-memory-guard", every, panicked, |g| {
|
||||
g.residency_tick();
|
||||
});
|
||||
SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Sleep up to `total` in steps of 50 ms, returning early once the governor is told to stop.
|
||||
fn nap(inner: &Inner, total: Duration) {
|
||||
let mut slept = Duration::ZERO;
|
||||
while slept < total && !inner.stop.load(Ordering::Acquire) {
|
||||
let step = Duration::from_millis(50).min(total - slept);
|
||||
std::thread::sleep(step);
|
||||
slept += step;
|
||||
}
|
||||
}
|
||||
|
||||
fn host_json(facts: &HostFacts) -> serde_json::Value {
|
||||
json!({
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
fn process_json(facts: &HostFacts) -> serde_json::Value {
|
||||
json!({
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
fn counters_json(c: &Counters) -> serde_json::Value {
|
||||
json!({
|
||||
"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),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,6 +3,96 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The `LELEKA_MEMORY_*` overrides over any lookup `Fn(&str) -> Option<String>`.
|
||||
trait EnvLookup {
|
||||
fn var(&self, name: &str) -> Option<String>;
|
||||
|
||||
/// An unsigned override; `None` when unset, an error naming the variable when it is not a number.
|
||||
fn number(&self, name: &str) -> Result<Option<u64>, String> {
|
||||
match self.var(name) {
|
||||
None => Ok(None),
|
||||
Some(v) => v.trim().parse::<u64>().map(Some).map_err(|_| format!("{name}={v:?} is not a number")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A non-negative finite override; `None` when unset.
|
||||
fn float(&self, name: &str) -> Result<Option<f64>, String> {
|
||||
match self.var(name) {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|f| f.is_finite() && *f >= 0.0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| format!("{name}={v:?} is not a non-negative number")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Override `field` with a number of MiB, in bytes.
|
||||
fn set_mib(&self, name: &str, field: &mut u64) -> Result<(), String> {
|
||||
if let Some(v) = self.number(name)? {
|
||||
*field = v.saturating_mul(MIB);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Override `field` with a number.
|
||||
fn set_number(&self, name: &str, field: &mut u64) -> Result<(), String> {
|
||||
if let Some(v) = self.number(name)? {
|
||||
*field = v;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Override `field` with a flag (any number but 0 is on).
|
||||
fn set_flag(&self, name: &str, field: &mut bool) -> Result<(), String> {
|
||||
if let Some(v) = self.number(name)? {
|
||||
*field = v != 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Override `field` with a non-negative number.
|
||||
fn set_float(&self, name: &str, field: &mut f64) -> Result<(), String> {
|
||||
if let Some(v) = self.float(name)? {
|
||||
*field = v;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Fn(&str) -> Option<String> + ?Sized> EnvLookup for F {
|
||||
fn var(&self, name: &str) -> Option<String> {
|
||||
self(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// The floors, the reserve, the cache share and the swap-out limit.
|
||||
fn apply_env_floors(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> {
|
||||
env.set_mib("LELEKA_MEMORY_SOFT_FLOOR_MIB", &mut self.soft_floor)?;
|
||||
env.set_mib("LELEKA_MEMORY_HARD_FLOOR_MIB", &mut self.hard_floor)?;
|
||||
env.set_mib("LELEKA_MEMORY_RESERVE_MIB", &mut self.reserve)?;
|
||||
env.set_mib("LELEKA_MEMORY_HYSTERESIS_MIB", &mut self.hysteresis)?;
|
||||
if let Some(v) = env.number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? {
|
||||
if v == 0 || v > 100 {
|
||||
return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100"));
|
||||
}
|
||||
self.cache_share_percent = v;
|
||||
}
|
||||
env.set_number("LELEKA_MEMORY_SWAPOUT_PAGES_PER_S", &mut self.swapout_pages_per_s_shed)
|
||||
}
|
||||
|
||||
/// The PSI guard and its two limits, and whether the plan is enforced.
|
||||
fn apply_env_psi(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> {
|
||||
env.set_mib("LELEKA_MEMORY_PSI_GUARD_MIB", &mut self.psi_guard_available)?;
|
||||
env.set_float("LELEKA_MEMORY_PSI_SOME_SHED", &mut self.psi_some_shed)?;
|
||||
env.set_float("LELEKA_MEMORY_PSI_FULL_REJECT", &mut self.psi_full_reject)?;
|
||||
env.set_flag("LELEKA_MEMORY_ENFORCE", &mut self.enforce)
|
||||
}
|
||||
}
|
||||
|
||||
impl GovernorConfig {
|
||||
pub fn new(policy: Policy) -> Self {
|
||||
Self {
|
||||
@@ -16,77 +106,33 @@ impl GovernorConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<String>) -> Result<Self, String> {
|
||||
let mut cfg = Self::new(Policy::for_host(mem_total, laptop));
|
||||
let number = |name: &str| -> Result<Option<u64>, String> {
|
||||
match env(name) {
|
||||
None => Ok(None),
|
||||
Some(v) => v.trim().parse::<u64>().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);
|
||||
/// The sampler, the heal and the lock overrides.
|
||||
fn apply_env_runtime(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> {
|
||||
if let Some(v) = env.number("LELEKA_MEMORY_SAMPLE_MS")? {
|
||||
self.sample_interval_ms = v.clamp(50, 60_000);
|
||||
}
|
||||
if let Some(v) = number("LELEKA_MEMORY_HARD_FLOOR_MIB")? {
|
||||
cfg.policy.hard_floor = v.saturating_mul(MIB);
|
||||
env.set_flag("LELEKA_MEMORY_HEAL", &mut self.heal)?;
|
||||
if let Some(v) = env.number("LELEKA_MEMORY_RESIDENCY_S")? {
|
||||
self.residency_every_ms = v.saturating_mul(1000).max(1000);
|
||||
}
|
||||
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_SWAPOUT_PAGES_PER_S")? {
|
||||
cfg.policy.swapout_pages_per_s_shed = v;
|
||||
}
|
||||
let float = |name: &str| -> Result<Option<f64>, String> {
|
||||
match env(name) {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|f| f.is_finite() && *f >= 0.0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| format!("{name}={v:?} is not a non-negative number")),
|
||||
}
|
||||
};
|
||||
if let Some(v) = number("LELEKA_MEMORY_PSI_GUARD_MIB")? {
|
||||
cfg.policy.psi_guard_available = v.saturating_mul(MIB);
|
||||
}
|
||||
if let Some(v) = float("LELEKA_MEMORY_PSI_SOME_SHED")? {
|
||||
cfg.policy.psi_some_shed = v;
|
||||
}
|
||||
if let Some(v) = float("LELEKA_MEMORY_PSI_FULL_REJECT")? {
|
||||
cfg.policy.psi_full_reject = 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())
|
||||
if let Some(v) = env.var("LELEKA_MEMORY_LOCK") {
|
||||
self.lock_mode = LockMode::parse(v.trim())
|
||||
.ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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<String>) -> Result<Self, String> {
|
||||
let mut cfg = Self::new(Policy::for_host(mem_total, laptop));
|
||||
cfg.policy.apply_env_floors(env)?;
|
||||
cfg.policy.apply_env_psi(env)?;
|
||||
cfg.apply_env_runtime(env)?;
|
||||
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)",
|
||||
"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
|
||||
));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Giving freed heap memory back to the kernel.
|
||||
//!
|
||||
//! glibc serves allocations below its (dynamic, up to 32 MiB) mmap threshold from the heap arenas and keeps freed pages there: evicting 4 GiB
|
||||
//! of 29 MB prefix-cache blocks would leave the process RSS, and so `MemAvailable`, unchanged, and the shed would not help the
|
||||
//! host at all. `trim` hands the free pages of every arena back (`malloc_trim(0)`), and is called after an eviction. On other
|
||||
//! allocators or platforms it does nothing.
|
||||
//! glibc serves allocations below its (dynamic, up to 32 MiB) mmap threshold from the heap arenas and keeps freed pages
|
||||
//! there: evicting 4 GiB of 29 MB prefix-cache blocks would leave the process RSS, and so `MemAvailable`, unchanged,
|
||||
//! and the shed would not help the host at all. `trim` hands the free pages of every arena back (`malloc_trim(0)`), and
|
||||
//! is called after an eviction. On other allocators or platforms it does nothing.
|
||||
|
||||
/// `LELEKA_MEMORY_NO_TRIM=1` turns `trim` into a no-op (for the A/B of what the trim buys).
|
||||
fn trim_disabled() -> bool {
|
||||
@@ -30,7 +30,8 @@ pub struct HeapStats {
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))]
|
||||
#[allow(unsafe_code)]
|
||||
pub fn stats() -> Option<HeapStats> {
|
||||
// SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters under its locks.
|
||||
// SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters
|
||||
// under its locks.
|
||||
let m = unsafe { libc::mallinfo2() };
|
||||
Some(HeapStats {
|
||||
arena: m.arena as u64,
|
||||
@@ -53,8 +54,8 @@ pub fn trim() -> bool {
|
||||
if trim_disabled() {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: `malloc_trim` takes no pointers; it walks the allocator's own free lists under the allocator's locks and releases whole
|
||||
// free pages with madvise. It is safe to call from any thread at any time.
|
||||
// SAFETY: `malloc_trim` takes no pointers; it walks the allocator's own free lists under the allocator's locks and
|
||||
// releases whole free pages with madvise. It is safe to call from any thread at any time.
|
||||
unsafe {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
|
||||
+110
-163
@@ -169,8 +169,8 @@ impl HostFacts {
|
||||
/// `/proc/self/cgroup` is not the unified hierarchy.
|
||||
fn probe_cgroup(src: &dyn ProcSource) -> Option<CgroupFacts> {
|
||||
let text = src.read("/proc/self/cgroup").ok()?;
|
||||
// the unified hierarchy first; on a hybrid host (WSL2, older container hosts) the memory controller may still be a v1
|
||||
// hierarchy, which is where the limit lives
|
||||
// the unified hierarchy first; on a hybrid host (WSL2, older container hosts) the memory controller may still be a
|
||||
// v1 hierarchy, which is where the limit lives
|
||||
let v2 = procfs::parse_cgroup_path(&text).and_then(|rel| probe_cgroup_v2(src, rel));
|
||||
if v2.as_ref().is_some_and(|c| !c.levels.is_empty()) {
|
||||
return v2;
|
||||
@@ -178,90 +178,127 @@ fn probe_cgroup(src: &dyn ProcSource) -> Option<CgroupFacts> {
|
||||
probe_cgroup_v1(src, &text).or(v2)
|
||||
}
|
||||
|
||||
/// cgroup v1 `memory` controller: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes`, `memory.stat` and the
|
||||
/// `oom_kill` counter of `memory.oom_control`.
|
||||
fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option<CgroupFacts> {
|
||||
const ROOT: &str = "/sys/fs/cgroup/memory";
|
||||
const UNLIMITED: u64 = 1 << 62;
|
||||
let rel = procfs::parse_cgroup_v1_memory_path(proc_cgroup)?;
|
||||
if rel.split('/').any(|c| c == ".." || c == ".") {
|
||||
/// Anything that could leave the cgroup root is refused.
|
||||
fn escapes_root(rel: &str) -> bool {
|
||||
rel.split('/').any(|c| c == ".." || c == ".")
|
||||
}
|
||||
|
||||
/// The directory of a cgroup path relative to the hierarchy `root`.
|
||||
fn cgroup_dir(root: &str, rel: &str) -> String {
|
||||
format!("{root}{}", if rel == "/" { String::new() } else { rel.to_owned() })
|
||||
}
|
||||
|
||||
/// The directory above `dir`, down to and including `root`; `None` at the root.
|
||||
fn parent_dir(dir: &str, root: &str) -> Option<String> {
|
||||
if dir == root {
|
||||
return None;
|
||||
}
|
||||
let own = format!("{ROOT}{}", if rel == "/" { String::new() } else { rel.clone() });
|
||||
let mut dir = own.clone();
|
||||
let mut levels = Vec::new();
|
||||
loop {
|
||||
let limit = src.read(&format!("{dir}/memory.limit_in_bytes")).ok().and_then(|t| t.trim().parse::<u64>().ok());
|
||||
let current = src.read(&format!("{dir}/memory.usage_in_bytes")).ok().and_then(|t| t.trim().parse::<u64>().ok());
|
||||
let stat = src.read(&format!("{dir}/memory.stat")).ok();
|
||||
let reclaimable = stat
|
||||
.as_deref()
|
||||
.and_then(|t| {
|
||||
procfs::flat_keyed(t, "total_inactive_file").or_else(|| procfs::flat_keyed(t, "inactive_file"))
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if limit.is_some() || current.is_some() {
|
||||
let limit = limit.filter(|l| *l < UNLIMITED);
|
||||
let headroom = match (limit, current) {
|
||||
(Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))),
|
||||
_ => None,
|
||||
};
|
||||
levels.push(CgroupLevel { path: dir.clone(), limit, current, reclaimable, headroom });
|
||||
}
|
||||
if dir == ROOT {
|
||||
break;
|
||||
}
|
||||
match dir.rfind('/') {
|
||||
Some(i) if i >= ROOT.len() => dir.truncate(i),
|
||||
_ => break,
|
||||
}
|
||||
match dir.rfind('/') {
|
||||
Some(i) if i >= root.len() => Some(dir[..i].to_owned()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The levels from `own` up to `root`, innermost first; `level` reads one directory (`None` = nothing there).
|
||||
fn walk_levels(own: &str, root: &str, mut level: impl FnMut(&str) -> Option<CgroupLevel>) -> Vec<CgroupLevel> {
|
||||
let mut levels = Vec::new();
|
||||
let mut dir = Some(own.to_owned());
|
||||
while let Some(d) = dir {
|
||||
levels.extend(level(&d));
|
||||
dir = parent_dir(&d, root);
|
||||
}
|
||||
levels
|
||||
}
|
||||
|
||||
/// The tightest limit among the levels (and where it is), and the smallest headroom.
|
||||
fn tightest_and_headroom(levels: &[CgroupLevel]) -> (Option<(u64, String)>, Option<u64>) {
|
||||
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();
|
||||
(tightest, levels.iter().filter_map(|l| l.headroom).min())
|
||||
}
|
||||
|
||||
/// `limit - current + reclaimable` (the reclaimable part counted only up to what is in use).
|
||||
fn headroom_of(limit: Option<u64>, current: Option<u64>, reclaimable: u64) -> Option<u64> {
|
||||
match (limit, current) {
|
||||
(Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A number in a one-line cgroup file.
|
||||
fn read_number(src: &(impl ProcSource + ?Sized), path: &str) -> Option<u64> {
|
||||
src.read(path).ok().and_then(|t| t.trim().parse::<u64>().ok())
|
||||
}
|
||||
|
||||
/// One v1 level: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes` and `memory.stat`.
|
||||
fn level_v1(src: &(impl ProcSource + ?Sized), dir: &str) -> Option<CgroupLevel> {
|
||||
const UNLIMITED: u64 = 1 << 62;
|
||||
let limit = read_number(src, &format!("{dir}/memory.limit_in_bytes"));
|
||||
let current = read_number(src, &format!("{dir}/memory.usage_in_bytes"));
|
||||
let stat = src.read(&format!("{dir}/memory.stat")).ok();
|
||||
let reclaimable = stat
|
||||
.as_deref()
|
||||
.and_then(|t| procfs::flat_keyed(t, "total_inactive_file").or_else(|| procfs::flat_keyed(t, "inactive_file")))
|
||||
.unwrap_or(0);
|
||||
if limit.is_none() && current.is_none() {
|
||||
return None;
|
||||
}
|
||||
let limit = limit.filter(|l| *l < UNLIMITED);
|
||||
Some(CgroupLevel {
|
||||
path: dir.to_owned(),
|
||||
limit,
|
||||
current,
|
||||
reclaimable,
|
||||
headroom: headroom_of(limit, current, reclaimable),
|
||||
})
|
||||
}
|
||||
|
||||
/// cgroup v1 `memory` controller: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes`, `memory.stat`
|
||||
/// and the `oom_kill` counter of `memory.oom_control`.
|
||||
fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option<CgroupFacts> {
|
||||
const ROOT: &str = "/sys/fs/cgroup/memory";
|
||||
let rel = procfs::parse_cgroup_v1_memory_path(proc_cgroup)?;
|
||||
if escapes_root(&rel) {
|
||||
return None;
|
||||
}
|
||||
let own = cgroup_dir(ROOT, &rel);
|
||||
let levels = walk_levels(&own, ROOT, |dir| level_v1(src, dir));
|
||||
let (limit, headroom) = tightest_and_headroom(&levels);
|
||||
let oom_kill = src.read(&format!("{own}/memory.oom_control")).ok().and_then(|t| procfs::flat_keyed(&t, "oom_kill"));
|
||||
let events = oom_kill.map(|k| CgroupEvents { low: 0, high: 0, max: 0, oom: k, oom_kill: k });
|
||||
Some(CgroupFacts { path: rel, levels, limit: tightest, headroom, swap_max: None, events })
|
||||
Some(CgroupFacts { path: rel, levels, limit, headroom, swap_max: None, events })
|
||||
}
|
||||
|
||||
/// One v2 level: `memory.max`, `memory.current` and `memory.stat`.
|
||||
fn level_v2(src: &(impl ProcSource + ?Sized), dir: &str) -> Option<CgroupLevel> {
|
||||
// limit: Some(Some(n)) = a limit, Some(None) = "max", None = unreadable (a level without the controller)
|
||||
let limit = src.read(&format!("{dir}/memory.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t));
|
||||
let current = read_number(src, &format!("{dir}/memory.current"));
|
||||
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);
|
||||
if limit.is_none() && current.is_none() {
|
||||
return None;
|
||||
}
|
||||
let limit = limit.flatten();
|
||||
Some(CgroupLevel {
|
||||
path: dir.to_owned(),
|
||||
limit,
|
||||
current,
|
||||
reclaimable,
|
||||
headroom: headroom_of(limit, current, reclaimable),
|
||||
})
|
||||
}
|
||||
|
||||
fn probe_cgroup_v2(src: &dyn ProcSource, rel: String) -> Option<CgroupFacts> {
|
||||
// Refuse anything that could leave the cgroup root.
|
||||
if rel.split('/').any(|c| c == ".." || c == ".") {
|
||||
if escapes_root(&rel) {
|
||||
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::<u64>().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 own = cgroup_dir(CGROUP_ROOT, &rel);
|
||||
let levels = walk_levels(&own, CGROUP_ROOT, |dir| level_v2(src, dir));
|
||||
let (limit, headroom) = tightest_and_headroom(&levels);
|
||||
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 })
|
||||
Some(CgroupFacts { path: rel, levels, limit, headroom, swap_max, events })
|
||||
}
|
||||
|
||||
/// Advice text for the WSL2 case, appended to refusals.
|
||||
@@ -271,94 +308,4 @@ pub fn wsl_advice() -> &'static str {
|
||||
}
|
||||
|
||||
#[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_v1_memory_controller_limit_is_honoured_on_a_hybrid_host() {
|
||||
let mut p = server();
|
||||
p.set("/proc/self/cgroup", "5:memory:/docker/abc\n0::/docker/abc\n");
|
||||
let base = "/sys/fs/cgroup/memory/docker/abc";
|
||||
p.set(&format!("{base}/memory.limit_in_bytes"), &format!("{}\n", 12u64 << 30));
|
||||
p.set(&format!("{base}/memory.usage_in_bytes"), &format!("{}\n", 11u64 << 30));
|
||||
p.set(&format!("{base}/memory.stat"), &format!("cache 1\ntotal_inactive_file {}\n", 512u64 << 20));
|
||||
p.set(&format!("{base}/memory.oom_control"), "oom_kill_disable 0\nunder_oom 0\noom_kill 2\n");
|
||||
p.set("/sys/fs/cgroup/memory/memory.limit_in_bytes", "9223372036854771712\n");
|
||||
p.set("/sys/fs/cgroup/memory/memory.usage_in_bytes", "123\n");
|
||||
let f = HostFacts::probe(&p);
|
||||
let cg = f.cgroup.as_ref().unwrap();
|
||||
assert_eq!(cg.limit, Some((12 << 30, base.to_owned())));
|
||||
assert_eq!(cg.headroom, Some((1u64 << 30) + (512 << 20)));
|
||||
assert_eq!(f.effective_available(), Some((1u64 << 30) + (512 << 20)));
|
||||
assert_eq!(cg.events.unwrap().oom_kill, 2);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
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_v1_memory_controller_limit_is_honoured_on_a_hybrid_host() {
|
||||
let mut p = server();
|
||||
p.set("/proc/self/cgroup", "5:memory:/docker/abc\n0::/docker/abc\n");
|
||||
let base = "/sys/fs/cgroup/memory/docker/abc";
|
||||
p.set(&format!("{base}/memory.limit_in_bytes"), &format!("{}\n", 12u64 << 30));
|
||||
p.set(&format!("{base}/memory.usage_in_bytes"), &format!("{}\n", 11u64 << 30));
|
||||
p.set(&format!("{base}/memory.stat"), &format!("cache 1\ntotal_inactive_file {}\n", 512u64 << 20));
|
||||
p.set(&format!("{base}/memory.oom_control"), "oom_kill_disable 0\nunder_oom 0\noom_kill 2\n");
|
||||
p.set("/sys/fs/cgroup/memory/memory.limit_in_bytes", "9223372036854771712\n");
|
||||
p.set("/sys/fs/cgroup/memory/memory.usage_in_bytes", "123\n");
|
||||
let f = HostFacts::probe(&p);
|
||||
let cg = f.cgroup.as_ref().unwrap();
|
||||
assert_eq!(cg.limit, Some((12 << 30, base.to_owned())));
|
||||
assert_eq!(cg.headroom, Some((1u64 << 30) + (512 << 20)));
|
||||
assert_eq!(f.effective_available(), Some((1u64 << 30) + (512 << 20)));
|
||||
assert_eq!(cg.events.unwrap().oom_kill, 2);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
@@ -190,7 +190,8 @@ impl Inventory {
|
||||
}
|
||||
totals
|
||||
}
|
||||
/// Host RAM the classes account for: everything except file-backed mappings (the OS file cache holds those and gives them back).
|
||||
/// Host RAM the classes account for: everything except file-backed mappings (the OS file cache holds those and
|
||||
/// gives them back).
|
||||
pub fn total_host(&self) -> u64 {
|
||||
self.lock().values().filter(|e| e.space.is_host() && e.space != Space::HostMapped).map(|e| e.bytes).sum()
|
||||
}
|
||||
@@ -215,50 +216,49 @@ impl Inventory {
|
||||
/// 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!(
|
||||
rows.sort_by(|a, b| row_key(a).cmp(&row_key(b)));
|
||||
let mut out = format!(
|
||||
"{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n",
|
||||
"space", "when", "component.class", "MiB", "peak MiB", "planned", "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} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n",
|
||||
e.space.label(),
|
||||
e.when.label(),
|
||||
e.id(),
|
||||
mib(e.bytes),
|
||||
mib(e.peak),
|
||||
e.expected.map_or("-".to_owned(), mib),
|
||||
if e.swappable { "yes" } else { "no" },
|
||||
e.formula
|
||||
));
|
||||
out.push_str(&table_row(e));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"{:<15} {:<11} {:<34} {:>11}\n{:<15} {:<11} {:<34} {:>11}\n{:<15} {:<11} {:<34} {:>11}\n",
|
||||
"total",
|
||||
"",
|
||||
"host RAM (accounted)",
|
||||
mib(self.total_host()),
|
||||
"total",
|
||||
"",
|
||||
"file-mapped (page cache)",
|
||||
mib(self.total_mapped()),
|
||||
"total",
|
||||
"",
|
||||
"device (accounted)",
|
||||
mib(self.total_device())
|
||||
));
|
||||
out.push_str(&self.total_rows());
|
||||
out
|
||||
}
|
||||
|
||||
/// The three total lines closing the table: host RAM, file-mapped memory, device memory.
|
||||
fn total_rows(&self) -> String {
|
||||
let total =
|
||||
|label: &str, bytes: u64| format!("{:<15} {:<11} {:<34} {:>11}\n", "total", "", label, mib_text(bytes));
|
||||
total("host RAM (accounted)", self.total_host())
|
||||
+ &total("file-mapped (page cache)", self.total_mapped())
|
||||
+ &total("device (accounted)", self.total_device())
|
||||
}
|
||||
}
|
||||
|
||||
/// The order of the table: by space, when, component and class.
|
||||
fn row_key(e: &Entry) -> (Space, When, &str, &str) {
|
||||
(e.space, e.when, e.component.as_str(), e.class.as_str())
|
||||
}
|
||||
|
||||
fn mib_text(bytes: u64) -> String {
|
||||
format!("{:.1}", bytes as f64 / 1_048_576.0)
|
||||
}
|
||||
|
||||
fn table_row(e: &Entry) -> String {
|
||||
format!(
|
||||
"{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n",
|
||||
e.space.label(),
|
||||
e.when.label(),
|
||||
e.id(),
|
||||
mib_text(e.bytes),
|
||||
mib_text(e.peak),
|
||||
e.expected.map_or("-".to_owned(), mib_text),
|
||||
if e.swappable { "yes" } else { "no" },
|
||||
e.formula
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! 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.
|
||||
//! 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`.
|
||||
//! 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;
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
//! 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`).
|
||||
//! 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.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl LockMode, fn plan_lock, impl LockOutcome, fn residency_from_smaps, fn spans_bytes, fn check_spans ....
|
||||
//! Moved out of the parent module by STRA-338: impl LockMode, fn plan_lock, impl LockOutcome, fn residency_from_smaps,
|
||||
//! fn spans_bytes, fn check_spans ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -14,7 +15,27 @@ impl LockMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the capabilities?
|
||||
/// What the operator can change when `RLIMIT_MEMLOCK` cannot cover `need` bytes.
|
||||
fn memlock_advice(need: u64) -> Vec<String> {
|
||||
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(),
|
||||
concat!(
|
||||
"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(),
|
||||
]
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -27,16 +48,7 @@ pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status:
|
||||
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(),
|
||||
],
|
||||
},
|
||||
Some((soft, hard)) => LockDecision::Insufficient { need, soft, hard, advice: memlock_advice(need) },
|
||||
None => LockDecision::Attempt { raise_soft_to: None },
|
||||
}
|
||||
}
|
||||
@@ -66,7 +78,8 @@ pub fn spans_bytes(spans: &[Span]) -> u64 {
|
||||
spans.iter().map(|s| s.1).sum()
|
||||
}
|
||||
|
||||
/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, disjoint, inside?
|
||||
/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted,
|
||||
/// disjoint, inside?
|
||||
pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> {
|
||||
let mut previous_end = 0u64;
|
||||
for (i, (offset, n)) in spans.iter().enumerate() {
|
||||
@@ -81,9 +94,9 @@ pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, at most
|
||||
/// `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A sparse archive
|
||||
/// is walked with this so that nothing is ever asked of a hole.
|
||||
/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`,
|
||||
/// at most `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A
|
||||
/// sparse archive is walked with this so that nothing is ever asked of a hole.
|
||||
pub fn compact_piece(spans: &[Span], pos: u64, max: u64) -> Option<(u64, u64)> {
|
||||
let mut start = 0u64;
|
||||
for (offset, n) in spans {
|
||||
|
||||
@@ -98,7 +98,8 @@ impl FdMapping {
|
||||
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.
|
||||
// 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}") };
|
||||
@@ -108,10 +109,29 @@ impl FdMapping {
|
||||
}
|
||||
LockOutcome::Locked { bytes: self.locked }
|
||||
}
|
||||
/// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before
|
||||
/// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file
|
||||
/// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the
|
||||
/// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans.
|
||||
/// `mlock` the `n` bytes at `offset` of the mapping; the reason when that fails.
|
||||
fn mlock_range(&self, offset: u64, n: u64) -> Result<(), String> {
|
||||
let (ptr, n_usize) = self.range(offset, n).map_err(|e| 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 {
|
||||
return Err(format!("mlock: {}", io::Error::last_os_error()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Ask `allow`, then `mlock` and record the `n` bytes at `offset`; the reason when either refuses.
|
||||
fn lock_chunk(&mut self, offset: u64, n: u64, allow: &mut impl FnMut(u64) -> bool) -> Result<(), String> {
|
||||
if !allow(n) {
|
||||
return Err("host memory guard refused the next chunk".to_owned());
|
||||
}
|
||||
self.mlock_range(offset, n)?;
|
||||
self.locked_spans.push((offset, n));
|
||||
Ok(())
|
||||
}
|
||||
/// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling
|
||||
/// `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. The holes between the spans are never
|
||||
/// touched: `mlock` of a hole in a shmem file allocates zero pages for it (the sparse copy would silently become
|
||||
/// the full 55 GB again), so a range outside the spans is not representable here. `check_spans` runs first. The
|
||||
/// counter `locked_bytes` is the sum of the locked spans.
|
||||
pub fn lock_ranges(
|
||||
&mut self,
|
||||
spans: &[super::Span],
|
||||
@@ -128,23 +148,9 @@ impl FdMapping {
|
||||
let mut done = 0u64;
|
||||
while done < span_len {
|
||||
let n = chunk.min(span_len - done);
|
||||
if !allow(n) {
|
||||
return LockOutcome::Partial {
|
||||
locked,
|
||||
wanted,
|
||||
why: "host memory guard refused the next chunk".into(),
|
||||
};
|
||||
if let Err(why) = self.lock_chunk(span_offset + done, n, &mut allow) {
|
||||
return LockOutcome::Partial { locked, wanted, why };
|
||||
}
|
||||
let (ptr, n_usize) = match self.range(span_offset + done, n) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return LockOutcome::Partial { locked, wanted, 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, wanted, why: format!("mlock: {e}") };
|
||||
}
|
||||
self.locked_spans.push((span_offset + done, n));
|
||||
done += n;
|
||||
locked += n;
|
||||
self.locked = locked;
|
||||
@@ -166,8 +172,8 @@ impl FdMapping {
|
||||
}
|
||||
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.
|
||||
/// 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<Vec<bool>> {
|
||||
let (ptr, n_usize) = self.range(offset, n)?;
|
||||
let pages = n_usize.div_ceil(PAGE as usize);
|
||||
@@ -323,7 +329,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() {
|
||||
// the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be needed
|
||||
// the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be
|
||||
// needed
|
||||
let f = sparse_memfd(256, &[(10, 4), (100, 6)]);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap();
|
||||
let outcome = m.lock(64 * PAGE, |_| true);
|
||||
|
||||
@@ -28,8 +28,8 @@ pub struct Policy {
|
||||
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) and for lazy growth the plan does not model.
|
||||
/// 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) and for lazy growth the plan does not model.
|
||||
/// It is also the margin above the soft floor at which the caches stop admitting (see `Policy::admit_floor`).
|
||||
pub reserve: u64,
|
||||
/// Leaving a level needs this much margin above its threshold.
|
||||
@@ -40,8 +40,9 @@ pub struct Policy {
|
||||
pub prefix_cap: u64,
|
||||
/// An `auto` cache smaller than this is off.
|
||||
pub min_useful_cache: u64,
|
||||
/// PSI is system wide and is raised by any reader streaming a file through the page cache (job 910: a `dd` of the KAR file drove `full` to
|
||||
/// 5.2% with 68 GiB available), so it only counts while available memory is below this; above it the stalls are not about us.
|
||||
/// PSI is system wide and is raised by any reader streaming a file through the page cache (job 910: a `dd` of the
|
||||
/// KAR file drove `full` to 5.2% with 68 GiB available), so it only counts while available memory is below this;
|
||||
/// above it the stalls are not about us.
|
||||
pub psi_guard_available: u64,
|
||||
/// PSI `some avg10` (percent of time stalled) that starts shedding.
|
||||
pub psi_some_shed: f64,
|
||||
|
||||
@@ -14,10 +14,10 @@ pub fn auto_prefix_budget(available: Option<u64>, policy: &Policy, complement_pi
|
||||
if bytes < policy.min_useful_cache { 0 } else { bytes }
|
||||
}
|
||||
|
||||
/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the wish**.
|
||||
/// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM
|
||||
/// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number.
|
||||
/// Returns the granted bytes and the elastic memory it was clamped against.
|
||||
/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the
|
||||
/// wish**. Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing
|
||||
/// RAM elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's
|
||||
/// number. Returns the granted bytes and the elastic memory it was clamped against.
|
||||
pub fn explicit_prefix_budget(
|
||||
wish: u64,
|
||||
available: Option<u64>,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Policy, impl FixedItem, impl std_fmt_Display, impl std_error_Error, fn gib, fn check_vram ....
|
||||
//! Moved out of the parent module by STRA-338: impl Policy, impl FixedItem, impl std_fmt_Display, impl std_error_Error,
|
||||
//! fn gib, fn check_vram ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl Policy {
|
||||
/// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`.
|
||||
/// Below this much available memory a cache stops admitting new entries (before anything has to be shed):
|
||||
/// `soft_floor + reserve`.
|
||||
pub fn admit_floor(&self) -> u64 {
|
||||
self.soft_floor.saturating_add(self.reserve)
|
||||
}
|
||||
@@ -13,7 +15,8 @@ impl Policy {
|
||||
Self {
|
||||
soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB),
|
||||
hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB),
|
||||
// 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in the real Codex CRM session (job 945)
|
||||
// 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in
|
||||
// the real Codex CRM session (job 945)
|
||||
reserve: 2 * GIB,
|
||||
hysteresis: GIB,
|
||||
cache_share_percent: 75,
|
||||
@@ -54,8 +57,25 @@ pub fn gib(bytes: u64) -> String {
|
||||
format!("{:.2} GiB", bytes as f64 / GIB as f64)
|
||||
}
|
||||
|
||||
/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the free
|
||||
/// VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned.
|
||||
/// The device does not have room for the measured fixed footprint.
|
||||
fn vram_refusal(plan: &VramPlan, estimate: u64) -> Refusal {
|
||||
Refusal {
|
||||
code: "vram",
|
||||
message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)),
|
||||
numbers: vec![
|
||||
("vram free".into(), plan.free),
|
||||
("vram fixed footprint".into(), estimate),
|
||||
("vram headroom".into(), plan.headroom),
|
||||
],
|
||||
advice: vec![
|
||||
"stop the other GPU processes (nvidia-smi)".into(),
|
||||
"lower --gpu-budget / the expert slots / --kv-resident".into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the
|
||||
/// free VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned.
|
||||
pub fn check_vram(
|
||||
policy: &Policy,
|
||||
vram: VramFacts,
|
||||
@@ -67,19 +87,7 @@ pub fn check_vram(
|
||||
&& plan.free < estimate.saturating_add(plan.headroom)
|
||||
&& policy.enforce
|
||||
{
|
||||
return Err(Refusal {
|
||||
code: "vram",
|
||||
message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)),
|
||||
numbers: vec![
|
||||
("vram free".into(), plan.free),
|
||||
("vram fixed footprint".into(), estimate),
|
||||
("vram headroom".into(), plan.headroom),
|
||||
],
|
||||
advice: vec![
|
||||
"stop the other GPU processes (nvidia-smi)".into(),
|
||||
"lower --gpu-budget / the expert slots / --kv-resident".into(),
|
||||
],
|
||||
});
|
||||
return Err(vram_refusal(&plan, estimate));
|
||||
}
|
||||
let note = (plan.free < plan.budget).then(|| {
|
||||
format!(
|
||||
@@ -91,159 +99,240 @@ pub fn check_vram(
|
||||
Ok((plan, note))
|
||||
}
|
||||
|
||||
/// The budget. Pure: no file system, no clock.
|
||||
pub fn plan(input: &PlanInput) -> Result<Plan, Refusal> {
|
||||
let policy = input.policy;
|
||||
let mut notes: Vec<String> = 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 = match input.vram {
|
||||
Some(v) => {
|
||||
let (plan, note) = check_vram(&policy, v, input.vram_budget, input.vram_fixed_estimate)?;
|
||||
notes.extend(note);
|
||||
Some(plan)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
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);
|
||||
/// What the host has and what the fixed items still take from it.
|
||||
struct HostBudget {
|
||||
available: u64,
|
||||
fixed_bytes: u64,
|
||||
kar_to_create: u64,
|
||||
/// `soft_floor + reserve`: what must be left after the fixed footprint.
|
||||
required_after: u64,
|
||||
}
|
||||
|
||||
// 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;
|
||||
impl HostBudget {
|
||||
fn needs(&self) -> u64 {
|
||||
self.fixed_bytes.saturating_add(self.kar_to_create)
|
||||
}
|
||||
// 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)
|
||||
));
|
||||
}
|
||||
}
|
||||
/// Available memory after the fixed footprint; `None` when it does not even fit.
|
||||
fn after(&self) -> Option<u64> {
|
||||
self.available.checked_sub(self.needs())
|
||||
}
|
||||
Ok(Plan {
|
||||
available_before: Some(available),
|
||||
}
|
||||
|
||||
/// The plan of a host without memory telemetry: caches off, the monitor sheds (fail closed).
|
||||
fn blind_plan(
|
||||
input: &PlanInput,
|
||||
kar_to_create: u64,
|
||||
fixed_bytes: u64,
|
||||
vram: Option<VramPlan>,
|
||||
notes: Vec<String>,
|
||||
) -> Plan {
|
||||
let policy = input.policy;
|
||||
Plan {
|
||||
available_before: None,
|
||||
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,
|
||||
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: false,
|
||||
blind: true,
|
||||
vram,
|
||||
notes,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the operator can change when the fixed footprint does not leave room.
|
||||
fn host_ram_advice(input: &PlanInput) -> Vec<String> {
|
||||
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());
|
||||
}
|
||||
advice
|
||||
}
|
||||
|
||||
/// The fixed host footprint leaves less than `soft_floor + reserve`.
|
||||
fn host_ram_refusal(input: &PlanInput, hb: &HostBudget) -> Refusal {
|
||||
let (needs, available) = (hb.needs(), hb.available);
|
||||
let mut numbers = vec![("available".to_owned(), available), ("fixed host footprint".to_owned(), hb.fixed_bytes)];
|
||||
if hb.kar_to_create > 0 {
|
||||
numbers.push(("sealed KAR memfd to create".to_owned(), hb.kar_to_create));
|
||||
}
|
||||
numbers.push(("soft floor + reserve".to_owned(), hb.required_after));
|
||||
numbers.push(("short by".to_owned(), hb.required_after.saturating_add(needs).saturating_sub(available)));
|
||||
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),
|
||||
hb.after().map_or("nothing".to_owned(), gib),
|
||||
gib(available),
|
||||
gib(hb.required_after)
|
||||
),
|
||||
numbers,
|
||||
advice: host_ram_advice(input),
|
||||
}
|
||||
}
|
||||
|
||||
/// The explicit resident complement (pinned at open), clamped to the elastic memory.
|
||||
fn size_complement(input: &PlanInput, elastic: u64, notes: &mut Vec<String>) -> u64 {
|
||||
let Some(wish) = input.resident_complement else {
|
||||
return 0;
|
||||
};
|
||||
let complement = wish.min(elastic);
|
||||
if complement < wish {
|
||||
notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement)));
|
||||
}
|
||||
complement
|
||||
}
|
||||
|
||||
/// Conversation checkpoints, the replacement of a prefix cache that is off: how many fit.
|
||||
fn size_checkpoints(input: &PlanInput, elastic: u64, notes: &mut Vec<String>) -> u64 {
|
||||
let each = input.checkpoint_bytes.max(1);
|
||||
let 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)
|
||||
));
|
||||
}
|
||||
checkpoints
|
||||
}
|
||||
|
||||
/// An `auto` prefix cache: a share of the elastic memory, capped, or off when below the useful minimum.
|
||||
fn size_auto_prefix(policy: &Policy, elastic: u64, notes: &mut Vec<String>) -> u64 {
|
||||
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)
|
||||
));
|
||||
return 0;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// An explicit prefix cache budget, clamped to the elastic memory.
|
||||
fn size_wished_prefix(wish: u64, elastic: u64, notes: &mut Vec<String>) -> u64 {
|
||||
let bytes = wish.min(elastic) / MIB * MIB;
|
||||
if bytes < wish {
|
||||
notes.push(format!(
|
||||
"prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory",
|
||||
gib(wish),
|
||||
gib(bytes),
|
||||
gib(elastic)
|
||||
));
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The device plan of a host that reports free VRAM (refuses when the fixed footprint cannot fit).
|
||||
fn plan_vram(input: &PlanInput, notes: &mut Vec<String>) -> Result<Option<VramPlan>, Refusal> {
|
||||
let Some(v) = input.vram else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (plan, note) = check_vram(&input.policy, v, input.vram_budget, input.vram_fixed_estimate)?;
|
||||
notes.extend(note);
|
||||
Ok(Some(plan))
|
||||
}
|
||||
|
||||
const BLIND_NOTE: &str =
|
||||
"host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)";
|
||||
|
||||
/// Refuse when the fixed footprint leaves too little, unless enforcement is off (then say so in the notes).
|
||||
fn check_enforced(input: &PlanInput, hb: &HostBudget, notes: &mut Vec<String>) -> Result<(), Refusal> {
|
||||
let refusal = host_ram_refusal(input, hb);
|
||||
if input.policy.enforce {
|
||||
return Err(refusal);
|
||||
}
|
||||
notes.push(format!("ENFORCEMENT OFF: {refusal}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How the elastic memory was divided between the caches.
|
||||
struct Caches {
|
||||
complement: u64,
|
||||
/// What is left of the elastic memory after the complement.
|
||||
elastic: u64,
|
||||
prefix_bytes: u64,
|
||||
checkpoints: u64,
|
||||
conversation_bytes: u64,
|
||||
}
|
||||
|
||||
fn size_caches(input: &PlanInput, elastic: u64, notes: &mut Vec<String>) -> Caches {
|
||||
// 1. the resident complement (explicit, pinned at open)
|
||||
let complement = size_complement(input, elastic, notes);
|
||||
let elastic = elastic - complement;
|
||||
let mut caches = Caches { complement, elastic, prefix_bytes: 0, checkpoints: 0, conversation_bytes: 0 };
|
||||
// 2. the prefix cache, or the conversation checkpoints it replaces
|
||||
match input.prefix {
|
||||
CacheWish::Off => {
|
||||
caches.checkpoints = size_checkpoints(input, elastic, notes);
|
||||
caches.conversation_bytes = caches.checkpoints * input.checkpoint_bytes;
|
||||
}
|
||||
CacheWish::Auto => caches.prefix_bytes = size_auto_prefix(&input.policy, elastic, notes),
|
||||
CacheWish::Bytes(wish) => caches.prefix_bytes = size_wished_prefix(wish, elastic, notes),
|
||||
}
|
||||
caches
|
||||
}
|
||||
|
||||
/// Host bytes of the fixed items the runtime has yet to allocate.
|
||||
fn fixed_host_bytes(input: &PlanInput) -> u64 {
|
||||
input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum()
|
||||
}
|
||||
|
||||
/// The sealed memfd this process still has to create (an inherited one is already out of `MemAvailable`).
|
||||
fn kar_bytes_to_create(input: &PlanInput) -> u64 {
|
||||
match input.kar {
|
||||
KarForm::MemfdToCreate { bytes } => bytes,
|
||||
KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The budget. Pure: no file system, no clock.
|
||||
pub fn plan(input: &PlanInput) -> Result<Plan, Refusal> {
|
||||
let mut notes: Vec<String> = Vec::new();
|
||||
let (fixed_bytes, kar_to_create) = (fixed_host_bytes(input), kar_bytes_to_create(input));
|
||||
let vram = plan_vram(input, &mut notes)?;
|
||||
let Some(available) = input.host.effective_available() else {
|
||||
notes.push(BLIND_NOTE.into());
|
||||
return Ok(blind_plan(input, kar_to_create, fixed_bytes, vram, notes));
|
||||
};
|
||||
let required_after = input.policy.soft_floor.saturating_add(input.policy.reserve);
|
||||
let hb = HostBudget { available, fixed_bytes, kar_to_create, required_after };
|
||||
let after = hb.after();
|
||||
if after.is_none_or(|r| r < required_after) {
|
||||
check_enforced(input, &hb, &mut notes)?;
|
||||
}
|
||||
let after = after.unwrap_or(0);
|
||||
let c = size_caches(input, after.saturating_sub(required_after), &mut notes);
|
||||
Ok(Plan {
|
||||
available_before: Some(available),
|
||||
available_after_fixed: Some(after),
|
||||
elastic: c.elastic + c.complement,
|
||||
resident_complement_bytes: c.complement,
|
||||
prefix_bytes: c.prefix_bytes,
|
||||
conversation_checkpoints: c.checkpoints,
|
||||
conversation_bytes: c.conversation_bytes,
|
||||
blind: false,
|
||||
..blind_plan(input, kar_to_create, fixed_bytes, vram, notes)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -170,8 +170,9 @@ fn auto_budget_at_open_follows_the_same_rule_and_fails_closed() {
|
||||
let b = auto_prefix_budget(Some(g(22)), &p, 0);
|
||||
assert!(b >= g(12) && b < g(13), "{b}"); // (22 - 4 - 2) x 75%
|
||||
assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b);
|
||||
// the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the host sat at 7.4 GiB
|
||||
// available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and takes 75% of the rest
|
||||
// the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the
|
||||
// host sat at 7.4 GiB available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and
|
||||
// takes 75% of the rest
|
||||
let crm = auto_prefix_budget(Some(14_064 * MIB), &p, 0);
|
||||
assert!(crm > 5 * GIB + 800 * MIB && crm < 6 * GIB + 100 * MIB, "{crm}");
|
||||
assert!(14_064 * MIB - crm > 7 * GIB + 900 * MIB, "at least ~8 GiB stays available with the cache full");
|
||||
@@ -191,7 +192,8 @@ fn floors_scale_with_very_large_hosts_only() {
|
||||
fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() {
|
||||
let p = Policy::for_host(g(121), false);
|
||||
let cap = 6144 * MIB;
|
||||
// the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure ~14 GiB)
|
||||
// the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure
|
||||
// ~14 GiB)
|
||||
let before = 14_064 * MIB;
|
||||
// the sparse memfd frees ~36.6 GiB of shmem: MemAvailable at open rises by that much
|
||||
let after = before + 36_600 * MIB;
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! * [`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.
|
||||
//! * [`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`.
|
||||
|
||||
@@ -108,162 +109,6 @@ impl Monitor {
|
||||
self.policy = 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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
// stalls count only while memory is not plentiful (see `Policy::psi_guard_available`); unknown available memory counts
|
||||
let psi_counts = s.available.is_none_or(|a| a < p.psi_guard_available);
|
||||
if let Some(psi) = s.psi.filter(|_| psi_counts) {
|
||||
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 = s.psi.map(|p| p.some.avg10);
|
||||
self.observed.psi_full_avg10 = s.psi.map(|p| p.full.avg10);
|
||||
}
|
||||
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<Transition> {
|
||||
let (wanted, why, relaxed) = self.target(s);
|
||||
@@ -303,5 +148,7 @@ impl Monitor {
|
||||
}
|
||||
}
|
||||
|
||||
mod ask;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! The level a sample asks for: one step per signal (available memory, PSI, cgroup events, swap-out rate), each
|
||||
//! raising the asked level and the level that still holds once the hysteresis margin is added.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The level a sample asks for, why, and the level that still holds with the hysteresis margin added to every
|
||||
/// threshold (to decide a step down).
|
||||
struct Ask {
|
||||
level: Level,
|
||||
why: String,
|
||||
relaxed: Level,
|
||||
}
|
||||
|
||||
impl Ask {
|
||||
fn new() -> Self {
|
||||
Self { level: Level::Normal, why: String::from("within budget"), relaxed: Level::Normal }
|
||||
}
|
||||
|
||||
/// A signal asks for `level` (and still holds it relaxed).
|
||||
fn raise(&mut self, level: Level, reason: String) {
|
||||
if level > self.level {
|
||||
self.level = level;
|
||||
self.why = reason;
|
||||
}
|
||||
self.hold(level);
|
||||
}
|
||||
|
||||
/// The relaxed view still holds at least `level`.
|
||||
fn hold(&mut self, level: Level) {
|
||||
self.relaxed = self.relaxed.max(level);
|
||||
}
|
||||
}
|
||||
|
||||
/// Available memory against the floors, and against the floors plus the margin.
|
||||
fn ask_available_known(a: u64, p: &Policy, ask: &mut Ask) {
|
||||
let (hard, soft, h) = (p.hard_floor, p.soft_floor, p.hysteresis);
|
||||
if a < hard {
|
||||
ask.raise(Level::Reject, format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20));
|
||||
} else if a < soft {
|
||||
ask.raise(Level::Shed, format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20));
|
||||
}
|
||||
// what the relaxed (stepping-down) view still holds
|
||||
let relaxed = if a < hard.saturating_add(h) {
|
||||
Level::Reject
|
||||
} else if a < soft.saturating_add(h) {
|
||||
Level::Shed
|
||||
} else {
|
||||
Level::Normal
|
||||
};
|
||||
ask.hold(relaxed);
|
||||
}
|
||||
|
||||
/// Stalls: `full` refuses, `some` sheds; stepping down needs them clearly below the limit.
|
||||
fn ask_psi_levels(psi: Psi, p: &Policy, ask: &mut Ask) {
|
||||
if psi.full.avg10 >= p.psi_full_reject {
|
||||
ask.raise(Level::Reject, format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject));
|
||||
} else if psi.some.avg10 >= p.psi_some_shed {
|
||||
ask.raise(Level::Shed, format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed));
|
||||
}
|
||||
// PSI avg10 decays smoothly; stepping down needs it clearly below the limit
|
||||
if psi.full.avg10 >= p.psi_full_reject / 2.0 || psi.some.avg10 >= p.psi_some_shed / 2.0 {
|
||||
ask.hold(Level::Shed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Monitor {
|
||||
/// The level the sample asks for, why, and the level that holds with the margin added to every threshold.
|
||||
pub(super) fn target(&mut self, s: &Sample) -> (Level, String, Level) {
|
||||
let mut ask = Ask::new();
|
||||
match s.available {
|
||||
None => ask.raise(Level::Shed, "available memory unknown (fail closed)".into()),
|
||||
Some(a) => ask_available_known(a, &self.policy, &mut ask),
|
||||
}
|
||||
self.ask_psi(s, &mut ask);
|
||||
self.ask_cgroup(s, &mut ask);
|
||||
self.ask_swapout(s, &mut ask);
|
||||
self.observed.available = s.available;
|
||||
(ask.level, ask.why, ask.relaxed)
|
||||
}
|
||||
|
||||
fn ask_psi(&mut self, s: &Sample, ask: &mut Ask) {
|
||||
self.observed.psi_some_avg10 = s.psi.map(|p| p.some.avg10);
|
||||
self.observed.psi_full_avg10 = s.psi.map(|p| p.full.avg10);
|
||||
// stalls count only while memory is not plentiful (see `Policy::psi_guard_available`); unknown available memory
|
||||
// counts
|
||||
let psi_counts = s.available.is_none_or(|a| a < self.policy.psi_guard_available);
|
||||
if let Some(psi) = s.psi.filter(|_| psi_counts) {
|
||||
ask_psi_levels(psi, &self.policy, ask);
|
||||
}
|
||||
}
|
||||
|
||||
fn ask_cgroup(&mut self, s: &Sample, ask: &mut Ask) {
|
||||
if let (Some(now), Some(before)) = (s.events, self.prev_events) {
|
||||
let d = |a: u64, b: u64| a.saturating_sub(b);
|
||||
let o = &mut self.observed;
|
||||
o.cgroup_high_delta = d(now.high, before.high);
|
||||
o.cgroup_max_delta = d(now.max, before.max);
|
||||
o.cgroup_oom_delta = d(now.oom, before.oom).max(d(now.oom_kill, before.oom_kill));
|
||||
if o.cgroup_oom_delta > 0 {
|
||||
ask.raise(Level::Reject, format!("cgroup oom events +{}", o.cgroup_oom_delta));
|
||||
} else if o.cgroup_max_delta > 0 || o.cgroup_high_delta > 0 {
|
||||
let reason =
|
||||
format!("cgroup memory.high +{} / memory.max +{} events", o.cgroup_high_delta, o.cgroup_max_delta);
|
||||
ask.raise(Level::Shed, reason);
|
||||
}
|
||||
}
|
||||
if s.events.is_some() {
|
||||
self.prev_events = s.events;
|
||||
}
|
||||
}
|
||||
|
||||
/// The system-wide swap-out rate between two samples at least 500 ms apart.
|
||||
fn ask_swapout(&mut self, s: &Sample, ask: &mut Ask) {
|
||||
let Some(out) = s.pswpout else { return };
|
||||
let Some((t0, o0)) = self.prev_swap else {
|
||||
self.prev_swap = Some((s.at_ms, out));
|
||||
return;
|
||||
};
|
||||
let dt = s.at_ms.saturating_sub(t0);
|
||||
if dt < 500 {
|
||||
return;
|
||||
}
|
||||
let limit = self.policy.swapout_pages_per_s_shed;
|
||||
let rate = out.saturating_sub(o0) * 1000 / dt;
|
||||
self.observed.swapout_pages_per_s = Some(rate);
|
||||
if rate >= limit {
|
||||
ask.raise(Level::Shed, format!("swap-out {rate} pages/s (limit {limit})"));
|
||||
}
|
||||
if rate >= limit / 2 {
|
||||
ask.hold(Level::Shed);
|
||||
}
|
||||
self.prev_swap = Some((s.at_ms, out));
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,8 @@ fn psi_stalls_shed_and_reject_independent_of_available_memory() {
|
||||
full: PsiLine { avg10: full, ..Default::default() },
|
||||
})
|
||||
};
|
||||
// above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free changes nothing
|
||||
// above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free
|
||||
// changes nothing
|
||||
assert!(
|
||||
m.update(&Sample { at_ms: 0, available: Some(30 * GIB), psi: psi(60.0, 20.0), ..Sample::default() }).is_none()
|
||||
);
|
||||
|
||||
@@ -38,6 +38,35 @@ pub struct MemInfo {
|
||||
pub hugepage_size: Option<u64>,
|
||||
}
|
||||
|
||||
/// The `/proc/meminfo` keys of [`MemInfo`] and where each one lives.
|
||||
type MemInfoSlot = fn(&mut MemInfo) -> &mut Option<u64>;
|
||||
const MEMINFO_FIELDS: [(&str, MemInfoSlot); 17] = [
|
||||
("MemTotal", |i| &mut i.mem_total),
|
||||
("MemFree", |i| &mut i.mem_free),
|
||||
("MemAvailable", |i| &mut i.mem_available),
|
||||
("Buffers", |i| &mut i.buffers),
|
||||
("Cached", |i| &mut i.cached),
|
||||
("SwapCached", |i| &mut i.swap_cached),
|
||||
("SwapTotal", |i| &mut i.swap_total),
|
||||
("SwapFree", |i| &mut i.swap_free),
|
||||
("Shmem", |i| &mut i.shmem),
|
||||
("Mlocked", |i| &mut i.mlocked),
|
||||
("Unevictable", |i| &mut i.unevictable),
|
||||
("AnonPages", |i| &mut i.anon_pages),
|
||||
("Active(file)", |i| &mut i.active_file),
|
||||
("Inactive(file)", |i| &mut i.inactive_file),
|
||||
("Hugetlb", |i| &mut i.hugetlb),
|
||||
("HugePages_Total", |i| &mut i.hugepages_total),
|
||||
("Hugepagesize", |i| &mut i.hugepage_size),
|
||||
];
|
||||
|
||||
/// The keys the governor decides on: a duplicated or malformed one makes the field unknown.
|
||||
const POISONABLE: [&str; 6] = ["MemTotal", "MemFree", "MemAvailable", "SwapTotal", "SwapFree", "Shmem"];
|
||||
|
||||
fn meminfo_slot<'a>(info: &'a mut MemInfo, key: &str) -> Option<&'a mut Option<u64>> {
|
||||
MEMINFO_FIELDS.iter().find(|(name, _)| *name == key).map(|(_, slot)| slot(info))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -47,47 +76,17 @@ pub fn parse_meminfo(text: &str) -> MemInfo {
|
||||
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) {
|
||||
if fields.next().is_some() || 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;
|
||||
let Some(slot) = meminfo_slot(&mut info, key) else { continue };
|
||||
*slot = if key == "HugePages_Total" { value.parse().ok() } else { kib(value, unit) };
|
||||
}
|
||||
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,
|
||||
_ => {}
|
||||
for key in poisoned.into_iter().filter(|key| POISONABLE.contains(key)) {
|
||||
if let Some(slot) = meminfo_slot(&mut info, key) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
info
|
||||
@@ -111,32 +110,35 @@ pub struct ProcStatus {
|
||||
pub cap_eff: Option<u64>,
|
||||
}
|
||||
|
||||
fn status_slot<'a>(status: &'a mut ProcStatus, key: &str) -> Option<&'a mut Option<u64>> {
|
||||
match key {
|
||||
"VmRSS" => Some(&mut status.vm_rss),
|
||||
"VmHWM" => Some(&mut status.vm_hwm),
|
||||
"VmSwap" => Some(&mut status.vm_swap),
|
||||
"VmLck" => Some(&mut status.vm_lck),
|
||||
"VmPin" => Some(&mut status.vm_pin),
|
||||
"RssAnon" => Some(&mut status.rss_anon),
|
||||
"RssFile" => Some(&mut status.rss_file),
|
||||
"RssShmem" => Some(&mut status.rss_shmem),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
match key {
|
||||
"Threads" => status.threads = value.parse().ok(),
|
||||
"CapEff" => status.cap_eff = u64::from_str_radix(value, 16).ok(),
|
||||
_ => {
|
||||
if let Some(slot) = status_slot(&mut status, key) {
|
||||
*slot = kib(value, unit);
|
||||
}
|
||||
}
|
||||
"CapEff" => {
|
||||
status.cap_eff = u64::from_str_radix(value, 16).ok();
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
*slot = kib(value, unit);
|
||||
}
|
||||
}
|
||||
status
|
||||
}
|
||||
@@ -166,27 +168,37 @@ pub struct Psi {
|
||||
pub full: PsiLine,
|
||||
}
|
||||
|
||||
/// One `key=value` field of a PSI line: `Some(false)` for a key that is not read, `None` for a malformed number.
|
||||
fn psi_field(line: &mut PsiLine, key: &str, value: &str) -> Option<bool> {
|
||||
match key {
|
||||
"avg10" => line.avg10 = value.parse().ok()?,
|
||||
"avg60" => line.avg60 = value.parse().ok()?,
|
||||
"avg300" => line.avg300 = value.parse().ok()?,
|
||||
"total" => line.total_us = value.parse().ok()?,
|
||||
_ => return Some(false),
|
||||
}
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// The fields after `some` / `full`: all four of avg10, avg60, avg300 and total, with finite averages.
|
||||
fn parse_psi_line<'a>(fields: impl Iterator<Item = &'a str>) -> Option<PsiLine> {
|
||||
let mut parsed = PsiLine::default();
|
||||
let mut complete = 0;
|
||||
for field in fields {
|
||||
let (key, value) = field.split_once('=')?;
|
||||
complete += usize::from(psi_field(&mut parsed, key, value)?);
|
||||
}
|
||||
let finite = parsed.avg10.is_finite() && parsed.avg60.is_finite() && parsed.avg300.is_finite();
|
||||
(complete == 4 && finite).then_some(parsed)
|
||||
}
|
||||
|
||||
pub fn parse_psi(text: &str) -> Option<Psi> {
|
||||
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;
|
||||
}
|
||||
let parsed = parse_psi_line(fields)?;
|
||||
match kind {
|
||||
"some" => (psi.some, some) = (parsed, true),
|
||||
"full" => (psi.full, full) = (parsed, true),
|
||||
@@ -272,38 +284,51 @@ pub struct SmapsEntry {
|
||||
pub shmem_pmd_mapped: u64,
|
||||
}
|
||||
|
||||
/// A mapping header line: `start-end perms offset dev inode [path...]`.
|
||||
fn is_smaps_header(line: &str) -> bool {
|
||||
let first = line.split_ascii_whitespace().next().unwrap_or("");
|
||||
first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':')
|
||||
}
|
||||
|
||||
/// The entry a header line opens; `None` for a malformed range.
|
||||
fn parse_smaps_header(line: &str) -> Option<SmapsEntry> {
|
||||
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::<Vec<_>>().join(" ");
|
||||
let (a, b) = range.split_once('-')?;
|
||||
let (Ok(start), Ok(end)) = (u64::from_str_radix(a, 16), u64::from_str_radix(b, 16)) else { return None };
|
||||
Some(SmapsEntry { start, end, perms, path, ..SmapsEntry::default() })
|
||||
}
|
||||
|
||||
/// A `Key: value kB` counter line of the current entry; anything else is skipped.
|
||||
fn apply_smaps_counter(entry: &mut SmapsEntry, line: &str) {
|
||||
let Some((key, rest)) = line.split_once(':') else { return };
|
||||
let mut fields = rest.split_ascii_whitespace();
|
||||
let (Some(value), unit) = (fields.next(), fields.next()) else { return };
|
||||
let Some(bytes) = kib(value, unit) else { return };
|
||||
match key {
|
||||
"Size" => entry.size = bytes,
|
||||
"Rss" => entry.rss = bytes,
|
||||
"Swap" => entry.swap = bytes,
|
||||
"Locked" => entry.locked = bytes,
|
||||
"ShmemPmdMapped" => entry.shmem_pmd_mapped = bytes,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `/proc/self/smaps`. A malformed header or counter line stops the entry (never fabricates numbers).
|
||||
pub fn parse_smaps(text: &str) -> Vec<SmapsEntry> {
|
||||
let mut entries: Vec<SmapsEntry> = 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::<Vec<_>>().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() });
|
||||
if is_smaps_header(line) {
|
||||
entries.extend(parse_smaps_header(line));
|
||||
} 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,
|
||||
_ => {}
|
||||
}
|
||||
apply_smaps_counter(entry, line);
|
||||
}
|
||||
}
|
||||
entries
|
||||
|
||||
@@ -27,7 +27,8 @@ pub const RUN_LIMIT: Duration = Duration::from_secs(5);
|
||||
const EXTRA_LOCATIONS: [&str; 3] =
|
||||
["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"];
|
||||
|
||||
/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and anything else.
|
||||
/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and
|
||||
/// anything else.
|
||||
fn number(field: &str) -> Option<f64> {
|
||||
let field = field.trim();
|
||||
if field.is_empty() || field.starts_with('[') || field.eq_ignore_ascii_case("n/a") {
|
||||
@@ -77,10 +78,9 @@ pub fn find_binary() -> Option<std::path::PathBuf> {
|
||||
from_path.or_else(|| EXTRA_LOCATIONS.iter().map(std::path::PathBuf::from).find(|candidate| candidate.is_file()))
|
||||
}
|
||||
|
||||
/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed out or
|
||||
/// printed something unusable.
|
||||
pub fn query(binary: &std::path::Path, index: u32) -> Option<GpuSample> {
|
||||
let mut child = Command::new(binary)
|
||||
/// Start `nvidia-smi` for [`QUERY`] on device `index`, its standard output piped.
|
||||
fn spawn_query(binary: &std::path::Path, index: u32) -> Option<std::process::Child> {
|
||||
Command::new(binary)
|
||||
.arg(format!("--query-gpu={QUERY}"))
|
||||
.arg("--format=csv,noheader,nounits")
|
||||
.arg("-i")
|
||||
@@ -89,7 +89,13 @@ pub fn query(binary: &std::path::Path, index: u32) -> Option<GpuSample> {
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed
|
||||
/// out or printed something unusable.
|
||||
pub fn query(binary: &std::path::Path, index: u32) -> Option<GpuSample> {
|
||||
let mut child = spawn_query(binary, index)?;
|
||||
let mut stdout = child.stdout.take()?;
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
@@ -159,7 +165,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn output_captured_from_real_drivers_parses() {
|
||||
// `nvidia-smi --query-gpu=<QUERY> --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02, Linux)
|
||||
// `nvidia-smi --query-gpu=<QUERY> --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02,
|
||||
// Linux)
|
||||
let server = parse_csv("0, 94, 21, 31606, 32607, 271.40, 2887, 58, NVIDIA GeForce RTX 5090\n", 0).unwrap();
|
||||
assert_eq!((server.util_pct, server.vram_used_mib, server.vram_total_mib), (94, 31606, 32607));
|
||||
assert_eq!((server.power_w, server.sm_clock_mhz, server.temp_c), (Some(271.4), Some(2887), Some(58)));
|
||||
|
||||
@@ -89,7 +89,8 @@ struct State {
|
||||
decode_ema: Option<f64>,
|
||||
context_live: u64,
|
||||
context_max: u64,
|
||||
/// Non-finite verify windows (upstream's NaN guard): retried from the round's checkpoint and then fine, or given up on.
|
||||
/// Non-finite verify windows (upstream's NaN guard): retried from the round's checkpoint and then fine, or given up
|
||||
/// on.
|
||||
nan_healed: u64,
|
||||
nan_unhealed: u64,
|
||||
nan_last: Option<String>,
|
||||
@@ -97,7 +98,8 @@ struct State {
|
||||
spec_rounds: u64,
|
||||
spec_tokens: u64,
|
||||
last_request: Option<LastRequest>,
|
||||
/// The expert tier's counters as of the last finished request (lifetime of the stack, so a delta is a request's share).
|
||||
/// The expert tier's counters as of the last finished request (lifetime of the stack, so a delta is a request's
|
||||
/// share).
|
||||
expert_tier: Option<TierCounters>,
|
||||
}
|
||||
|
||||
@@ -215,7 +217,8 @@ struct LiveRequest {
|
||||
elapsed_s: f64,
|
||||
}
|
||||
|
||||
/// Speculative decode as the operator reads it: committed tokens per verified round (1.0 would be no gain from drafting).
|
||||
/// Speculative decode as the operator reads it: committed tokens per verified round (1.0 would be no gain from
|
||||
/// drafting).
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Spec {
|
||||
rounds: u64,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: fn lock, fn with_state, fn published_telemetry, fn set_settings, fn set_context_max, fn request_started ....
|
||||
//! Moved out of the parent module by STRA-338: fn lock, fn with_state, fn published_telemetry, fn set_settings, fn
|
||||
//! set_context_max, fn request_started ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -16,7 +17,8 @@ pub fn published_telemetry() -> Option<String> {
|
||||
lock(&PUBLISHED).clone()
|
||||
}
|
||||
|
||||
/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the document.
|
||||
/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the
|
||||
/// document.
|
||||
pub fn set_settings(settings: serde_json::Value) {
|
||||
*lock(&SETTINGS) = Some(settings);
|
||||
}
|
||||
@@ -26,7 +28,8 @@ pub fn set_context_max(tokens: u64) {
|
||||
with_state(|s| s.context_max = tokens);
|
||||
}
|
||||
|
||||
/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the figures of the last finished request stay until then).
|
||||
/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the
|
||||
/// figures of the last finished request stay until then).
|
||||
pub fn request_started(prompt_tokens: u64) {
|
||||
request_started_at(prompt_tokens, SystemClock.now());
|
||||
}
|
||||
@@ -60,8 +63,9 @@ pub fn tokens_delivered_at(count: u64, at: Instant) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the retry was good.
|
||||
/// `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in the document.
|
||||
/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the
|
||||
/// retry was good. `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in
|
||||
/// the document.
|
||||
pub fn nan_guard_healed(what: &str) {
|
||||
with_state(|s| {
|
||||
s.nan_healed += 1;
|
||||
@@ -69,7 +73,8 @@ pub fn nan_guard_healed(what: &str) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request fails as before.
|
||||
/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request
|
||||
/// fails as before.
|
||||
pub fn nan_guard_unhealed(what: &str) {
|
||||
with_state(|s| {
|
||||
s.nan_unhealed += 1;
|
||||
@@ -86,6 +91,30 @@ pub fn request_aborted() {
|
||||
});
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Fold the prompt tokens this request really prefilled (not the reused ones) into the prefill rates.
|
||||
fn fold_prefill(&mut self, prefilled: u64, prompt_ms: f64) {
|
||||
if prefilled > 0 && prompt_ms > 0.0 {
|
||||
let rate = prefilled as f64 * 1e3 / prompt_ms;
|
||||
self.prefill_tokens += prefilled;
|
||||
self.prefill_ms += prompt_ms;
|
||||
self.last_prefill_tok_s = Some(rate);
|
||||
self.prefill_ema = Some(ema(self.prefill_ema, rate));
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold the tokens this request decoded into the decode rates.
|
||||
fn fold_decode(&mut self, produced: u64, decode_ms: f64) {
|
||||
if produced > 0 && decode_ms > 0.0 {
|
||||
let rate = produced as f64 * 1e3 / decode_ms;
|
||||
self.decode_tokens += produced;
|
||||
self.decode_ms += decode_ms;
|
||||
self.last_decode_tok_s = Some(rate);
|
||||
self.decode_ema = Some(ema(self.decode_ema, rate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A request finished (any outcome that produced numbers): fold it into the lifetime figures.
|
||||
pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) {
|
||||
with_state(|s| {
|
||||
@@ -105,21 +134,8 @@ pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, p
|
||||
s.last_prefill_ms = prompt_ms;
|
||||
s.last_decode_ms = decode_ms;
|
||||
s.context_live = prompt_tokens + produced;
|
||||
let prefilled = prompt_tokens.saturating_sub(reused_tokens);
|
||||
if prefilled > 0 && prompt_ms > 0.0 {
|
||||
let rate = prefilled as f64 * 1e3 / prompt_ms;
|
||||
s.prefill_tokens += prefilled;
|
||||
s.prefill_ms += prompt_ms;
|
||||
s.last_prefill_tok_s = Some(rate);
|
||||
s.prefill_ema = Some(ema(s.prefill_ema, rate));
|
||||
}
|
||||
if produced > 0 && decode_ms > 0.0 {
|
||||
let rate = produced as f64 * 1e3 / decode_ms;
|
||||
s.decode_tokens += produced;
|
||||
s.decode_ms += decode_ms;
|
||||
s.last_decode_tok_s = Some(rate);
|
||||
s.decode_ema = Some(ema(s.decode_ema, rate));
|
||||
}
|
||||
s.fold_prefill(prompt_tokens.saturating_sub(reused_tokens), prompt_ms);
|
||||
s.fold_decode(produced, decode_ms);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -146,8 +162,9 @@ pub fn request_detail(request_id: &str, rounds: u64, tier: Option<TierCounters>)
|
||||
});
|
||||
}
|
||||
|
||||
/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the counters are
|
||||
/// the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, when they went back).
|
||||
/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the
|
||||
/// counters are the stack's lifetime, so it is the difference to the previous request (or all of them after a reload,
|
||||
/// when they went back).
|
||||
pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, f64, f64) {
|
||||
let base = previous.filter(|p| {
|
||||
now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries
|
||||
@@ -163,8 +180,8 @@ pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64,
|
||||
(pct(v), pct(p), pct(c))
|
||||
}
|
||||
|
||||
/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request so that
|
||||
/// `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable.
|
||||
/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request
|
||||
/// so that `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable.
|
||||
pub fn request_line_fields<'a>(r: &RequestLine<'a>) -> Vec<leleka_obs::Field<'a>> {
|
||||
use leleka_obs::V;
|
||||
let fresh = r.input_tokens.saturating_sub(r.reused_tokens);
|
||||
|
||||
@@ -3,82 +3,114 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn render(state: &State, measured: &Measured) -> String {
|
||||
fn ram_of(measured: &Measured) -> Option<Ram> {
|
||||
let mib = |bytes: Option<u64>| bytes.map_or(0, |b| b >> 20);
|
||||
let ram = measured.meminfo.mem_total.map(|total| Ram {
|
||||
measured.meminfo.mem_total.map(|total| Ram {
|
||||
total_mib: total >> 20,
|
||||
available_mib: mib(measured.meminfo.mem_available),
|
||||
process_rss_mib: mib(measured.status.vm_rss),
|
||||
process_pinned_mib: mib(measured.status.vm_pin),
|
||||
swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0))
|
||||
>> 20,
|
||||
});
|
||||
let live_rate = match (state.phase, state.first_token) {
|
||||
})
|
||||
}
|
||||
|
||||
/// The decode rate of the request in flight, once it has produced more than a token over more than 50 ms.
|
||||
fn live_rate_of(state: &State, measured: &Measured) -> Option<f64> {
|
||||
match (state.phase, state.first_token) {
|
||||
(Phase::Decode, Some(first)) if state.produced_now > 1 => {
|
||||
let secs = measured.at.saturating_duration_since(first).as_secs_f64();
|
||||
(secs > 0.05).then(|| round1(state.produced_now as f64 / secs))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn live_request_of(state: &State, measured: &Measured) -> Option<LiveRequest> {
|
||||
state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest {
|
||||
prompt_tokens: state.prompt_now,
|
||||
generated_tokens: state.produced_now,
|
||||
elapsed_s: (measured.at.saturating_duration_since(started).as_secs_f64() * 10.0).round() / 10.0,
|
||||
})
|
||||
}
|
||||
|
||||
fn rates_of(state: &State, live_rate: Option<f64>) -> Rates {
|
||||
Rates {
|
||||
prefill_tok_s_last: state.last_prefill_tok_s.map(round1),
|
||||
prefill_tok_s_avg: state.prefill_ema.map(round1),
|
||||
prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms),
|
||||
decode_tok_s_last: state.last_decode_tok_s.map(round1),
|
||||
decode_tok_s_avg: state.decode_ema.map(round1),
|
||||
decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms),
|
||||
decode_tok_s_live: live_rate,
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_of(state: &State) -> Cache {
|
||||
Cache {
|
||||
requests: state.requests,
|
||||
hit_requests: state.cache_hit_requests,
|
||||
hit_ratio: ratio(state.cache_hit_requests, state.requests),
|
||||
prompt_tokens: state.prompt_tokens,
|
||||
reused_tokens: state.reused_tokens,
|
||||
token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens),
|
||||
last_prompt_tokens: state.last_prompt_tokens,
|
||||
last_reused_tokens: state.last_reused_tokens,
|
||||
}
|
||||
}
|
||||
|
||||
fn spec_of(state: &State) -> Spec {
|
||||
Spec {
|
||||
rounds: state.spec_rounds,
|
||||
tokens: state.spec_tokens,
|
||||
tokens_per_round: (state.spec_rounds > 0)
|
||||
.then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn tier_of(state: &State) -> Option<Tier> {
|
||||
state.expert_tier.map(|counters| Tier {
|
||||
counters,
|
||||
vram_ratio: ratio(counters.vram_entries, counters.vram_entries + counters.pcie_entries + counters.cpu_entries),
|
||||
})
|
||||
}
|
||||
|
||||
fn cpu_of(measured: &Measured) -> Option<Cpu> {
|
||||
measured.cpu.map(|(process, system)| Cpu {
|
||||
cores: measured.cores,
|
||||
process_busy_cores: round1(process),
|
||||
system_busy_pct: round1(system),
|
||||
})
|
||||
}
|
||||
|
||||
fn context_of(state: &State) -> Context {
|
||||
Context {
|
||||
live_tokens: state.context_live,
|
||||
max_tokens: state.context_max,
|
||||
used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2),
|
||||
}
|
||||
}
|
||||
|
||||
fn nan_guard_of(state: &State) -> NanGuard {
|
||||
NanGuard { healed_windows: state.nan_healed, unhealed_windows: state.nan_unhealed, last: state.nan_last.clone() }
|
||||
}
|
||||
|
||||
pub(super) fn render(state: &State, measured: &Measured) -> String {
|
||||
let document = Document {
|
||||
version: 1,
|
||||
ts_ms: measured.now_ms,
|
||||
uptime_s: measured.uptime_s,
|
||||
phase: state.phase,
|
||||
request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest {
|
||||
prompt_tokens: state.prompt_now,
|
||||
generated_tokens: state.produced_now,
|
||||
elapsed_s: (measured.at.saturating_duration_since(started).as_secs_f64() * 10.0).round() / 10.0,
|
||||
}),
|
||||
request: live_request_of(state, measured),
|
||||
gpu: measured.gpu.clone(),
|
||||
ram,
|
||||
cpu: measured.cpu.map(|(process, system)| Cpu {
|
||||
cores: measured.cores,
|
||||
process_busy_cores: round1(process),
|
||||
system_busy_pct: round1(system),
|
||||
}),
|
||||
throughput: Rates {
|
||||
prefill_tok_s_last: state.last_prefill_tok_s.map(round1),
|
||||
prefill_tok_s_avg: state.prefill_ema.map(round1),
|
||||
prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms),
|
||||
decode_tok_s_last: state.last_decode_tok_s.map(round1),
|
||||
decode_tok_s_avg: state.decode_ema.map(round1),
|
||||
decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms),
|
||||
decode_tok_s_live: live_rate,
|
||||
},
|
||||
cache: Cache {
|
||||
requests: state.requests,
|
||||
hit_requests: state.cache_hit_requests,
|
||||
hit_ratio: ratio(state.cache_hit_requests, state.requests),
|
||||
prompt_tokens: state.prompt_tokens,
|
||||
reused_tokens: state.reused_tokens,
|
||||
token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens),
|
||||
last_prompt_tokens: state.last_prompt_tokens,
|
||||
last_reused_tokens: state.last_reused_tokens,
|
||||
},
|
||||
context: Context {
|
||||
live_tokens: state.context_live,
|
||||
max_tokens: state.context_max,
|
||||
used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2),
|
||||
},
|
||||
nan_guard: NanGuard {
|
||||
healed_windows: state.nan_healed,
|
||||
unhealed_windows: state.nan_unhealed,
|
||||
last: state.nan_last.clone(),
|
||||
},
|
||||
spec: Spec {
|
||||
rounds: state.spec_rounds,
|
||||
tokens: state.spec_tokens,
|
||||
tokens_per_round: (state.spec_rounds > 0)
|
||||
.then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0),
|
||||
},
|
||||
expert_tier: state.expert_tier.map(|counters| Tier {
|
||||
counters,
|
||||
vram_ratio: ratio(
|
||||
counters.vram_entries,
|
||||
counters.vram_entries + counters.pcie_entries + counters.cpu_entries,
|
||||
),
|
||||
}),
|
||||
ram: ram_of(measured),
|
||||
cpu: cpu_of(measured),
|
||||
throughput: rates_of(state, live_rate_of(state, measured)),
|
||||
cache: cache_of(state),
|
||||
context: context_of(state),
|
||||
nan_guard: nan_guard_of(state),
|
||||
spec: spec_of(state),
|
||||
expert_tier: tier_of(state),
|
||||
last_request: state.last_request.clone(),
|
||||
settings: lock(&SETTINGS).clone(),
|
||||
};
|
||||
@@ -106,7 +138,8 @@ impl Drop for Sampler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block.
|
||||
/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU
|
||||
/// block.
|
||||
pub fn start(gpu_probe: Option<GpuProbe>, period: Duration) -> Sampler {
|
||||
start_with_clock(gpu_probe, period, SystemClock)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,11 @@ pub fn meminfo_text(m: &SystemMemory) -> String {
|
||||
m.total_commit.saturating_sub(m.avail_commit).saturating_sub(m.total_phys.saturating_sub(m.avail_phys));
|
||||
let swap_free = swap_total.saturating_sub(swap_used);
|
||||
format!(
|
||||
"MemTotal: {} kB\nMemFree: {} kB\nMemAvailable: {} kB\nSwapTotal: {} kB\nSwapFree: {} kB\n",
|
||||
"MemTotal: {} kB\n\
|
||||
MemFree: {} kB\n\
|
||||
MemAvailable: {} kB\n\
|
||||
SwapTotal: {} kB\n\
|
||||
SwapFree: {} kB\n",
|
||||
kb(m.total_phys),
|
||||
kb(m.avail_phys),
|
||||
kb(m.avail_phys),
|
||||
@@ -67,10 +71,15 @@ pub fn status_text(p: &ProcessMemory) -> String {
|
||||
/// `/proc/self/limits`: Windows has no `RLIMIT_MEMLOCK`; `VirtualLock` is bounded by the working-set quota and reports
|
||||
/// its own failure, so the limit is reported unlimited (the lock plan then attempts and the attempt decides).
|
||||
pub fn limits_text() -> String {
|
||||
"Limit Soft Limit Hard Limit Units\nMax locked memory unlimited unlimited bytes\n".to_owned()
|
||||
concat!(
|
||||
"Limit Soft Limit Hard Limit Units\n",
|
||||
"Max locked memory unlimited unlimited bytes\n"
|
||||
)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// `/proc/self/stat` with only the fields the CPU telemetry reads: `utime` and `stime` (fields 14 and 15) in 10 ms ticks.
|
||||
/// `/proc/self/stat` with only the fields the CPU telemetry reads: `utime` and `stime` (fields 14 and 15) in 10 ms
|
||||
/// ticks.
|
||||
pub fn self_stat_text(user_ticks: u64, kernel_ticks: u64) -> String {
|
||||
format!("1 (leleka) R 0 0 0 0 0 0 0 0 0 0 {user_ticks} {kernel_ticks} 0 0 20 0 1 0 0\n")
|
||||
}
|
||||
@@ -99,8 +108,9 @@ pub fn read(path: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Trim this process's working set (Windows only; `false` elsewhere or on failure). Windows counts the mapped pages a process still has in its
|
||||
/// working set as in use, so a file-mapped expert bank that was touched looks like pressure to the governor although the OS could reclaim it.
|
||||
/// Trim this process's working set (Windows only; `false` elsewhere or on failure). Windows counts the mapped pages a
|
||||
/// process still has in its working set as in use, so a file-mapped expert bank that was touched looks like pressure to
|
||||
/// the governor although the OS could reclaim it.
|
||||
pub fn trim_working_set() -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
@@ -168,8 +178,8 @@ mod win32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its working set to the
|
||||
/// standby list: they stay cached, count as available again and come back with a soft fault.
|
||||
/// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its
|
||||
/// working set to the standby list: they stay cached, count as available again and come back with a soft fault.
|
||||
pub fn trim_working_set() -> bool {
|
||||
// SAFETY: the pseudo handle of the current process is always valid.
|
||||
unsafe { EmptyWorkingSet(GetCurrentProcess()) != 0 }
|
||||
|
||||
@@ -120,12 +120,6 @@
|
||||
"fn_lines": 2,
|
||||
"complexity": 2
|
||||
},
|
||||
"leleka-memory": {
|
||||
"fn_lines": 24,
|
||||
"width": 97,
|
||||
"complexity": 11,
|
||||
"nesting": 1
|
||||
},
|
||||
"leleka-model-format": {
|
||||
"fn_lines": 69,
|
||||
"complexity": 63,
|
||||
@@ -308,7 +302,7 @@
|
||||
"fn_lines": 5,
|
||||
"complexity": 1,
|
||||
"nesting": 1,
|
||||
"width": 21
|
||||
"width": 13
|
||||
},
|
||||
"leleka-model-format": {
|
||||
"fn_lines": 71,
|
||||
|
||||
Reference in New Issue
Block a user