Skip to main content

nmbrs_runtime/sysmon/
cpu.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! CPU utilization from `/proc/stat`: the mean, the hottest core and
5//! the per-core quartiles (SRD-118 §3.1).
6
7/// Per-category CPU readings: the mean, the hottest core, and the
8/// SHAPE of the per-core distribution.
9///
10/// The hottest core alone cannot answer "is there headroom": one
11/// pegged core on an otherwise idle box reads identically to a box
12/// that is genuinely out of CPU. Measured 2026-08-21 on a live
13/// `stcs_adaptive` run — `max_core` p90 = 1.000 while `mean` sat at
14/// 0.183 — so any guard keyed on the max would throttle at 18% host
15/// utilization. The quartiles separate the two cases: `p50` low with
16/// `max_core` pegged is a single hot thread (headroom remains); `p50`
17/// high is real saturation.
18///
19/// `max_core` is kept, not replaced — it remains the right signal for
20/// spotting a single-threaded bottleneck, which is a different
21/// question from headroom.
22#[derive(Debug, Clone, Copy, PartialEq, Default)]
23pub struct CpuReading {
24    pub mean: f64,
25    pub max_core: f64,
26    pub top_core: usize,
27    /// Per-core utilization quartiles across all online cores.
28    pub p25: f64,
29    pub p50: f64,
30    pub p75: f64,
31    /// How many cores the quartiles were computed over — the sample
32    /// size behind the shape, so a reader can tell a 2-core box's
33    /// "quartiles" from a 96-core box's.
34    pub cores: usize,
35}
36
37/// Cumulative jiffy counts for one `cpu` line: (busy, total).
38///
39/// total = user+nice+system+idle+iowait+irq+softirq+steal (the first eight
40/// fields; guest time is already accounted inside user/nice). busy = total −
41/// idle − iowait: iowait is idle-with-an-excuse, and counting it as busy
42/// would read an I/O-bound stall as CPU saturation.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct CpuTicks {
45    pub busy: u64,
46    pub total: u64,
47}
48
49/// Aggregate + per-core cumulative ticks from `/proc/stat`.
50pub fn parse_proc_stat(text: &str) -> Option<(CpuTicks, Vec<CpuTicks>)> {
51    let mut aggregate: Option<CpuTicks> = None;
52    let mut cores: Vec<(usize, CpuTicks)> = Vec::new();
53    for line in text.lines() {
54        let mut t = line.split_whitespace();
55        let Some(name) = t.next() else { continue };
56        if !name.starts_with("cpu") {
57            continue;
58        }
59        let fields: Vec<u64> = t.filter_map(|f| f.parse().ok()).collect();
60        if fields.len() < 8 {
61            continue;
62        }
63        let total: u64 = fields[..8].iter().sum();
64        let idle = fields[3] + fields[4];
65        let ticks = CpuTicks {
66            busy: total - idle,
67            total,
68        };
69        if name == "cpu" {
70            aggregate = Some(ticks);
71        } else if let Ok(n) = name[3..].parse::<usize>() {
72            cores.push((n, ticks));
73        }
74    }
75    cores.sort_by_key(|(n, _)| *n);
76    aggregate.map(|a| (a, cores.into_iter().map(|(_, t)| t).collect()))
77}
78
79/// Utilization between two tick snapshots: Δbusy / Δtotal.
80pub fn cpu_util(prev: CpuTicks, cur: CpuTicks) -> f64 {
81    let dt = cur.total.saturating_sub(prev.total);
82    if dt == 0 {
83        return 0.0;
84    }
85    (cur.busy.saturating_sub(prev.busy) as f64 / dt as f64).clamp(0.0, 1.0)
86}
87
88/// The most saturated core between two snapshots. Core lists of different
89/// lengths (offline/online between samples) compare over the shared prefix.
90pub fn max_core_util(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(usize, f64)> {
91    prev.iter()
92        .zip(cur.iter())
93        .enumerate()
94        .map(|(i, (p, c))| (i, cpu_util(*p, *c)))
95        .max_by(|a, b| a.1.total_cmp(&b.1))
96}
97
98/// Per-core utilization quartiles between two snapshots: `(p25, p50,
99/// p75, cores)`. Same shared-prefix rule as [`max_core_util`].
100///
101/// The per-core vector is already built to find the max; the quartiles
102/// are a sort of that same vector, so the shape costs one sort per
103/// sample window and no extra reads of `/proc/stat`.
104///
105/// Nearest-rank on the sorted ascending vector (no interpolation): the
106/// quantile of a core count is a real core's utilization, which is the
107/// honest reading when the population is small — an interpolated "p75"
108/// across 4 cores would name a utilization no core actually had.
109pub fn core_util_quartiles(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(f64, f64, f64, usize)> {
110    let mut utils: Vec<f64> = prev
111        .iter()
112        .zip(cur.iter())
113        .map(|(p, c)| cpu_util(*p, *c))
114        .collect();
115    if utils.is_empty() {
116        return None;
117    }
118    utils.sort_by(f64::total_cmp);
119    let n = utils.len();
120    let at = |q: f64| -> f64 {
121        // Nearest-rank, clamped: ceil(q*n) - 1 over 1-based ranks.
122        let rank = (q * n as f64).ceil().max(1.0) as usize;
123        utils[rank.min(n) - 1]
124    };
125    Some((at(0.25), at(0.50), at(0.75), n))
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    /// Mean and max-core are separate measures: one saturated core among
133    /// idle ones must not disappear into the mean.
134    #[test]
135    fn one_hot_core_shows_in_max_not_mean() {
136        let stat_t0 = "\
137cpu  1000 0 0 8000 0 0 0 0 0 0
138cpu0 1000 0 0 0 0 0 0 0 0 0
139cpu1 0 0 0 4000 0 0 0 0 0 0
140cpu2 0 0 0 4000 0 0 0 0 0 0";
141        let stat_t1 = "\
142cpu  2000 0 0 16000 0 0 0 0 0 0
143cpu0 2000 0 0 0 0 0 0 0 0 0
144cpu1 0 0 0 8000 0 0 0 0 0 0
145cpu2 0 0 0 8000 0 0 0 0 0 0";
146        let (a0, c0) = parse_proc_stat(stat_t0).unwrap();
147        let (a1, c1) = parse_proc_stat(stat_t1).unwrap();
148        let mean = cpu_util(a0, a1);
149        let (core, max) = max_core_util(&c0, &c1).unwrap();
150        assert!((mean - 1000.0 / 9000.0).abs() < 1e-9, "mean {mean}");
151        assert_eq!(core, 0);
152        assert!((max - 1.0).abs() < 1e-9, "core0 fully busy, got {max}");
153
154        // The quartiles are what separate THIS box — one pegged core, two
155        // idle — from a box where every core is genuinely busy. Both read
156        // max_core = 1.0; only the median tells them apart.
157        let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
158        assert_eq!(cores, 3);
159        assert!((p25 - 0.0).abs() < 1e-9, "p25 {p25}");
160        assert!((p50 - 0.0).abs() < 1e-9, "median core is IDLE, got {p50}");
161        assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
162    }
163
164    /// The saturation case the quartiles must NOT confuse with one hot
165    /// core: every core busy reads max_core = 1.0 just like a single
166    /// pegged core, but the median moves with it.
167    #[test]
168    fn quartiles_separate_broad_saturation_from_one_hot_core() {
169        let stat_t0 = "\
170cpu  0 0 0 12000 0 0 0 0 0 0
171cpu0 0 0 0 4000 0 0 0 0 0 0
172cpu1 0 0 0 4000 0 0 0 0 0 0
173cpu2 0 0 0 4000 0 0 0 0 0 0";
174        let stat_t1 = "\
175cpu  12000 0 0 12000 0 0 0 0 0 0
176cpu0 4000 0 0 4000 0 0 0 0 0 0
177cpu1 4000 0 0 4000 0 0 0 0 0 0
178cpu2 4000 0 0 4000 0 0 0 0 0 0";
179        let (_, c0) = parse_proc_stat(stat_t0).unwrap();
180        let (_, c1) = parse_proc_stat(stat_t1).unwrap();
181        let (_, max) = max_core_util(&c0, &c1).unwrap();
182        let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
183        assert_eq!(cores, 3);
184        // EXACTLY the max the one-hot-core case reports — 1.0 there, 1.0
185        // here. On the max alone the two boxes are indistinguishable.
186        assert!((max - 1.0).abs() < 1e-9, "max {max}");
187        // The median is what tells them apart: 0.0 when one core is hot
188        // and the rest idle, 1.0 when the whole box is saturated.
189        assert!((p25 - 1.0).abs() < 1e-9, "p25 {p25}");
190        assert!((p50 - 1.0).abs() < 1e-9, "p50 {p50}");
191        assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
192    }
193
194    /// Nearest-rank, not interpolation: every quartile of a small core
195    /// count must be a utilization some real core actually had.
196    #[test]
197    fn quartiles_are_nearest_rank_over_real_cores() {
198        let single = vec![CpuTicks {
199            busy: 0,
200            total: 1000,
201        }];
202        let single_end = vec![CpuTicks {
203            busy: 250,
204            total: 2000,
205        }];
206        let (p25, p50, p75, cores) = core_util_quartiles(&single, &single_end).unwrap();
207        assert_eq!(cores, 1);
208        // One core: every quantile is that core.
209        assert!((p25 - 0.25).abs() < 1e-9);
210        assert!((p50 - 0.25).abs() < 1e-9);
211        assert!((p75 - 0.25).abs() < 1e-9);
212        // No cores at all is None, not a fabricated zero.
213        assert!(core_util_quartiles(&[], &[]).is_none());
214    }
215
216    /// iowait is idle-with-an-excuse: an I/O-bound stall must not read as
217    /// CPU saturation.
218    #[test]
219    fn iowait_does_not_count_as_busy() {
220        let t0 = parse_proc_stat("cpu 0 0 0 0 0 0 0 0 0 0").unwrap().0;
221        let t1 = parse_proc_stat("cpu 0 0 0 500 500 0 0 0 0 0").unwrap().0;
222        assert_eq!(cpu_util(t0, t1), 0.0);
223    }
224}