nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! CPU utilization from `/proc/stat`: the mean, the hottest core and
//! the per-core quartiles (SRD-118 §3.1).

/// Per-category CPU readings: the mean, the hottest core, and the
/// SHAPE of the per-core distribution.
///
/// The hottest core alone cannot answer "is there headroom": one
/// pegged core on an otherwise idle box reads identically to a box
/// that is genuinely out of CPU. Measured 2026-08-21 on a live
/// `stcs_adaptive` run — `max_core` p90 = 1.000 while `mean` sat at
/// 0.183 — so any guard keyed on the max would throttle at 18% host
/// utilization. The quartiles separate the two cases: `p50` low with
/// `max_core` pegged is a single hot thread (headroom remains); `p50`
/// high is real saturation.
///
/// `max_core` is kept, not replaced — it remains the right signal for
/// spotting a single-threaded bottleneck, which is a different
/// question from headroom.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CpuReading {
    pub mean: f64,
    pub max_core: f64,
    pub top_core: usize,
    /// Per-core utilization quartiles across all online cores.
    pub p25: f64,
    pub p50: f64,
    pub p75: f64,
    /// How many cores the quartiles were computed over — the sample
    /// size behind the shape, so a reader can tell a 2-core box's
    /// "quartiles" from a 96-core box's.
    pub cores: usize,
}

/// Cumulative jiffy counts for one `cpu` line: (busy, total).
///
/// total = user+nice+system+idle+iowait+irq+softirq+steal (the first eight
/// fields; guest time is already accounted inside user/nice). busy = total −
/// idle − iowait: iowait is idle-with-an-excuse, and counting it as busy
/// would read an I/O-bound stall as CPU saturation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CpuTicks {
    pub busy: u64,
    pub total: u64,
}

/// Aggregate + per-core cumulative ticks from `/proc/stat`.
pub fn parse_proc_stat(text: &str) -> Option<(CpuTicks, Vec<CpuTicks>)> {
    let mut aggregate: Option<CpuTicks> = None;
    let mut cores: Vec<(usize, CpuTicks)> = Vec::new();
    for line in text.lines() {
        let mut t = line.split_whitespace();
        let Some(name) = t.next() else { continue };
        if !name.starts_with("cpu") {
            continue;
        }
        let fields: Vec<u64> = t.filter_map(|f| f.parse().ok()).collect();
        if fields.len() < 8 {
            continue;
        }
        let total: u64 = fields[..8].iter().sum();
        let idle = fields[3] + fields[4];
        let ticks = CpuTicks {
            busy: total - idle,
            total,
        };
        if name == "cpu" {
            aggregate = Some(ticks);
        } else if let Ok(n) = name[3..].parse::<usize>() {
            cores.push((n, ticks));
        }
    }
    cores.sort_by_key(|(n, _)| *n);
    aggregate.map(|a| (a, cores.into_iter().map(|(_, t)| t).collect()))
}

/// Utilization between two tick snapshots: Δbusy / Δtotal.
pub fn cpu_util(prev: CpuTicks, cur: CpuTicks) -> f64 {
    let dt = cur.total.saturating_sub(prev.total);
    if dt == 0 {
        return 0.0;
    }
    (cur.busy.saturating_sub(prev.busy) as f64 / dt as f64).clamp(0.0, 1.0)
}

