Skip to main content

agentmux_bashwrap/
idle_gate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Is a command that has printed nothing for the idle timeout stuck, or busy?
5//!
6//! The idle kill exists for a command stuck waiting for input that never
7//! comes: a pager (`less`) in the PTY
8//! (docs/retro/RETRO_BASHWRAP_PAGER_HANG_LEAK_2026_07_14.md). But a build or
9//! test run with its output sent to a file is silent too, and it was killed in
10//! the middle of its work (seen 2026-10-17, `cargo test > log`). A stuck
11//! command uses no CPU and starts nothing; a busy one does. So when the
12//! timeout is reached, the gate looks at the command's process tree twice,
13//! a probe window apart: CPU used or a new process means busy, and the
14//! timeout starts over; nothing means stuck, and the command is killed as
15//! before.
16
17use std::collections::BTreeMap;
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, Instant};
20
21use tokio::sync::oneshot;
22
23use agentmux_procstats::{ProcInfo, ProcKey};
24
25/// The longest probe window: how much later than the idle timeout a stuck
26/// command is killed.
27const PROBE_MAX: Duration = Duration::from_secs(30);
28
29/// What the gate says when the command has been silent for the idle timeout.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub(crate) enum Verdict {
32    /// Still looking: ask again on the next tick.
33    Probing,
34    /// It used CPU or started a process: restart the idle clock.
35    Busy,
36    /// It did neither: kill it.
37    Stuck,
38}
39
40pub(crate) struct IdleGate {
41    root: Option<u32>,
42    window: Duration,
43    probe: Option<(Instant, Option<TreeSample>)>,
44}
45
46impl IdleGate {
47    /// `root`: the command's shell process, whose tree is looked at.
48    pub(crate) fn new(root: Option<u32>, idle_timeout: Duration) -> Self {
49        Self { root, window: PROBE_MAX.min(idle_timeout / 2), probe: None }
50    }
51
52    /// The command printed something: any probe is moot.
53    pub(crate) fn reset(&mut self) {
54        self.probe = None;
55    }
56
57    /// On a tick once the command has been silent for the idle timeout:
58    /// whether it is stuck and should be killed. A busy one gets
59    /// `last_activity` restarted, so it has a whole timeout again.
60    pub(crate) fn stuck(&mut self, last_activity: &mut Instant) -> bool {
61        match self.check() {
62            Verdict::Probing => false,
63            Verdict::Busy => {
64                tracing::info!(target: "bashwrap", "silent for the idle timeout but busy (CPU or new processes); not killing");
65                *last_activity = Instant::now();
66                false
67            }
68            Verdict::Stuck => true,
69        }
70    }
71
72    /// Called on each tick once the command has been silent for the idle
73    /// timeout. A tree that can't be read counts as stuck, as before the gate.
74    pub(crate) fn check(&mut self) -> Verdict {
75        let Some((since, before)) = &self.probe else {
76            self.probe = Some((Instant::now(), self.root.and_then(sample)));
77            return Verdict::Probing;
78        };
79        if since.elapsed() < self.window {
80            return Verdict::Probing;
81        }
82        let after = self.root.and_then(sample);
83        let verdict = match (before, &after) {
84            (Some(b), Some(a)) if busy(b, a, self.window) => Verdict::Busy,
85            _ => Verdict::Stuck,
86        };
87        self.probe = None;
88        verdict
89    }
90}
91
92/// The pipe path's idle watcher: every 200 ms, the time since the last byte
93/// either stream read (`activity`); past `idle_timeout`, the gate decides, and
94/// a stuck command gets `idle_tx`. The look at the tree is a blocking
95/// snapshot, so it runs off the async runtime.
96pub(crate) async fn watch(
97    activity: Arc<Mutex<Instant>>,
98    root: Option<u32>,
99    idle_timeout: Duration,
100    idle_tx: oneshot::Sender<()>,
101) {
102    let mut gate = Some(IdleGate::new(root, idle_timeout));
103    loop {
104        tokio::time::sleep(Duration::from_millis(200)).await;
105        let mut last = *activity.lock().unwrap_or_else(|e| e.into_inner());
106        let Some(mut g) = gate.take() else { return };
107        if last.elapsed() < idle_timeout {
108            g.reset();
109            gate = Some(g);
110            continue;
111        }
112        let Ok((stuck, g, last)) = tokio::task::spawn_blocking(move || (g.stuck(&mut last), g, last)).await else {
113            let _ = idle_tx.send(());
114            return;
115        };
116        if stuck {
117            let _ = idle_tx.send(());
118            return;
119        }
120        *activity.lock().unwrap_or_else(|e| e.into_inner()) = last;
121        gate = Some(g);
122    }
123}
124
125/// Each process of a tree, by key, with the CPU it had used.
126#[derive(Debug, Clone, Default, PartialEq, Eq)]
127pub(crate) struct TreeSample(BTreeMap<ProcKey, u64>);
128
129fn sample(root: u32) -> Option<TreeSample> {
130    let procs = agentmux_procstats::snapshot().ok()?;
131    Some(tree_sample(&procs, root))
132}
133
134/// `root` and every process descended from it.
135fn tree_sample(procs: &[ProcInfo], root: u32) -> TreeSample {
136    let mut out = BTreeMap::new();
137    let Some(top) = procs.iter().find(|p| p.pid == root) else { return TreeSample(out) };
138    let mut stack = vec![top];
139    while let Some(p) = stack.pop() {
140        if out.insert(p.key(), p.cpu_ns.unwrap_or(0)).is_some() {
141            continue;
142        }
143        stack.extend(procs.iter().filter(|c| c.is_child_of(p)));
144    }
145    TreeSample(out)
146}
147
148/// Busy: a process that wasn't there before, or one that used at least 1% of
149/// a core over the window (at least 10 ms).
150fn busy(before: &TreeSample, after: &TreeSample, window: Duration) -> bool {
151    let threshold = (window.as_nanos() / 100).max(10_000_000) as u64;
152    after.0.iter().any(|(key, &cpu)| match before.0.get(key) {
153        None => true,
154        Some(&was) => cpu.saturating_sub(was) >= threshold,
155    })
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    fn proc(pid: u32, ppid: Option<u32>, cpu_ms: u64) -> ProcInfo {
163        ProcInfo {
164            pid,
165            ppid,
166            start_key: pid as u64,
167            started_at_ms: Some(pid as u64),
168            name: format!("p{pid}"),
169            cpu_ns: Some(cpu_ms * 1_000_000),
170            mem_private: None,
171            mem_resident: None,
172            mem_commit: None,
173        }
174    }
175
176    #[test]
177    fn the_tree_is_the_root_and_its_descendants_only() {
178        let procs = [proc(10, Some(1), 0), proc(11, Some(10), 0), proc(12, Some(11), 0), proc(20, Some(1), 0)];
179        let pids: Vec<u32> = tree_sample(&procs, 10).0.keys().map(|k| k.pid).collect();
180        assert_eq!(pids, vec![10, 11, 12]);
181        assert!(tree_sample(&procs, 99).0.is_empty(), "a root that's gone has no tree");
182    }
183
184    #[test]
185    fn cpu_or_a_new_process_is_busy_and_nothing_is_stuck() {
186        let window = Duration::from_secs(30);
187        let before = tree_sample(&[proc(10, None, 100), proc(11, Some(10), 0)], 10);
188        // A pager: the same processes, no CPU.
189        assert!(!busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 0)], 10), window));
190        // Under 1% of a core over 30 s (300 ms) is idle noise.
191        assert!(!busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 200)], 10), window));
192        // A compiler: CPU.
193        assert!(busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 5_000)], 10), window));
194        // cargo starting the next rustc: a new process.
195        assert!(busy(&before, &tree_sample(&[proc(10, None, 100), proc(12, Some(10), 0)], 10), window));
196    }
197
198    #[test]
199    fn the_gate_probes_once_then_decides() {
200        // No root to look at: after the window, stuck, as before the gate.
201        let mut gate = IdleGate::new(None, Duration::from_millis(40));
202        assert_eq!(gate.check(), Verdict::Probing);
203        assert_eq!(gate.check(), Verdict::Probing, "inside the window");
204        std::thread::sleep(Duration::from_millis(25));
205        assert_eq!(gate.check(), Verdict::Stuck);
206        // Output in between starts the probe over.
207        assert_eq!(gate.check(), Verdict::Probing);
208        gate.reset();
209        assert_eq!(gate.check(), Verdict::Probing);
210    }
211
212    #[test]
213    fn the_probe_window_is_at_most_half_the_timeout() {
214        assert_eq!(IdleGate::new(None, Duration::from_secs(600)).window, PROBE_MAX);
215        assert_eq!(IdleGate::new(None, Duration::from_secs(1)).window, Duration::from_millis(500));
216    }
217
218    /// A command that prints nothing while it works (a build with its output
219    /// in a file) is not killed: here 4 s of a busy loop, silent, against a
220    /// 1 s idle timeout. A stuck one still is (`bash_wrap`'s idle-kill tests).
221    mod end_to_end {
222        use crate::bash_wrap::{locate_bash, run_via_pipes, run_via_pty, Args};
223        use crate::cwd_state::CWD_STATE_FILE_OVERRIDE_ENV;
224        use crate::test_env_lock::{unique_temp_dir, EnvVarGuard, ENV_LOCK};
225        use std::sync::Arc;
226        use std::time::Duration;
227
228        const BUSY_AND_SILENT: &str = "end=$((SECONDS+4)); while [ $SECONDS -lt $end ]; do :; done; echo finished";
229
230        fn args(tool: &str) -> Args {
231            Args { tool_id: tool.into(), b64_cmd: String::new(), block_id: None, declared_background: false, agent: None, agent_unknown: false }
232        }
233
234        #[tokio::test]
235        async fn a_silent_but_busy_command_finishes_through_pipes() {
236            let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
237            let scratch = unique_temp_dir("idle-busy-pipes");
238            let _state = EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, scratch.join("s.cwd").to_str().unwrap());
239            let _idle = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
240            let bash = locate_bash().expect("bash");
241            let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
242            let code = tokio::time::timeout(
243                Duration::from_secs(30),
244                run_via_pipes(&args("idle-busy-pipes"), BUSY_AND_SILENT, None, buffered.clone(), &bash),
245            )
246            .await
247            .expect("finishes")
248            .expect("runs");
249            let out = String::from_utf8_lossy(&buffered.lock().await).into_owned();
250            let _ = std::fs::remove_dir_all(&scratch);
251            assert_eq!(code, 0, "{out}");
252            assert!(out.contains("finished"), "{out}");
253            assert!(!out.contains("idle timeout"), "{out}");
254        }
255
256        #[tokio::test]
257        async fn a_silent_but_busy_command_finishes_in_a_pty() {
258            let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
259            let scratch = unique_temp_dir("idle-busy-pty");
260            let _state = EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, scratch.join("s.cwd").to_str().unwrap());
261            let _idle = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
262            let bash = locate_bash().expect("bash");
263            let size = portable_pty::PtySize { rows: 24, cols: 80, pixel_width: 0, pixel_height: 0 };
264            let Ok(pair) = portable_pty::native_pty_system().openpty(size) else {
265                eprintln!("skipping: PTY unavailable in this environment");
266                return;
267            };
268            let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
269            let code = tokio::time::timeout(
270                Duration::from_secs(30),
271                run_via_pty(&args("idle-busy-pty"), BUSY_AND_SILENT, None, buffered.clone(), &bash, pair),
272            )
273            .await
274            .expect("finishes")
275            .expect("runs");
276            let out = String::from_utf8_lossy(&buffered.lock().await).into_owned();
277            let _ = std::fs::remove_dir_all(&scratch);
278            assert_eq!(code, 0, "{out}");
279            assert!(out.contains("finished"), "{out}");
280            assert!(!out.contains("idle timeout"), "{out}");
281        }
282    }
283}