Skip to main content

agentmux_srv_core/backend/
build_slot_idle.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Notices a build-slot holder that has stopped working: its process tree has used no CPU for
5//! [`IDLE_AFTER_SECS`] (a hung test, a prompt waiting for input, a lost network call), while
6//! everyone else waits in the queue. Never stops anything.
7//!
8//! Git Bash cannot do this itself: it sees no CPU time for native programs and reports pid 1 for a
9//! parent that is one. So the script records its Windows process id (`winpid` in the owner file)
10//! and srv, once a minute while a slot is held, adds up the CPU of that process and everything
11//! below it. When it has not moved, srv
12//!
13//! - writes `<slot>/idle` (`build-slot status` prints "idle for N min, no CPU"), and
14//! - tells the holder's agent once, then at most once an hour while it stays idle.
15//!
16//! The decisions are pure ([`Watch::observe`], [`tree_cpu_ms`]) and the process list is a
17//! parameter of [`check`], so they are tested without a clock or a running build.
18
19use std::collections::HashSet;
20use std::panic::AssertUnwindSafe;
21use std::path::Path;
22use std::time::Duration;
23
24use agentmux_common::build_slot::{self as slot, SlotHolder};
25
26use crate::backend::reactive::ReactiveHandler;
27
28/// A holder whose tree used no CPU for this long is idle.
29pub const IDLE_AFTER_SECS: u64 = 10 * 60;
30/// While it stays idle, its agent hears of it at most this often.
31pub const RENOTIFY_SECS: u64 = 60 * 60;
32const CHECK_EVERY: Duration = Duration::from_secs(60);
33/// The script's own heartbeat (a subshell that touches a file every 20 s) is in the tree, and a
34/// fork under Git Bash costs it a little CPU each time. That much, plus [`NOISE_MS_PER_SEC`] for
35/// every second since the CPU last moved, is not work.
36const NOISE_FLOOR_MS: u64 = 500;
37const NOISE_MS_PER_SEC: u64 = 5;
38
39/// One process, as far as the check needs to know it.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct Proc {
42    pub pid: u32,
43    pub parent: Option<u32>,
44    /// CPU time used since it started, user plus kernel, in milliseconds.
45    pub cpu_ms: u64,
46}
47
48/// The CPU time of `root` and every process below it, or `None` when `root` is not running.
49pub fn tree_cpu_ms(procs: &[Proc], root: u32) -> Option<u64> {
50    procs.iter().find(|p| p.pid == root)?;
51    let mut seen: HashSet<u32> = HashSet::from([root]);
52    let mut queue = vec![root];
53    let mut total = 0u64;
54    while let Some(pid) = queue.pop() {
55        for p in procs {
56            if p.pid == pid {
57                total = total.saturating_add(p.cpu_ms);
58            }
59            // A parent link can be stale (a reused pid): `seen` keeps it from looping.
60            if p.parent == Some(pid) && seen.insert(p.pid) {
61                queue.push(p.pid);
62            }
63        }
64    }
65    Some(total)
66}
67
68/// What the last look at the holder found.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Step {
71    /// Working, or not known to be idle.
72    Busy,
73    /// No CPU since `since` (epoch seconds). `notify`: its agent should be told now.
74    Idle { since: u64, notify: bool },
75}
76
77#[derive(Debug)]
78struct Run {
79    token: String,
80    /// The tree's CPU when it last moved by more than noise, and when that was.
81    base_cpu_ms: u64,
82    base_at: u64,
83    notified_at: Option<u64>,
84}
85
86/// What srv remembers between looks: the run being watched.
87#[derive(Debug, Default)]
88pub struct Watch {
89    run: Option<Run>,
90}
91
92impl Watch {
93    /// Forgets the run: the slot is free, or the holder cannot be watched.
94    pub fn forget(&mut self) {
95        self.run = None;
96    }
97
98    /// One look: `cpu_ms` is the holder tree's CPU now (`None` when it could not be read) and
99    /// `now` epoch seconds.
100    pub fn observe(&mut self, token: &str, cpu_ms: Option<u64>, now: u64) -> Step {
101        let Some(cpu) = cpu_ms else {
102            self.run = None;
103            return Step::Busy;
104        };
105        let run = match &mut self.run {
106            Some(run) if run.token == token => run,
107            other => other.insert(Run { token: token.to_string(), base_cpu_ms: cpu, base_at: now, notified_at: None }),
108        };
109        let allowed = NOISE_FLOOR_MS + now.saturating_sub(run.base_at) * NOISE_MS_PER_SEC;
110        // Less than before means a child ended: something happened.
111        if cpu < run.base_cpu_ms || cpu - run.base_cpu_ms > allowed {
112            *run = Run { token: run.token.clone(), base_cpu_ms: cpu, base_at: now, notified_at: None };
113            return Step::Busy;
114        }
115        if now.saturating_sub(run.base_at) < IDLE_AFTER_SECS {
116            return Step::Busy;
117        }
118        let notify = run.notified_at.is_none_or(|at| now.saturating_sub(at) >= RENOTIFY_SECS);
119        if notify {
120            run.notified_at = Some(now);
121        }
122        Step::Idle { since: run.base_at, notify }
123    }
124}
125
126/// A holder found idle.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Idle {
129    pub holder: SlotHolder,
130    pub since: u64,
131    pub notify: bool,
132}
133
134/// One look at the slot under `root` at `now` (epoch seconds). `processes` lists the machine's
135/// processes and is only called when a slot is held. Keeps `<slot>/idle` in step with what it
136/// finds, and returns the holder when it is idle.
137pub fn check(root: &Path, watch: &mut Watch, now: u64, processes: impl FnOnce() -> Vec<Proc>) -> Option<Idle> {
138    let Some(holder) = slot::read_holder(root, now) else {
139        watch.forget();
140        return None;
141    };
142    // A script from before version 9 wrote no Windows id, and a run with no token cannot be told
143    // from the next one: neither can be watched.
144    let Some(pid) = holder.process_id().filter(|_| !holder.token.is_empty()) else {
145        watch.forget();
146        return None;
147    };
148    let cpu = tree_cpu_ms(&processes(), pid);
149    match watch.observe(&holder.token, cpu, now) {
150        Step::Busy => {
151            slot::clear_idle(root);
152            None
153        }
154        Step::Idle { since, notify } => {
155            if let Err(e) = slot::write_idle(root, &holder.token, since) {
156                tracing::debug!(error = %e, "build slot: could not write the idle note");
157            }
158            Some(Idle { holder, since, notify })
159        }
160    }
161}
162
163/// What the holder's agent is told.
164pub fn note_text(idle: &Idle, now: u64) -> String {
165    let minutes = now.saturating_sub(idle.since) / 60;
166    let process = match idle.holder.process_id() {
167        Some(pid) => format!("its process id is {pid}, and what it started runs below it"),
168        None => "by its process id, which `BUILD_SLOT_VERBOSE=1 build-slot status` shows".to_string(),
169    };
170    let command: String = idle.holder.command.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
171    format!(
172        "The build you started in the build slot has used no CPU for {minutes} min: {command}\n\
173         It may be stuck (a hung test, a prompt waiting for input, a lost network call), and anyone queued behind it is waiting. \
174         `build-slot status` shows it. AgentMux has not stopped it: if it is stuck, end it ({process}) so the slot is free. \
175         You hear of it again at most once an hour while it stays idle."
176    )
177}
178
179fn snapshot(sys: &mut sysinfo::System) -> Vec<Proc> {
180    sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::All, true, sysinfo::ProcessRefreshKind::nothing().with_cpu());
181    sys.processes()
182        .iter()
183        .map(|(pid, p)| Proc { pid: pid.as_u32(), parent: p.parent().map(|p| p.as_u32()), cpu_ms: p.accumulated_cpu_time() })
184        .collect()
185}
186
187/// Tells the idle holder's agent, from the watch's own thread. That thread has no Tokio runtime, and a note to an agent
188/// between turns starts a turn, which spawns tasks (the status heartbeat): without a runtime `tokio::spawn` panics, while
189/// the handler lock is held (#2577: on 2026-11-15 that stopped all agent messaging on a machine for two hours). So the
190/// delivery runs inside `runtime`, and a panic in it is logged and costs this note, not the watch.
191fn tell_holder(runtime: &tokio::runtime::Handle, handler: &ReactiveHandler, idle: &Idle, now: u64) {
192    let _in_runtime = runtime.enter();
193    let text = note_text(idle, now);
194    match std::panic::catch_unwind(AssertUnwindSafe(|| handler.deliver_system_note(&idle.holder.agent, &text))) {
195        Ok(Ok(())) => tracing::info!(agent = %idle.holder.agent, idle_min = (now - idle.since) / 60, "build slot: told the holder it is idle"),
196        Ok(Err(e)) => tracing::debug!(agent = %idle.holder.agent, error = %e, "build slot: the idle holder was not told"),
197        Err(_) => tracing::error!(agent = %idle.holder.agent, "build slot: telling the idle holder panicked; the watch goes on"),
198    }
199}
200
201/// Starts the once-a-minute look. Only the srv that runs the host's cleanups does it, so two
202/// AgentMux channels on one machine do not both write the note or message the agent.
203pub fn install() {
204    if !crate::backend::build_cache_service::this_srv_may_clean() {
205        return;
206    }
207    // Called during srv start, inside the runtime: the watch's thread delivers through this handle.
208    let Ok(runtime) = tokio::runtime::Handle::try_current() else {
209        tracing::warn!("build slot: idle watch not started: not called from inside the Tokio runtime");
210        return;
211    };
212    let spawned = std::thread::Builder::new().name("build-slot-idle".into()).spawn(move || {
213        let (mut watch, mut sys) = (Watch::default(), sysinfo::System::new());
214        loop {
215            std::thread::sleep(CHECK_EVERY);
216            let Some(root) = slot::lock_dir() else { return };
217            let now = agentmux_common::time::now_secs_u64();
218            let Some(idle) = check(&root, &mut watch, now, || snapshot(&mut sys)).filter(|i| i.notify) else { continue };
219            tell_holder(&runtime, crate::backend::reactive::get_global_handler(), &idle, now);
220        }
221    });
222    if let Err(e) = spawned {
223        tracing::warn!(error = %e, "build slot: idle watch not started");
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    fn p(pid: u32, parent: Option<u32>, cpu_ms: u64) -> Proc {
232        Proc { pid, parent, cpu_ms }
233    }
234
235    #[test]
236    fn the_tree_adds_the_root_and_everything_below_it_and_nothing_else() {
237        let procs = [p(1, None, 5), p(10, Some(1), 100), p(11, Some(10), 200), p(12, Some(10), 300), p(20, Some(1), 7000)];
238        assert_eq!(tree_cpu_ms(&procs, 10), Some(600), "the root, a child and a grandchild; not its sibling or parent");
239        assert_eq!(tree_cpu_ms(&procs, 99), None, "a root that is not running");
240        let looped = [p(1, Some(2), 1), p(2, Some(1), 2)];
241        assert_eq!(tree_cpu_ms(&looped, 1), Some(3), "a parent cycle (a reused pid) does not loop");
242    }
243
244    const T0: u64 = 1_000_000;
245
246    #[test]
247    fn a_tree_that_uses_no_cpu_is_idle_after_the_wait_and_told_once_an_hour() {
248        let mut w = Watch::default();
249        assert_eq!(w.observe("a", Some(5000), T0), Step::Busy, "the first look only takes the base");
250        assert_eq!(w.observe("a", Some(5000), T0 + 9 * 60), Step::Busy, "not yet");
251        assert_eq!(w.observe("a", Some(5000), T0 + 10 * 60), Step::Idle { since: T0, notify: true });
252        assert_eq!(w.observe("a", Some(5000), T0 + 11 * 60), Step::Idle { since: T0, notify: false }, "told already");
253        assert_eq!(w.observe("a", Some(5000), T0 + 10 * 60 + 59 * 60), Step::Idle { since: T0, notify: false });
254        assert_eq!(w.observe("a", Some(5000), T0 + 10 * 60 + 60 * 60), Step::Idle { since: T0, notify: true }, "an hour after the first note");
255    }
256
257    #[test]
258    fn a_busy_command_is_never_idle() {
259        let mut w = Watch::default();
260        let mut cpu = 1000;
261        for minute in 0..60 {
262            cpu += 20_000; // a compile using a core for a fifth of the minute
263            assert_eq!(w.observe("a", Some(cpu), T0 + minute * 60), Step::Busy, "minute {minute}");
264        }
265    }
266
267    #[test]
268    fn the_scripts_own_heartbeat_is_not_work_but_a_real_burst_is() {
269        let mut w = Watch::default();
270        w.observe("a", Some(1000), T0);
271        // The heartbeat's forks: 30 ms every 20 s is 90 ms a minute.
272        assert!(matches!(w.observe("a", Some(1000 + 900), T0 + 10 * 60), Step::Idle { notify: true, .. }));
273        // Ten seconds of CPU in one minute is a build that woke up.
274        assert_eq!(w.observe("a", Some(1000 + 900 + 10_000), T0 + 11 * 60), Step::Busy);
275        assert_eq!(w.observe("a", Some(1000 + 900 + 10_000), T0 + 12 * 60), Step::Busy, "the wait starts over");
276        assert!(matches!(w.observe("a", Some(1000 + 900 + 10_000), T0 + 21 * 60), Step::Idle { since, notify: true } if since == T0 + 11 * 60));
277    }
278
279    #[test]
280    fn a_child_that_ends_counts_as_activity() {
281        let mut w = Watch::default();
282        w.observe("a", Some(50_000), T0);
283        assert_eq!(w.observe("a", Some(10_000), T0 + 10 * 60), Step::Busy, "the total fell: a process ended");
284    }
285
286    #[test]
287    fn a_new_run_or_an_unreadable_tree_starts_over() {
288        let mut w = Watch::default();
289        w.observe("a", Some(5000), T0);
290        assert!(matches!(w.observe("a", Some(5000), T0 + 10 * 60), Step::Idle { .. }));
291        assert_eq!(w.observe("b", Some(5000), T0 + 11 * 60), Step::Busy, "another holder: not idle for the first one's minutes");
292        assert_eq!(w.observe("b", Some(5000), T0 + 12 * 60), Step::Busy);
293        assert_eq!(w.observe("b", None, T0 + 30 * 60), Step::Busy, "the tree could not be read");
294        assert_eq!(w.observe("b", Some(5000), T0 + 31 * 60), Step::Busy, "and the wait began again");
295    }
296
297    /// A held slot whose heartbeat was last touched at `alive_at` (epoch seconds): the looks below
298    /// pretend to be minutes apart, so the heartbeat is dated after the last of them.
299    fn holder_slot(root: &Path, owner: &str, alive_at: u64) {
300        let dir = root.join("slot");
301        std::fs::create_dir_all(&dir).unwrap();
302        std::fs::write(dir.join("owner"), owner).unwrap();
303        let beat = std::fs::File::create(dir.join("heartbeat")).unwrap();
304        beat.set_modified(std::time::UNIX_EPOCH + Duration::from_secs(alive_at)).unwrap();
305    }
306
307    /// Both the Windows id and the pid are 700: `check` looks for the one this platform uses.
308    const OWNER: &str = "agent=lazo\npid=700\nwinpid=700\ntoken=tok\nstart=1\ncmd=cargo test -p srv\n";
309
310    #[test]
311    fn check_writes_the_idle_note_and_removes_it_when_the_holder_works_again() {
312        let dir = tempfile::tempdir().unwrap();
313        let root = dir.path();
314        let t0 = agentmux_common::time::now_secs_u64();
315        holder_slot(root, OWNER, t0 + 30 * 60);
316        let idle_file = root.join("slot").join("idle");
317        let mut w = Watch::default();
318        let quiet = || vec![p(700, None, 100), p(701, Some(700), 4000)];
319        assert_eq!(check(root, &mut w, t0, quiet), None, "the first look");
320        assert!(!idle_file.exists());
321        let idle = check(root, &mut w, t0 + 11 * 60, quiet).expect("11 minutes with no CPU");
322        assert_eq!((idle.since, idle.notify, idle.holder.agent.as_str()), (t0, true, "lazo"));
323        let text = std::fs::read_to_string(&idle_file).unwrap();
324        assert_eq!(text, format!("token=tok\nidle_since={t0}\n"));
325        let busy = || vec![p(700, None, 100), p(701, Some(700), 90_000)];
326        assert_eq!(check(root, &mut w, t0 + 12 * 60, busy), None);
327        assert!(!idle_file.exists(), "work removes the note");
328    }
329
330    #[test]
331    fn a_free_slot_or_a_holder_that_cannot_be_watched_is_left_alone() {
332        let dir = tempfile::tempdir().unwrap();
333        let root = dir.path();
334        let mut w = Watch::default();
335        let never = || -> Vec<Proc> { panic!("no slot is held: the machine's processes are not listed") };
336        assert_eq!(check(root, &mut w, agentmux_common::time::now_secs_u64(), never), None);
337        holder_slot(root, "agent=lazo\npid=1\ntoken=tok\nstart=1\ncmd=x\n", agentmux_common::time::now_secs_u64());
338        let never = || -> Vec<Proc> { panic!("no usable process id: the processes are not listed") };
339        assert_eq!(check(root, &mut w, agentmux_common::time::now_secs_u64(), never), None, "a script from before version 9 wrote no Windows id");
340    }
341
342    #[test]
343    fn the_note_names_the_command_and_says_nothing_was_stopped() {
344        let holder = SlotHolder { agent: "lazo".into(), command: "cargo test -p srv\nsecond line".into(), pid: Some(4321), winpid: Some(4321), ..Default::default() };
345        let text = note_text(&Idle { holder, since: T0, notify: true }, T0 + 12 * 60 + 5);
346        assert!(text.contains("12 min") && text.contains("cargo test -p srv second line"), "got {text}");
347        assert!(text.contains("has not stopped it"));
348        assert!(text.contains("process id is 4321"), "the note gives the id to end: {text}");
349    }
350
351    use std::sync::atomic::{AtomicBool, Ordering};
352    use std::sync::Arc;
353
354    use crate::backend::reactive::SenderDelivery;
355
356    /// What the watch finds: `lazo`'s build idle since `T0`, to be told now.
357    fn idle_lazo() -> Idle {
358        let holder = SlotHolder { agent: "lazo".into(), command: "cargo test -p srv".into(), pid: Some(700), winpid: Some(700), ..Default::default() };
359        Idle { holder, since: T0, notify: true }
360    }
361
362    /// A handler with `lazo` registered whose sender does what starting a turn does: spawn a task (the status heartbeat).
363    fn handler_whose_delivery_spawns(ran: &Arc<AtomicBool>) -> ReactiveHandler {
364        let handler = ReactiveHandler::new();
365        let ran = ran.clone();
366        handler.set_message_sender(Arc::new(move |_block: &str, _text: &str, _inline: &[serde_json::Value], _origin: &crate::backend::message_origin::MessageOrigin, _expires: Option<i64>| {
367            let ran = ran.clone();
368            tokio::spawn(async move { ran.store(true, Ordering::SeqCst) });
369            Ok(SenderDelivery::Delivered)
370        }));
371        handler.register_agent("lazo", "block1", None).unwrap();
372        handler
373    }
374
375    fn wait_for(flag: &AtomicBool) -> bool {
376        for _ in 0..200 {
377            if flag.load(Ordering::SeqCst) {
378                return true;
379            }
380            std::thread::sleep(Duration::from_millis(25));
381        }
382        false
383    }
384
385    /// #2577. The watch's thread has no Tokio runtime and the note starts a turn, which spawns a task: that panicked under
386    /// the handler lock on 2026-11-15 and stopped all agent messaging on the machine.
387    #[test]
388    fn the_idle_note_reaches_an_agent_between_turns_from_a_thread_with_no_runtime() {
389        let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(1).enable_all().build().unwrap();
390        let ran = Arc::new(AtomicBool::new(false));
391        let handler = handler_whose_delivery_spawns(&ran);
392
393        // Without the runtime the delivery panics: this is what the watch did.
394        let without = std::thread::scope(|s| s.spawn(|| handler.deliver_system_note("lazo", "[AgentMux] idle")).join());
395        assert!(without.is_err(), "a delivery that spawns, on a thread with no runtime, panics");
396        assert!(!ran.load(Ordering::SeqCst));
397
398        // The same delivery through `tell_holder` runs the task, and the handler works after both.
399        let rt = runtime.handle().clone();
400        std::thread::scope(|s| s.spawn(|| tell_holder(&rt, &handler, &idle_lazo(), T0 + 11 * 60)).join()).expect("the watch's thread does not panic");
401        assert!(wait_for(&ran), "the task the delivery spawned ran on the runtime");
402        assert_eq!(handler.list_agents().len(), 1, "messaging works");
403        assert!(handler.get_audit_log(5).iter().any(|e| e.success), "and the note was audited as delivered");
404    }
405
406    #[test]
407    fn a_delivery_that_panics_costs_the_watch_only_that_note() {
408        let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(1).enable_all().build().unwrap();
409        let handler = ReactiveHandler::new();
410        handler.set_message_sender(Arc::new(|_: &str, _: &str, _: &[serde_json::Value], _: &crate::backend::message_origin::MessageOrigin, _: Option<i64>| -> Result<SenderDelivery, String> {
411            panic!("a panic in the controller's delivery")
412        }));
413        handler.register_agent("lazo", "block1", None).unwrap();
414        let rt = runtime.handle().clone();
415        std::thread::scope(|s| s.spawn(|| tell_holder(&rt, &handler, &idle_lazo(), T0 + 11 * 60)).join()).expect("tell_holder keeps the panic to itself");
416        assert_eq!(handler.list_agents().len(), 1, "and the handler still answers");
417    }
418}