/// The most saturated core between two snapshots. Core lists of different
/// lengths (offline/online between samples) compare over the shared prefix.
pub fn max_core_util(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(usize, f64)> {
    prev.iter()
        .zip(cur.iter())
        .enumerate()
        .map(|(i, (p, c))| (i, cpu_util(*p, *c)))
        .max_by(|a, b| a.1.total_cmp(&b.1))
}

/// Per-core utilization quartiles between two snapshots: `(p25, p50,
/// p75, cores)`. Same shared-prefix rule as [`max_core_util`].
///
/// The per-core vector is already built to find the max; the quartiles
/// are a sort of that same vector, so the shape costs one sort per
/// sample window and no extra reads of `/proc/stat`.
///
/// Nearest-rank on the sorted ascending vector (no interpolation): the
/// quantile of a core count is a real core's utilization, which is the
/// honest reading when the population is small — an interpolated "p75"
/// across 4 cores would name a utilization no core actually had.
pub fn core_util_quartiles(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(f64, f64, f64, usize)> {
    let mut utils: Vec<f64> = prev
        .iter()
        .zip(cur.iter())
        .map(|(p, c)| cpu_util(*p, *c))
        .collect();
    if utils.is_empty() {
        return None;
    }
    utils.sort_by(f64::total_cmp);
    let n = utils.len();
    let at = |q: f64| -> f64 {
        // Nearest-rank, clamped: ceil(q*n) - 1 over 1-based ranks.
        let rank = (q * n as f64).ceil().max(1.0) as usize;
        utils[rank.min(n) - 1]
    };
    Some((at(0.25), at(0.50), at(0.75), n))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Mean and max-core are separate measures: one saturated core among
    /// idle ones must not disappear into the mean.
    #[test]
    fn one_hot_core_shows_in_max_not_mean() {
        let stat_t0 = "\
cpu  1000 0 0 8000 0 0 0 0 0 0
cpu0 1000 0 0 0 0 0 0 0 0 0
cpu1 0 0 0 4000 0 0 0 0 0 0
cpu2 0 0 0 4000 0 0 0 0 0 0";
        let stat_t1 = "\
cpu  2000 0 0 16000 0 0 0 0 0 0
cpu0 2000 0 0 0 0 0 0 0 0 0
cpu1 0 0 0 8000 0 0 0 0 0 0
cpu2 0 0 0 8000 0 0 0 0 0 0";
        let (a0, c0) = parse_proc_stat(stat_t0).unwrap();
        let (a1, c1) = parse_proc_stat(stat_t1).unwrap();
        let mean = cpu_util(a0, a1);
        let (core, max) = max_core_util(&c0, &c1).unwrap();
        assert!((mean - 1000.0 / 9000.0).abs() < 1e-9, "mean {mean}");
        assert_eq!(core, 0);
        assert!((max - 1.0).abs() < 1e-9, "core0 fully busy, got {max}");

        // The quartiles are what separate THIS box — one pegged core, two
        // idle — from a box where every core is genuinely busy. Both read
        // max_core = 1.0; only the median tells them apart.
        let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
        assert_eq!(cores, 3);
        assert!((p25 - 0.0).abs() < 1e-9, "p25 {p25}");
        assert!((p50 - 0.0).abs() < 1e-9, "median core is IDLE, got {p50}");
        assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
    }

    /// The saturation case the quartiles must NOT confuse with one hot
    /// core: every core busy reads max_core = 1.0 just like a single
    /// pegged core, but the median moves with it.
    #[test]
    fn quartiles_separate_broad_saturation_from_one_hot_core() {
        let stat_t0 = "\
cpu  0 0 0 12000 0 0 0 0 0 0
cpu0 0 0 0 4000 0 0 0 0 0 0
cpu1 0 0 0 4000 0 0 0 0 0 0
cpu2 0 0 0 4000 0 0 0 0 0 0";
        let stat_t1 = "\
cpu  12000 0 0 12000 0 0 0 0 0 0
cpu0 4000 0 0 4000 0 0 0 0 0 0
cpu1 4000 0 0 4000 0 0 0 0 0 0
cpu2 4000 0 0 4000 0 0 0 0 0 0";
        let (_, c0) = parse_proc_stat(stat_t0).unwrap();
        let (_, c1) = parse_proc_stat(stat_t1).unwrap();
        let (_, max) = max_core_util(&c0, &c1).unwrap();
        let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
        assert_eq!(cores, 3);
        // EXACTLY the max the one-hot-core case reports — 1.0 there, 1.0
        // here. On the max alone the two boxes are indistinguishable.
        assert!((max - 1.0).abs() < 1e-9, "max {max}");
        // The median is what tells them apart: 0.0 when one core is hot
        // and the rest idle, 1.0 when the whole box is saturated.
        assert!((p25 - 1.0).abs() < 1e-9, "p25 {p25}");
        assert!((p50 - 1.0).abs() < 1e-9, "p50 {p50}");
        assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
    }

    /// Nearest-rank, not interpolation: every quartile of a small core
    /// count must be a utilization some real core actually had.
    #[test]
    fn quartiles_are_nearest_rank_over_real_cores() {
        let single = vec![CpuTicks {
            busy: 0,
            total: 1000,
        }];
        let single_end = vec![CpuTicks {
            busy: 250,
            total: 2000,
        }];
        let (p25, p50, p75, cores) = core_util_quartiles(&single, &single_end).unwrap();
        assert_eq!(cores, 1);
        // One core: every quantile is that core.
        assert!((p25 - 0.25).abs() < 1e-9);
        assert!((p50 - 0.25).abs() < 1e-9);
        assert!((p75 - 0.25).abs() < 1e-9);
        // No cores at all is None, not a fabricated zero.
        assert!(core_util_quartiles(&[], &[]).is_none());
    }

    /// iowait is idle-with-an-excuse: an I/O-bound stall must not read as
    /// CPU saturation.
    #[test]
    fn iowait_does_not_count_as_busy() {
        let t0 = parse_proc_stat("cpu 0 0 0 0 0 0 0 0 0 0").unwrap().0;
        let t1 = parse_proc_stat("cpu 0 0 0 500 500 0 0 0 0 0").unwrap().0;
        assert_eq!(cpu_util(t0, t1), 0.0);
    }
}