Skip to main content

agentmux_srv_core/backend/
stall_load.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the machine and srv itself were doing in the seconds before a runtime stall.
5//!
6//! The stall watch (`stall_watch`) can say that the runtime's beat was late, not why. A late beat with an empty queue is
7//! what a machine with no CPU for srv looks like, and also what workers blocked in a synchronous call look like. These
8//! counters tell them apart: the machine's busy share, srv's own share, how much srv read and wrote, and how full memory
9//! was. They are read at every look (a few system calls, four times a second) and kept for a few seconds; the start line
10//! of a stall reports what changed over the last two seconds, which reaches back into the stall itself.
11//!
12//! Windows only: elsewhere [`read`] gives nothing and the line carries the load average instead. Numbers only.
13
14use std::collections::VecDeque;
15
16/// How far back the start line looks.
17pub const REPORT_OVER_MS: u64 = 2_000;
18/// How long a reading is kept.
19const KEEP_MS: u64 = 12_000;
20
21/// One reading of the counters, on the watch's clock.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub struct Sample {
24    pub at_ms: u64,
25    /// All cores, kernel and user time, minus idle time (100 ns units).
26    pub machine_busy: u64,
27    /// All cores, kernel and user time (100 ns units).
28    pub machine_total: u64,
29    /// This process, kernel and user time (100 ns units).
30    pub srv_cpu: u64,
31    pub io_read_bytes: u64,
32    pub io_write_bytes: u64,
33}
34
35/// What changed between two readings.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub struct Load {
38    /// The span the figures cover.
39    pub over_ms: u64,
40    /// The share of all cores that were busy, in percent.
41    pub machine_cpu_pct: u32,
42    /// The share of all cores srv's own threads used, in percent.
43    pub srv_cpu_pct: u32,
44    pub io_read_mb: u64,
45    pub io_write_mb: u64,
46    /// How full physical memory was when the stall was noticed, in percent.
47    pub mem_load_pct: Option<u32>,
48}
49
50fn pct(part: u64, whole: u64) -> u32 {
51    ((part as u128 * 100 + whole as u128 / 2) / whole as u128).min(100) as u32
52}
53
54/// The change from `from` to `to`, or nothing when no time passed between them.
55pub fn delta(from: &Sample, to: &Sample, mem_load_pct: Option<u32>) -> Option<Load> {
56    let total = to.machine_total.checked_sub(from.machine_total).filter(|t| *t > 0)?;
57    let over_ms = to.at_ms.checked_sub(from.at_ms).filter(|t| *t > 0)?;
58    Some(Load {
59        over_ms,
60        machine_cpu_pct: pct(to.machine_busy.saturating_sub(from.machine_busy), total),
61        srv_cpu_pct: pct(to.srv_cpu.saturating_sub(from.srv_cpu), total),
62        io_read_mb: to.io_read_bytes.saturating_sub(from.io_read_bytes) / (1024 * 1024),
63        io_write_mb: to.io_write_bytes.saturating_sub(from.io_write_bytes) / (1024 * 1024),
64        mem_load_pct,
65    })
66}
67
68/// The last few seconds of readings.
69#[derive(Debug, Default)]
70pub struct History {
71    samples: VecDeque<Sample>,
72}
73
74impl History {
75    /// Keeps `sample`, and drops what is older than [`KEEP_MS`].
76    pub fn push(&mut self, sample: Sample) {
77        while self.samples.front().is_some_and(|s| sample.at_ms.saturating_sub(s.at_ms) > KEEP_MS) {
78            self.samples.pop_front();
79        }
80        self.samples.push_back(sample);
81    }
82
83    /// What changed over the last `over_ms`, from the newest reading back to the latest one at least that far back
84    /// (the oldest kept one when the history is shorter).
85    pub fn load_over(&self, over_ms: u64, mem_load_pct: Option<u32>) -> Option<Load> {
86        let newest = self.samples.back()?;
87        let from = self
88            .samples
89            .iter()
90            .rev()
91            .find(|s| newest.at_ms.saturating_sub(s.at_ms) >= over_ms)
92            .or_else(|| self.samples.front())?;
93        delta(from, newest, mem_load_pct)
94    }
95}
96
97/// A reading now, stamped `at_ms`; nothing where the counters are not read.
98#[cfg(windows)]
99pub fn read(at_ms: u64) -> Option<Sample> {
100    use windows_sys::Win32::Foundation::FILETIME;
101    use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessIoCounters, GetProcessTimes, GetSystemTimes, IO_COUNTERS};
102    let value = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime);
103    let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
104    let (mut idle, mut kernel, mut user) = (zero, zero, zero);
105    // SAFETY: the three pointers are to live locals of the type the call fills.
106    if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
107        return None;
108    }
109    let (mut created, mut exited, mut proc_kernel, mut proc_user) = (zero, zero, zero, zero);
110    // SAFETY: as above; the pseudo-handle of the current process needs no closing.
111    let process = unsafe { GetCurrentProcess() };
112    if unsafe { GetProcessTimes(process, &mut created, &mut exited, &mut proc_kernel, &mut proc_user) } == 0 {
113        return None;
114    }
115    // SAFETY: `io` is a zeroed plain struct the call fills.
116    let mut io: IO_COUNTERS = unsafe { std::mem::zeroed() };
117    let io_ok = unsafe { GetProcessIoCounters(process, &mut io) } != 0;
118    let total = value(kernel) + value(user);
119    Some(Sample {
120        at_ms,
121        machine_busy: total.saturating_sub(value(idle)),
122        machine_total: total,
123        srv_cpu: value(proc_kernel) + value(proc_user),
124        io_read_bytes: if io_ok { io.ReadTransferCount } else { 0 },
125        io_write_bytes: if io_ok { io.WriteTransferCount } else { 0 },
126    })
127}
128
129#[cfg(not(windows))]
130pub fn read(_at_ms: u64) -> Option<Sample> {
131    None
132}
133
134/// How full physical memory is now, in percent.
135#[cfg(windows)]
136pub fn mem_load_pct() -> Option<u32> {
137    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
138    // SAFETY: a zeroed plain struct with its length set, as the call requires.
139    let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
140    mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
141    (unsafe { GlobalMemoryStatusEx(&mut mem) } != 0).then_some(mem.dwMemoryLoad)
142}
143
144#[cfg(not(windows))]
145pub fn mem_load_pct() -> Option<u32> {
146    None
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    fn sample(at_ms: u64, busy: u64, total: u64, srv: u64, read_mb: u64, write_mb: u64) -> Sample {
154        Sample { at_ms, machine_busy: busy, machine_total: total, srv_cpu: srv, io_read_bytes: read_mb << 20, io_write_bytes: write_mb << 20 }
155    }
156
157    #[test]
158    fn a_busy_machine_and_a_quiet_srv_read_as_such() {
159        // 2 s on 32 cores is 640,000,000 units of 100 ns in all; 90% busy, srv 3%.
160        let a = sample(1_000, 0, 0, 0, 10, 10);
161        let b = sample(3_000, 576_000_000, 640_000_000, 19_200_000, 10, 50);
162        let load = delta(&a, &b, Some(71)).unwrap();
163        assert_eq!(load, Load { over_ms: 2_000, machine_cpu_pct: 90, srv_cpu_pct: 3, io_read_mb: 0, io_write_mb: 40, mem_load_pct: Some(71) });
164    }
165
166    #[test]
167    fn no_time_between_two_readings_is_no_figure() {
168        let a = sample(1_000, 5, 10, 1, 0, 0);
169        assert_eq!(delta(&a, &a, None), None);
170        assert_eq!(delta(&sample(2_000, 5, 10, 1, 0, 0), &sample(1_000, 6, 11, 2, 0, 0), None), None);
171        assert_eq!(delta(&sample(1_000, 5, 10, 1, 0, 0), &sample(2_000, 5, 10, 1, 0, 0), None), None, "no CPU time passed");
172    }
173
174    #[test]
175    fn a_share_never_exceeds_a_hundred() {
176        let load = delta(&sample(0, 0, 0, 0, 0, 0), &sample(1_000, 300, 100, 500, 0, 0), None).unwrap();
177        assert_eq!((load.machine_cpu_pct, load.srv_cpu_pct), (100, 100));
178    }
179
180    #[test]
181    fn the_history_looks_back_the_span_asked_and_forgets_the_old() {
182        let mut h = History::default();
183        for i in 0..100u64 {
184            h.push(sample(i * 250, i * 10, i * 20, i, 0, 0));
185        }
186        // Newest at 24,750 ms; the span of 2 s starts at the reading 8 looks earlier.
187        let load = h.load_over(REPORT_OVER_MS, None).unwrap();
188        assert_eq!(load.over_ms, 2_000);
189        assert_eq!(load.machine_cpu_pct, 50);
190        assert!(h.samples.len() <= 50, "readings older than 12 s are dropped, kept {}", h.samples.len());
191    }
192
193    #[test]
194    fn a_short_history_reports_what_there_is() {
195        let mut h = History::default();
196        assert_eq!(h.load_over(REPORT_OVER_MS, None), None);
197        h.push(sample(0, 0, 0, 0, 0, 0));
198        assert_eq!(h.load_over(REPORT_OVER_MS, None), None, "one reading is no span");
199        h.push(sample(500, 5, 10, 1, 0, 0));
200        assert_eq!(h.load_over(REPORT_OVER_MS, None).unwrap().over_ms, 500);
201    }
202
203    #[cfg(windows)]
204    #[test]
205    fn the_counters_are_read_on_windows() {
206        let a = read(0).expect("a reading");
207        let mut x = 0u64;
208        for i in 0..50_000_000u64 {
209            x = x.wrapping_add(i);
210        }
211        std::hint::black_box(x);
212        let b = read(100).expect("a second reading");
213        assert!(b.machine_total >= a.machine_total && b.srv_cpu >= a.srv_cpu);
214        assert!(mem_load_pct().is_some_and(|p| p <= 100));
215    }
216}