1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//! Node CPU/RAM occupancy sampler — issue #1244 (PRD #1237, Phase C).
//!
//! Records whole-node CPU and RAM utilisation as point-in-time gauges
//! (ADR 0060 §2 "node samples" data class) so `/cluster/status` can show
//! current resource pressure. Like the latency slice (#1241) this is the
//! in-process measurement + current-snapshot read model both the status
//! surface and the red-ui occupancy panels consume; the durable rollup
//! substrate is a later slice and counters reset on restart by design.
//!
//! ## Honesty rule (#738 / ADR 0060 §6)
//!
//! Each field is one of three states, never a fabricated zero:
//!
//! * [`Occupancy::Measured`] — a real ratio in `0.0..=1.0`.
//! * [`Occupancy::NotSampled`] — the platform supports measurement but no
//! value exists yet. CPU utilisation is a *delta* between two readings,
//! so the very first sample after start only establishes a baseline and
//! reports `NotSampled`; the next sample carries a measured value.
//! * [`Occupancy::Unsupported`] — this platform cannot measure the field
//! at all (anything without `/proc/stat` + `/proc/meminfo`, i.e. non-Linux).
//!
//! The presentation layer maps these to a measured envelope
//! (`{ available: true, usage_ratio, usage_percent }`) or the stable
//! `{ available: false, reason }` envelope.
//!
//! ## Sampling interval and overhead (documented)
//!
//! The sampler is driven on-demand from the `/cluster/status` handler: each
//! status read calls [`OccupancySampler::sample`], which reads `/proc/stat`
//! (one line) and `/proc/meminfo` (two lines) and computes the CPU busy
//! ratio over the wall-clock interval **since the previous status read**.
//! red-ui polls `/cluster/status` on its own cadence (a few seconds), so the
//! CPU figure naturally reflects that polling interval. There is no
//! background thread: cost is two small `procfs` reads plus integer
//! arithmetic per status call (well under a millisecond, no allocation on
//! the hot path beyond the two read buffers, no lock contention outside the
//! sampler's own short critical sections). Because the window is the
//! status-poll interval rather than a fixed tick, a value is only reported
//! once two reads exist — consistent with the honesty rule above.
use std::sync::Mutex;
/// Cumulative CPU jiffies from the aggregate `cpu` line of `/proc/stat`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CpuTimes {
/// Sum of every field on the line (busy + idle).
total: u64,
/// `idle + iowait` — the time the CPU was not doing work.
idle: u64,
}
/// One occupancy field's honest state. See module docs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Occupancy {
/// Measured utilisation ratio, clamped to `0.0..=1.0`.
Measured(f64),
/// Platform supports measurement but no value is available yet.
NotSampled,
/// This platform cannot measure the field.
Unsupported,
}
/// A point-in-time CPU + RAM occupancy reading.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OccupancySample {
pub cpu: Occupancy,
pub ram: Occupancy,
}
/// Process-local CPU/RAM occupancy sampler. Holds the previous CPU jiffies
/// reading (for delta computation) and the latest computed sample.
#[derive(Debug, Default)]
pub struct OccupancySampler {
/// Previous `/proc/stat` reading. `None` before the first sample.
prev_cpu: Mutex<Option<CpuTimes>>,
/// Latest computed sample, so a consumer can read the current value
/// without forcing a fresh measurement.
latest: Mutex<Option<OccupancySample>>,
}
impl OccupancySampler {
pub fn new() -> Self {
Self::default()
}
/// Take one measurement, update internal state, and return the sample.
pub fn sample(&self) -> OccupancySample {
let sample = self.measure();
*self
.latest
.lock()
.unwrap_or_else(|poison| poison.into_inner()) = Some(sample);
sample
}
/// The most recent measured sample, without forcing a new reading.
/// Before the first [`sample`](Self::sample) call this reports the
/// platform's baseline state (`NotSampled` on Linux, `Unsupported`
/// elsewhere) so the honesty rule holds even on the cold path.
pub fn latest(&self) -> OccupancySample {
self.latest
.lock()
.unwrap_or_else(|poison| poison.into_inner())
.unwrap_or_else(unsampled_baseline)
}
#[cfg(target_os = "linux")]
fn measure(&self) -> OccupancySample {
let ram = std::fs::read_to_string("/proc/meminfo")
.ok()
.and_then(|c| parse_meminfo_used_ratio(&c))
.map(Occupancy::Measured)
.unwrap_or(Occupancy::NotSampled);
let current = std::fs::read_to_string("/proc/stat")
.ok()
.and_then(|c| parse_proc_stat_cpu(&c));
let mut prev = self
.prev_cpu
.lock()
.unwrap_or_else(|poison| poison.into_inner());
let cpu = match (*prev, current) {
(Some(p), Some(c)) => cpu_busy_ratio(p, c)
.map(Occupancy::Measured)
.unwrap_or(Occupancy::NotSampled),
_ => Occupancy::NotSampled,
};
if let Some(c) = current {
*prev = Some(c);
}
OccupancySample { cpu, ram }
}
#[cfg(not(target_os = "linux"))]
fn measure(&self) -> OccupancySample {
OccupancySample {
cpu: Occupancy::Unsupported,
ram: Occupancy::Unsupported,
}
}
}
/// Baseline state reported before any sample exists.
#[cfg(target_os = "linux")]
fn unsampled_baseline() -> OccupancySample {
OccupancySample {
cpu: Occupancy::NotSampled,
ram: Occupancy::NotSampled,
}
}
#[cfg(not(target_os = "linux"))]
fn unsampled_baseline() -> OccupancySample {
OccupancySample {
cpu: Occupancy::Unsupported,
ram: Occupancy::Unsupported,
}
}
/// Parse the aggregate `cpu` line of `/proc/stat` into cumulative jiffies.
/// Fields after the label are: `user nice system idle iowait irq softirq
/// steal guest guest_nice`. `idle` here is `idle + iowait`.
fn parse_proc_stat_cpu(contents: &str) -> Option<CpuTimes> {
let line = contents.lines().next()?;
let mut fields = line.split_whitespace();
if fields.next()? != "cpu" {
return None;
}
let vals: Vec<u64> = fields.filter_map(|v| v.parse::<u64>().ok()).collect();
// Need at least user/nice/system/idle to be meaningful.
if vals.len() < 4 {
return None;
}
let idle = vals[3] + vals.get(4).copied().unwrap_or(0);
let total: u64 = vals.iter().sum();
Some(CpuTimes { total, idle })
}
/// Busy ratio between two cumulative CPU readings. `None` when the totals
/// did not advance (no elapsed time) or went backwards (counter reset).
fn cpu_busy_ratio(prev: CpuTimes, current: CpuTimes) -> Option<f64> {
let total_delta = current.total.checked_sub(prev.total)?;
let idle_delta = current.idle.checked_sub(prev.idle)?;
if total_delta == 0 {
return None;
}
let busy = total_delta.saturating_sub(idle_delta);
Some((busy as f64 / total_delta as f64).clamp(0.0, 1.0))
}
/// Parse `MemTotal` / `MemAvailable` from `/proc/meminfo` into a used
/// ratio (`(total - available) / total`). `None` if either line is missing
/// or `MemTotal` is zero.
fn parse_meminfo_used_ratio(contents: &str) -> Option<f64> {
let mut total: Option<u64> = None;
let mut available: Option<u64> = None;
for line in contents.lines() {
if let Some(rest) = line.strip_prefix("MemTotal:") {
total = rest.split_whitespace().next().and_then(|v| v.parse().ok());
} else if let Some(rest) = line.strip_prefix("MemAvailable:") {
available = rest.split_whitespace().next().and_then(|v| v.parse().ok());
}
}
let total = total?;
let available = available?;
if total == 0 {
return None;
}
let used = total.saturating_sub(available);
Some((used as f64 / total as f64).clamp(0.0, 1.0))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_proc_stat_sums_total_and_idle() {
// user nice system idle iowait irq softirq steal ...
let stat = "cpu 100 0 50 800 40 0 10 0 0 0\ncpu0 ...\n";
let times = parse_proc_stat_cpu(stat).unwrap();
// idle = idle(800) + iowait(40) = 840
assert_eq!(times.idle, 840);
// total = 100+0+50+800+40+0+10+0+0+0 = 1000
assert_eq!(times.total, 1000);
}
#[test]
fn parse_proc_stat_rejects_malformed() {
assert!(parse_proc_stat_cpu("").is_none());
assert!(parse_proc_stat_cpu("notcpu 1 2 3 4\n").is_none());
assert!(parse_proc_stat_cpu("cpu 1 2\n").is_none());
}
#[test]
fn cpu_ratio_is_busy_over_total() {
let prev = CpuTimes {
total: 1000,
idle: 840,
};
// 1000 more jiffies elapse, 250 of them idle -> 75% busy.
let current = CpuTimes {
total: 2000,
idle: 1090,
};
let ratio = cpu_busy_ratio(prev, current).unwrap();
assert!((ratio - 0.75).abs() < 1e-9);
}
#[test]
fn cpu_ratio_none_when_no_time_elapsed() {
let t = CpuTimes {
total: 1000,
idle: 840,
};
assert_eq!(cpu_busy_ratio(t, t), None);
}
#[test]
fn cpu_ratio_none_on_counter_reset() {
let prev = CpuTimes {
total: 2000,
idle: 1000,
};
let current = CpuTimes {
total: 1000,
idle: 500,
};
assert_eq!(cpu_busy_ratio(prev, current), None);
}
#[test]
fn cpu_ratio_clamps_to_unit_interval() {
// Idle advances more than total (impossible in practice but the
// arithmetic must never produce a negative ratio).
let prev = CpuTimes {
total: 1000,
idle: 500,
};
let current = CpuTimes {
total: 1100,
idle: 800,
};
let ratio = cpu_busy_ratio(prev, current).unwrap();
assert!((0.0..=1.0).contains(&ratio));
}
#[test]
fn meminfo_used_ratio_is_one_minus_available() {
let meminfo = "MemTotal: 16000 kB\nMemFree: 1000 kB\nMemAvailable: 4000 kB\n";
let ratio = parse_meminfo_used_ratio(meminfo).unwrap();
// used = 16000 - 4000 = 12000 -> 0.75
assert!((ratio - 0.75).abs() < 1e-9);
}
#[test]
fn meminfo_none_when_fields_missing() {
assert!(parse_meminfo_used_ratio("MemTotal: 16000 kB\n").is_none());
assert!(parse_meminfo_used_ratio("MemAvailable: 4000 kB\n").is_none());
assert!(parse_meminfo_used_ratio("MemTotal: 0 kB\nMemAvailable: 0 kB\n").is_none());
}
#[test]
fn first_sample_establishes_baseline_only() {
// The very first sample cannot produce a CPU delta — it must report
// NotSampled (Linux) or Unsupported (other) for CPU, never a number.
let sampler = OccupancySampler::new();
let first = sampler.sample();
assert!(
!matches!(first.cpu, Occupancy::Measured(_)),
"first CPU sample must not be a measured value, got {:?}",
first.cpu
);
}
#[cfg(target_os = "linux")]
#[test]
fn second_sample_returns_measured_cpu_on_linux() {
// Two consecutive reads establish a delta. On an idle CI runner the
// busy ratio can legitimately be ~0; assert the value is *measurable*
// (a real ratio in the unit interval), not strictly positive.
let sampler = OccupancySampler::new();
let _ = sampler.sample(); // baseline
// Burn a little CPU so the second reading reflects real work, but
// do not assert on the magnitude — the runner may still be idle.
let mut acc: u64 = 0;
for i in 0..2_000_000u64 {
acc = acc.wrapping_add(i);
}
std::hint::black_box(acc);
// Guarantee the aggregate jiffy counter advances between the two
// reads so the CPU delta is `Measured`, not `NotSampled`. Without a
// wall-clock gap, two back-to-back reads can land in the same jiffy
// window on a fast host (`total_delta == 0`); the busy ratio may
// still be ~0 on an idle runner, which the range assertion allows.
std::thread::sleep(std::time::Duration::from_millis(50));
let second = sampler.sample();
match second.cpu {
Occupancy::Measured(ratio) => {
assert!(
(0.0..=1.0).contains(&ratio),
"cpu ratio {ratio} must be in 0..=1"
);
}
other => panic!("expected a measured CPU ratio on the second sample, got {other:?}"),
}
// RAM is a single-shot gauge — measurable on the very first read.
assert!(
matches!(second.ram, Occupancy::Measured(r) if (0.0..=1.0).contains(&r)),
"expected a measured RAM ratio on Linux, got {:?}",
second.ram
);
}
#[cfg(target_os = "linux")]
#[test]
fn linux_baseline_is_not_sampled_before_first_sample() {
let sampler = OccupancySampler::new();
assert!(matches!(sampler.latest().cpu, Occupancy::NotSampled));
assert!(matches!(sampler.latest().ram, Occupancy::NotSampled));
}
#[cfg(not(target_os = "linux"))]
#[test]
fn non_linux_is_unsupported() {
let sampler = OccupancySampler::new();
let sample = sampler.sample();
assert!(matches!(sample.cpu, Occupancy::Unsupported));
assert!(matches!(sample.ram, Occupancy::Unsupported));
assert!(matches!(sampler.latest().cpu, Occupancy::Unsupported));
}
}