Skip to main content

agentmux_srv_core/backend/
stall_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A watch on srv's async runtime: it says in the log when the runtime stops
5//! running tasks, and for how long.
6//!
7//! A task on the runtime beats every [`Config::beat_every`]; an OS thread
8//! outside the runtime looks at the beat every [`Config::poll_every`]. A beat
9//! that is [`Config::stall_after`] or more behind, or a look that itself comes
10//! that much late (the process was paused and the beat ran again before the
11//! look did), starts a stall, which ends
12//! when beats are on time again and stay so for [`Config::merge_gap`] (a stall
13//! that returns within that gap is the same stall). One line is written when it
14//! starts and one when it ends, whatever its length, each beginning with
15//! [`PREFIX`]:
16//!
17//! ```text
18//! runtime-stall: start late_ms=1830 cause=runtime workers=8 alive_tasks=412 queue=17 load1=3.2
19//! runtime-stall: start late_ms=1830 cause=runtime workers=32 alive_tasks=412 queue=0 over_ms=2000 cpu_machine=94 cpu_srv=2 io_read_mb=0 io_write_mb=3 mem_load=58
20//! runtime-stall: end lasted_ms=5300 worst_late_ms=5200 stalls=2
21//! ```
22//!
23//! `cause=machine` says the watching thread was itself late (the machine was
24//! suspended or had no CPU for srv); `cause=runtime` says only the runtime was,
25//! which is a blocked worker or a task that did not yield, or a machine that did not schedule srv's workers while it
26//! kept the watching thread's sleep honest. The `cpu_` and `io_` figures (Windows, `stall_load`) say which: the share of
27//! all cores the machine used and srv used over the last two seconds, srv's reads and writes in MB, and how full memory
28//! was. A machine at 95% and srv at 2% is a machine with no CPU for srv; both low is a blocked worker.
29
30use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
31use std::sync::Arc;
32use std::time::{Duration, Instant};
33
34use crate::backend::stall_load;
35
36/// Every line this watch writes starts with it, so a log search finds them all.
37pub const PREFIX: &str = "runtime-stall:";
38
39#[derive(Debug, Clone, Copy)]
40pub struct Config {
41    /// How often the beat task runs.
42    pub beat_every: Duration,
43    /// How often the watching thread looks.
44    pub poll_every: Duration,
45    /// How far behind a beat has to be for a stall.
46    pub stall_after: Duration,
47    /// How long beats stay on time before the stall is over.
48    pub merge_gap: Duration,
49}
50
51impl Default for Config {
52    fn default() -> Self {
53        Self {
54            beat_every: Duration::from_millis(100),
55            poll_every: Duration::from_millis(250),
56            stall_after: Duration::from_secs(1),
57            merge_gap: Duration::from_secs(5),
58        }
59    }
60}
61
62/// What the runtime looked like when a stall was noticed.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct Snapshot {
65    pub workers: usize,
66    pub alive_tasks: usize,
67    pub queue: usize,
68    /// One-minute load average, in hundredths, where the OS gives one.
69    pub load1_centis: Option<u32>,
70    /// What the machine and srv were doing over the last seconds, where the OS gives it (Windows).
71    pub load: Option<crate::backend::stall_load::Load>,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Event {
76    Start { late_ms: u64, machine: bool, snapshot: Snapshot },
77    End { lasted_ms: u64, worst_late_ms: u64, stalls: u32 },
78}
79
80impl Event {
81    /// The log line, beginning with [`PREFIX`].
82    pub fn line(&self) -> String {
83        match self {
84            Event::Start { late_ms, machine, snapshot: s } => {
85                let load = s.load1_centis.map(|c| format!(" load1={}.{:02}", c / 100, c % 100)).unwrap_or_default();
86                let load = format!("{load}{}", s.load.map(load_fields).unwrap_or_default());
87                let cause = if *machine { "machine" } else { "runtime" };
88                format!(
89                    "{PREFIX} start late_ms={late_ms} cause={cause} workers={} alive_tasks={} queue={}{load}",
90                    s.workers, s.alive_tasks, s.queue
91                )
92            }
93            Event::End { lasted_ms, worst_late_ms, stalls } => {
94                format!("{PREFIX} end lasted_ms={lasted_ms} worst_late_ms={worst_late_ms} stalls={stalls}")
95            }
96        }
97    }
98}
99
100/// The fields a line carries for a reading of the machine, with a leading space. Numbers only.
101fn load_fields(l: stall_load::Load) -> String {
102    let mem = l.mem_load_pct.map(|p| format!(" mem_load={p}")).unwrap_or_default();
103    format!(
104        " over_ms={} cpu_machine={} cpu_srv={} io_read_mb={} io_write_mb={}{mem}",
105        l.over_ms, l.machine_cpu_pct, l.srv_cpu_pct, l.io_read_mb, l.io_write_mb
106    )
107}
108
109/// Where a stall is, one look at a time. Pure over the times it is given.
110#[derive(Debug)]
111struct Tracker {
112    cfg: Config,
113    stall: Option<Stall>,
114}
115
116#[derive(Debug)]
117struct Stall {
118    /// When the first beat of it was due.
119    began_ms: u64,
120    worst_late_ms: u64,
121    stalls: u32,
122    /// The last look that found it late.
123    last_late_look_ms: u64,
124    /// When beats came back, and the beat that showed it: set while they stay
125    /// on time, cleared by a new stall inside the merge gap.
126    recovered: Option<(u64, u64)>,
127}
128
129impl Tracker {
130    fn new(cfg: Config) -> Self {
131        Self { cfg, stall: None }
132    }
133
134    /// One look at `now_ms`: the last beat was at `last_beat_ms`, and the
135    /// watching thread's own sleep ran `watcher_late_ms` over. `snapshot` is read
136    /// only when a stall starts.
137    fn look(&mut self, now_ms: u64, last_beat_ms: u64, watcher_late_ms: u64, snapshot: impl FnOnce() -> Snapshot) -> Option<Event> {
138        let beat_ms = self.cfg.beat_every.as_millis() as u64;
139        let stall_ms = self.cfg.stall_after.as_millis() as u64;
140        let gap_ms = self.cfg.merge_gap.as_millis() as u64;
141        // The beat's lateness, or the look's own if that is more: after a pause the
142        // beat may already have run again, and the look's lateness is what is left.
143        let late_ms = now_ms.saturating_sub(last_beat_ms).saturating_sub(beat_ms).max(watcher_late_ms);
144        let stalled_now = late_ms >= stall_ms;
145        let on_time = late_ms < stall_ms / 2;
146        match &mut self.stall {
147            None if stalled_now => {
148                self.stall = Some(Stall { began_ms: now_ms.saturating_sub(late_ms), worst_late_ms: late_ms, stalls: 1, last_late_look_ms: now_ms, recovered: None });
149                Some(Event::Start { late_ms, machine: watcher_late_ms >= stall_ms / 2, snapshot: snapshot() })
150            }
151            None => None,
152            Some(s) => {
153                s.worst_late_ms = s.worst_late_ms.max(late_ms);
154                if stalled_now {
155                    s.last_late_look_ms = now_ms;
156                    if s.recovered.take().is_some() {
157                        s.stalls += 1;
158                    }
159                    return None;
160                }
161                if on_time && s.recovered.is_none() {
162                    s.recovered = Some((now_ms, last_beat_ms));
163                }
164                match s.recovered {
165                    Some((at, beat)) if now_ms.saturating_sub(at) >= gap_ms => {
166                        // It ended at the beat that showed it, or at the last late look.
167                        let ended = s.last_late_look_ms.max(if beat >= s.began_ms { beat } else { 0 });
168                        let ev = Event::End { lasted_ms: ended.saturating_sub(s.began_ms), worst_late_ms: s.worst_late_ms, stalls: s.stalls };
169                        self.stall = None;
170                        Some(ev)
171                    }
172                    _ => None,
173                }
174            }
175        }
176    }
177}
178
179/// Stops the watching thread when the beat task is dropped with its runtime.
180struct StopOnDrop(Arc<AtomicBool>);
181
182impl Drop for StopOnDrop {
183    fn drop(&mut self) {
184        self.0.store(true, Ordering::Relaxed);
185    }
186}
187
188/// Watch `runtime` with `cfg`, calling `on_event` from the watching thread.
189pub fn watch(runtime: tokio::runtime::Handle, cfg: Config, on_event: impl Fn(Event) + Send + 'static) {
190    let epoch = Instant::now();
191    let beat = Arc::new(AtomicU64::new(0));
192    let stop = Arc::new(AtomicBool::new(false));
193    {
194        let (beat, guard) = (beat.clone(), StopOnDrop(stop.clone()));
195        runtime.spawn(async move {
196            let _guard = guard;
197            loop {
198                tokio::time::sleep(cfg.beat_every).await;
199                beat.store(epoch.elapsed().as_millis() as u64, Ordering::Relaxed);
200            }
201        });
202    }
203    let metrics = runtime.clone();
204    let spawned = std::thread::Builder::new().name("runtime-stall-watch".into()).spawn(move || {
205        let mut tracker = Tracker::new(cfg);
206        let mut history = stall_load::History::default();
207        loop {
208            let slept = Instant::now();
209            std::thread::sleep(cfg.poll_every);
210            if stop.load(Ordering::Relaxed) {
211                return;
212            }
213            let watcher_late_ms = slept.elapsed().saturating_sub(cfg.poll_every).as_millis() as u64;
214            let now_ms = epoch.elapsed().as_millis() as u64;
215            if let Some(reading) = stall_load::read(now_ms) {
216                history.push(reading);
217            }
218            let snapshot = || {
219                let m = metrics.metrics();
220                Snapshot {
221                    workers: m.num_workers(),
222                    alive_tasks: m.num_alive_tasks(),
223                    queue: m.global_queue_depth(),
224                    load1_centis: load1_centis(),
225                    load: history.load_over(stall_load::REPORT_OVER_MS, stall_load::mem_load_pct()),
226                }
227            };
228            if let Some(ev) = tracker.look(now_ms, beat.load(Ordering::Relaxed), watcher_late_ms, snapshot) {
229                on_event(ev);
230            }
231        }
232    });
233    if let Err(e) = spawned {
234        tracing::warn!("{PREFIX} the watch could not start: {e}");
235    }
236}
237
238/// The record's line for a stall that ended: how long it lasted, its worst lateness, how many stalls were merged
239/// into it, and whether the machine (not the runtime) was the cause. Numbers and a name only.
240pub fn record_fields(lasted_ms: u64, worst_late_ms: u64, stalls: u32, machine: bool) -> serde_json::Value {
241    serde_json::json!({ "ms": lasted_ms, "worst_ms": worst_late_ms, "n": stalls, "cause": if machine { "machine" } else { "runtime" } })
242}
243
244/// Start the watch on the current runtime, writing its lines to the log and each stall that ended to the record
245/// (`agentmux_common::record_events`: a stall of a month ago is as findable as one of a minute ago).
246pub fn start() {
247    let machine = AtomicBool::new(false);
248    watch(tokio::runtime::Handle::current(), Config::default(), move |ev| {
249        tracing::warn!("{}", ev.line());
250        match ev {
251            Event::Start { machine: m, .. } => machine.store(m, Ordering::Relaxed),
252            Event::End { lasted_ms, worst_late_ms, stalls } => {
253                let Some(dir) = agentmux_common::record_events::record_dir() else { return };
254                let fields = record_fields(lasted_ms, worst_late_ms, stalls, machine.load(Ordering::Relaxed));
255                if let Err(e) = agentmux_common::record_events::append_event(&dir, agentmux_common::time::now_ms_u64(), "srv_stall", fields) {
256                    tracing::debug!("{PREFIX} the record could not take the event: {e}");
257                }
258            }
259        }
260    });
261}
262
263#[cfg(unix)]
264fn load1_centis() -> Option<u32> {
265    let mut avg = [0f64; 1];
266    // SAFETY: `avg` holds the one value asked for.
267    let got = unsafe { libc::getloadavg(avg.as_mut_ptr(), 1) };
268    (got == 1).then(|| (avg[0] * 100.0).round() as u32)
269}
270
271#[cfg(not(unix))]
272fn load1_centis() -> Option<u32> {
273    None
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    fn tracker() -> Tracker {
281        Tracker::new(Config::default())
282    }
283
284    /// Looks every 250 ms from `from` to `to` (ms), the last beat at `beat` until
285    /// `back_at`, then on time; returns each look's event.
286    fn run(t: &mut Tracker, from: u64, to: u64, beat: u64, back_at: u64) -> Vec<(u64, Event)> {
287        let mut out = Vec::new();
288        let mut now = from;
289        while now <= to {
290            let last = if now >= back_at { now - 50 } else { beat };
291            if let Some(ev) = t.look(now, last, 0, Snapshot::default) {
292                out.push((now, ev));
293            }
294            now += 250;
295        }
296        out
297    }
298
299    #[test]
300    fn the_record_keeps_numbers_and_the_cause_of_a_stall() {
301        assert_eq!(record_fields(5_300, 5_200, 2, false), serde_json::json!({ "ms": 5_300, "worst_ms": 5_200, "n": 2, "cause": "runtime" }));
302        assert_eq!(record_fields(60_000, 59_000, 1, true)["cause"], "machine");
303    }
304
305    #[test]
306    fn beats_on_time_are_not_a_stall() {
307        let mut t = tracker();
308        assert!(run(&mut t, 1_000, 60_000, 0, 0).is_empty());
309        // 900 ms behind the due time is still under the 1 s line.
310        assert_eq!(t.look(2_000, 1_000, 0, Snapshot::default), None);
311    }
312
313    #[test]
314    fn a_long_stall_writes_a_start_and_an_end_not_a_line_a_second() {
315        let mut t = tracker();
316        // Last beat at 1 000; nothing until 61 000; then on time for longer than the gap.
317        let events = run(&mut t, 1_250, 80_000, 1_000, 61_000);
318        let kinds: Vec<_> = events.iter().map(|(_, e)| matches!(e, Event::Start { .. })).collect();
319        assert_eq!(kinds, vec![true, false], "{events:?}");
320        let (start_at, start) = &events[0];
321        // Noticed once it was a second late (the beat was due at 1 100).
322        assert_eq!(*start_at, 2_250);
323        assert!(matches!(start, Event::Start { late_ms: 1_150, machine: false, .. }), "{start:?}");
324        let (end_at, end) = &events[1];
325        assert!(*end_at >= 61_000 + 5_000, "ended only after beats stayed on time for the gap: {end_at}");
326        assert_eq!(*end, Event::End { lasted_ms: 61_000 - 50 - 1_100, worst_late_ms: 60_750 - 1_000 - 100, stalls: 1 });
327    }
328
329    #[test]
330    fn a_stall_that_returns_inside_the_gap_is_the_same_stall() {
331        let mut t = tracker();
332        let mut events = run(&mut t, 1_250, 7_500, 1_000, 5_000);
333        // Beats were back from 5 000, then stop again after the beat at 7 700.
334        events.extend(run(&mut t, 7_750, 40_000, 7_700, 30_000));
335        let starts = events.iter().filter(|(_, e)| matches!(e, Event::Start { .. })).count();
336        let ends: Vec<_> = events.iter().filter_map(|(_, e)| if let Event::End { stalls, .. } = e { Some(*stalls) } else { None }).collect();
337        assert_eq!((starts, ends), (1, vec![2]), "{events:?}");
338    }
339
340    #[test]
341    fn stalls_further_apart_than_the_gap_are_two_stalls() {
342        let mut t = tracker();
343        let mut events = run(&mut t, 1_250, 20_000, 1_000, 4_000);
344        events.extend(run(&mut t, 20_250, 60_000, 20_000, 30_000));
345        let shape: Vec<_> = events.iter().map(|(_, e)| matches!(e, Event::Start { .. })).collect();
346        assert_eq!(shape, vec![true, false, true, false], "{events:?}");
347    }
348
349    #[test]
350    fn a_late_watching_thread_says_the_machine_was_the_cause() {
351        let mut t = tracker();
352        let ev = t.look(5_000, 1_000, 3_000, Snapshot::default);
353        assert!(matches!(ev, Some(Event::Start { machine: true, .. })), "{ev:?}");
354        let mut t = tracker();
355        let ev = t.look(5_000, 1_000, 2, Snapshot::default);
356        assert!(matches!(ev, Some(Event::Start { machine: false, .. })), "{ev:?}");
357    }
358
359    /// A paused process whose beat ran again before the look did: the look's own
360    /// lateness is what shows it.
361    #[test]
362    fn a_pause_is_seen_even_when_the_beat_ran_again_first() {
363        let mut t = tracker();
364        let ev = t.look(5_000, 4_999, 3_750, Snapshot::default);
365        assert!(matches!(ev, Some(Event::Start { late_ms: 3_750, machine: true, .. })), "{ev:?}");
366        // Looks and beats on time after it: one end line once the gap has passed, and
367        // no second start.
368        let mut seen = Vec::new();
369        for now in (5_250..=12_000).step_by(250) {
370            seen.extend(t.look(now, now - 20, 1, Snapshot::default));
371        }
372        // It ended at the first beat seen on time, a look after the pause.
373        assert_eq!(seen, vec![Event::End { lasted_ms: 3_980, worst_late_ms: 3_750, stalls: 1 }]);
374    }
375
376    #[test]
377    fn every_line_starts_with_the_prefix() {
378        let snapshot = Snapshot { workers: 8, alive_tasks: 412, queue: 17, load1_centis: Some(320), load: None };
379        let start = Event::Start { late_ms: 1830, machine: false, snapshot }.line();
380        let end = Event::End { lasted_ms: 5300, worst_late_ms: 5200, stalls: 2 }.line();
381        assert_eq!(start, "runtime-stall: start late_ms=1830 cause=runtime workers=8 alive_tasks=412 queue=17 load1=3.20");
382        assert_eq!(end, "runtime-stall: end lasted_ms=5300 worst_late_ms=5200 stalls=2");
383        assert!(start.starts_with(PREFIX) && end.starts_with(PREFIX));
384    }
385
386    #[test]
387    fn a_start_line_carries_what_the_machine_and_srv_were_doing() {
388        let load = stall_load::Load { over_ms: 2_000, machine_cpu_pct: 94, srv_cpu_pct: 2, io_read_mb: 0, io_write_mb: 3, mem_load_pct: Some(58) };
389        let snapshot = Snapshot { workers: 32, alive_tasks: 412, queue: 0, load1_centis: None, load: Some(load) };
390        let start = Event::Start { late_ms: 1830, machine: false, snapshot }.line();
391        assert_eq!(
392            start,
393            "runtime-stall: start late_ms=1830 cause=runtime workers=32 alive_tasks=412 queue=0 over_ms=2000 cpu_machine=94 cpu_srv=2 io_read_mb=0 io_write_mb=3 mem_load=58"
394        );
395        let no_memory = Snapshot { load: Some(stall_load::Load { mem_load_pct: None, ..load }), ..snapshot };
396        assert!(!Event::Start { late_ms: 1830, machine: true, snapshot: no_memory }.line().contains("mem_load"));
397    }
398
399    fn fast() -> Config {
400        Config {
401            beat_every: Duration::from_millis(5),
402            poll_every: Duration::from_millis(10),
403            stall_after: Duration::from_millis(150),
404            merge_gap: Duration::from_millis(100),
405        }
406    }
407
408    /// A task that blocks the runtime's only worker is seen, and its end too.
409    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
410    async fn a_blocked_worker_is_reported_and_then_recovers() {
411        let (tx, rx) = std::sync::mpsc::channel();
412        watch(tokio::runtime::Handle::current(), fast(), move |ev| {
413            let _ = tx.send(ev);
414        });
415        tokio::time::sleep(Duration::from_millis(100)).await;
416        assert!(rx.try_recv().is_err(), "an idle runtime is not a stall");
417        tokio::spawn(async { std::thread::sleep(Duration::from_millis(400)) });
418        let wait = Duration::from_secs(10);
419        let start = rx.recv_timeout(wait).expect("start");
420        // Not `machine: false`: on a loaded runner the watching thread can itself be late, which is rightly said to be the
421        // machine (the classification has its own tests above).
422        assert!(matches!(start, Event::Start { snapshot: Snapshot { workers: 1, .. }, .. }), "{start:?}");
423        let end = rx.recv_timeout(wait).expect("end");
424        match end {
425            Event::End { lasted_ms, stalls, .. } => assert!((200..3_000).contains(&lasted_ms) && stalls == 1, "{end:?}"),
426            other => panic!("{other:?}"),
427        }
428    }
429}