Skip to main content

agentmux_srv_core/backend/process_tracker/
scan.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Finding an agent's processes in the process table, by the env tag they
5//! inherit. Two uses:
6//!
7//! - [`tagged`], on every OS: after a teardown, what still carries the tag got
8//!   out of the agent's tracker, and is reported (`agent_teardown`).
9//! - [`ScanTracker`]: the best-effort tracker where the OS can't hold the
10//!   tree: macOS (no cgroups), Linux without a delegated cgroup, and Windows
11//!   when a Job Object can't be created.
12//!
13//! An agent's processes are:
14//!
15//! - every descendant of the processes assigned to it (its CLI), and
16//! - every process carrying its `AGENTMUX_BLOCKID` in its environment, which
17//!   whatever the agent starts inherits, `setsid` daemons and orphans
18//!   reparented to init or launchd included, plus their descendants.
19//!
20//! A process that cleared its environment after leaving the tree is missed;
21//! hence `BestEffort`. See
22//! `docs/analysis/agent-spawned-process-tracking-2026-10-07.md` §6.3.
23
24use std::collections::{HashMap, HashSet};
25use std::ffi::OsString;
26use std::sync::{Arc, Mutex};
27
28use super::{TrackedProcess, TrackerHandle, TrackingConfidence};
29
30/// A process-table snapshot shared by every scan tracker, refreshed at most
31/// this often: the 2 s poll of N agents costs one OS scan, not N.
32const SNAPSHOT_TTL: std::time::Duration = std::time::Duration::from_millis(500);
33
34struct Snapshot {
35    sys: sysinfo::System,
36    at: Option<std::time::Instant>,
37}
38
39static SNAPSHOT: Mutex<Option<Snapshot>> = Mutex::new(None);
40
41/// Run `f` over a snapshot of the process table, environments and command
42/// lines included, taken no earlier than `after` (when given) and no older
43/// than [`SNAPSHOT_TTL`]. Callers waiting on the lock share the scan the
44/// first of them takes.
45fn with_snapshot<T>(after: Option<std::time::Instant>, f: impl FnOnce(&sysinfo::System) -> T) -> T {
46    let mut guard = SNAPSHOT.lock().unwrap_or_else(|e| e.into_inner());
47    let snap = guard.get_or_insert_with(|| Snapshot { sys: sysinfo::System::new(), at: None });
48    let stale = match snap.at {
49        None => true,
50        Some(t) => after.is_some_and(|a| t < a) || t.elapsed() >= SNAPSHOT_TTL,
51    };
52    if stale {
53        // Stamped with when the scan STARTED: a process spawned while it ran
54        // may be missing from it, so it must not satisfy a later `after`.
55        let started = std::time::Instant::now();
56        snap.sys.refresh_processes_specifics(
57            sysinfo::ProcessesToUpdate::All,
58            true,
59            // `nothing()` still reads every thread of every process (sysinfo's
60            // "tasks"); the scan reads only process-level fields.
61            sysinfo::ProcessRefreshKind::nothing()
62                .without_tasks()
63                .with_cmd(sysinfo::UpdateKind::Always)
64                .with_environ(sysinfo::UpdateKind::Always)
65                .with_memory(),
66        );
67        snap.at = Some(started);
68    }
69    f(&snap.sys)
70}
71
72/// Is `p` the process recorded as started at `started_ms`? A PID the OS has
73/// reused for another process is not (start times are whole seconds).
74fn same_process(started_ms: u64, p: &sysinfo::Process) -> bool {
75    started_ms.abs_diff(p.start_time() * 1000) <= 1000
76}
77
78fn is_root(roots: &HashMap<u32, u64>, pid: u32, p: &sysinfo::Process) -> bool {
79    roots.get(&pid).is_some_and(|started| same_process(*started, p))
80}
81
82/// The members of one agent's tree in `sys`: its live `roots` (PID → start
83/// time) and every process whose environment holds `tag`
84/// (`AGENTMUX_BLOCKID=<block>`), then all their descendants. Never srv itself.
85fn members_in(sys: &sysinfo::System, roots: &HashMap<u32, u64>, tag: &OsString) -> Vec<TrackedProcess> {
86    let me = std::process::id();
87    let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
88    for (pid, p) in sys.processes() {
89        if let Some(parent) = p.parent() {
90            children.entry(parent.as_u32()).or_default().push(pid.as_u32());
91        }
92    }
93    let mut set: Vec<u32> = sys
94        .processes()
95        .iter()
96        .filter(|(_, p)| p.status() != sysinfo::ProcessStatus::Zombie)
97        .filter(|(pid, p)| is_root(roots, pid.as_u32(), p) || p.environ().iter().any(|e| e == tag))
98        .map(|(pid, _)| pid.as_u32())
99        .collect();
100    let mut seen: HashSet<u32> = set.iter().copied().collect();
101    let mut i = 0;
102    while i < set.len() {
103        for c in children.get(&set[i]).into_iter().flatten() {
104            let zombie = sys.process(sysinfo::Pid::from_u32(*c)).is_some_and(|p| p.status() == sysinfo::ProcessStatus::Zombie);
105            if !zombie && seen.insert(*c) {
106                set.push(*c);
107            }
108        }
109        i += 1;
110    }
111    set.into_iter()
112        .filter(|pid| *pid != me && *pid > 1)
113        .filter_map(|pid| sys.process(sysinfo::Pid::from_u32(pid)).map(|p| (pid, p)))
114        .map(|(pid, p)| {
115            let cmd: Vec<String> = p.cmd().iter().map(|a| a.to_string_lossy().into_owned()).collect();
116            TrackedProcess {
117                pid,
118                command: if cmd.is_empty() { p.name().to_string_lossy().into_owned() } else { cmd.join(" ") },
119                rss_bytes: p.memory(),
120                started_at_ms: p.start_time() * 1000,
121                parent_pid: p.parent().map(|pp| pp.as_u32()),
122                exe: cmd.first().cloned().unwrap_or_else(|| p.name().to_string_lossy().into_owned()),
123            }
124        })
125        .collect()
126}
127
128/// Ask `pid` to exit. `false` where there is no such signal (Windows: the
129/// agent side runs without a console, so no CTRL_BREAK).
130#[cfg(unix)]
131fn ask_to_exit(pid: u32) -> bool {
132    // SAFETY: kill(2) with a pid from the process table and a constant signal.
133    unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) == 0 }
134}
135
136#[cfg(windows)]
137fn ask_to_exit(_pid: u32) -> bool {
138    false
139}
140
141#[cfg(unix)]
142fn kill_now(pid: u32) {
143    // SAFETY: kill(2) with a pid from the process table and a constant signal.
144    unsafe {
145        libc::kill(pid as libc::pid_t, libc::SIGKILL);
146    }
147}
148
149#[cfg(windows)]
150fn kill_now(pid: u32) {
151    use windows_sys::Win32::Foundation::CloseHandle;
152    use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
153    // SAFETY: a handle opened, used and closed here.
154    unsafe {
155        let h = OpenProcess(PROCESS_TERMINATE, 0, pid);
156        if !h.is_null() {
157            TerminateProcess(h, 1);
158            CloseHandle(h);
159        }
160    }
161}
162
163/// The env entry that marks a block's processes.
164pub fn block_tag(block_id: &str) -> OsString {
165    OsString::from(format!("AGENTMUX_BLOCKID={block_id}"))
166}
167
168/// Every live process tagged with `block_id` (and its descendants), from a
169/// fresh scan. What a teardown reports as having escaped its tracker.
170pub fn tagged(block_id: &str) -> Vec<TrackedProcess> {
171    with_snapshot(Some(std::time::Instant::now()), |sys| members_in(sys, &HashMap::new(), &block_tag(block_id)))
172}
173
174struct Inner {
175    tag: OsString,
176    /// The processes assigned to the agent (its CLI, one per spawn): PID →
177    /// start time (Unix ms). Pruned as they exit, so a reused PID never
178    /// counts.
179    roots: Mutex<HashMap<u32, u64>>,
180}
181
182impl Inner {
183    fn members(&self, fresh: bool) -> Vec<TrackedProcess> {
184        let after = fresh.then(std::time::Instant::now);
185        with_snapshot(after, |sys| {
186            let mut roots = self.roots.lock().unwrap_or_else(|e| e.into_inner());
187            roots.retain(|pid, started| sys.process(sysinfo::Pid::from_u32(*pid)).is_some_and(|p| same_process(*started, p)));
188            members_in(sys, &roots, &self.tag)
189        })
190    }
191
192    /// SIGKILL every member, leaves first, again until none is left (a
193    /// member may fork between the scan and the signal).
194    fn kill_all(&self) {
195        for _ in 0..4 {
196            let members = self.members(true);
197            if members.is_empty() {
198                return;
199            }
200            for p in members.iter().rev() {
201                kill_now(p.pid);
202            }
203            std::thread::sleep(std::time::Duration::from_millis(30));
204        }
205    }
206}
207
208/// One agent's best-effort tracker.
209pub struct ScanTracker {
210    inner: Arc<Inner>,
211}
212
213impl ScanTracker {
214    pub fn new(block_id: &str) -> Self {
215        Self { inner: Arc::new(Inner { tag: block_tag(block_id), roots: Mutex::new(HashMap::new()) }) }
216    }
217}
218
219impl TrackerHandle for ScanTracker {
220    fn assign_process(&self, pid: u32) -> Result<(), String> {
221        // Its start time, from a fresh scan: recorded with the PID so a later
222        // process reusing the PID is not taken for it.
223        let started = with_snapshot(Some(std::time::Instant::now()), |sys| {
224            sys.process(sysinfo::Pid::from_u32(pid)).map(|p| p.start_time() * 1000)
225        });
226        let Some(started) = started else {
227            return Err(format!("pid {pid} is not running"));
228        };
229        self.inner.roots.lock().unwrap_or_else(|e| e.into_inner()).insert(pid, started);
230        Ok(())
231    }
232
233    fn list_members(&self) -> Vec<TrackedProcess> {
234        self.inner.members(false)
235    }
236
237    fn kill_tree(&self) {
238        self.inner.kill_all();
239    }
240
241    fn kill_pid(&self, pid: u32) -> bool {
242        if !self.inner.members(true).iter().any(|p| p.pid == pid) {
243            return false;
244        }
245        kill_now(pid);
246        true
247    }
248
249    fn confidence(&self) -> TrackingConfidence {
250        TrackingConfidence::BestEffort
251    }
252
253    fn terminate(&self) -> bool {
254        let mut asked = false;
255        for p in self.inner.members(true) {
256            asked |= ask_to_exit(p.pid);
257        }
258        asked
259    }
260
261    fn member_count(&self) -> usize {
262        self.inner.members(true).len()
263    }
264}
265
266impl Drop for ScanTracker {
267    /// The agent is gone: end what it left. Off the caller's thread, since a
268    /// scan takes tens of milliseconds and the caller may be async.
269    fn drop(&mut self) {
270        let inner = Arc::clone(&self.inner);
271        std::thread::spawn(move || inner.kill_all());
272    }
273}
274
275#[cfg(all(test, unix))]
276mod tests {
277    use super::*;
278
279    fn spawn(script: &str, block_id: Option<&str>) -> std::process::Child {
280        let mut cmd = std::process::Command::new("sh");
281        cmd.args(["-c", script]);
282        if let Some(id) = block_id {
283            cmd.env("AGENTMUX_BLOCKID", id);
284        }
285        cmd.spawn().expect("spawn sh")
286    }
287
288    fn wait_for(mut f: impl FnMut() -> bool) -> bool {
289        let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
290        while !f() {
291            if std::time::Instant::now() >= until {
292                return false;
293            }
294            std::thread::sleep(std::time::Duration::from_millis(30));
295        }
296        true
297    }
298
299    fn commands(t: &ScanTracker) -> Vec<String> {
300        t.inner.members(true).into_iter().map(|p| p.command).collect()
301    }
302
303    /// The tag finds a detached process (a double fork, so reparented to
304    /// init or launchd once its shell exits; `setsid` isn't on every Unix),
305    /// and `kill_tree` ends it.
306    #[test]
307    fn a_detached_tagged_process_is_found_and_killed() {
308        let block = format!("scan-test-detached-{}", std::process::id());
309        let tracker = ScanTracker::new(&block);
310        let mut sh = spawn("(sleep 4001 >/dev/null 2>&1 < /dev/null &)", Some(&block));
311        let _ = sh.wait();
312        let found = || commands(&tracker).iter().any(|c| c.contains("4001"));
313        assert!(wait_for(found), "members: {:?}; tagged: {:?}", commands(&tracker), tagged(&block));
314        tracker.kill_tree();
315        assert!(wait_for(|| commands(&tracker).is_empty()), "left: {:?}", commands(&tracker));
316    }
317
318    /// A scan asked for "after now" sees a process spawned just before the
319    /// call, even while other threads keep the shared snapshot busy (a scan
320    /// that started before the spawn but finished after it doesn't count).
321    #[test]
322    fn a_fresh_scan_sees_a_just_spawned_process_under_concurrent_scans() {
323        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
324        let busy: Vec<_> = (0..6)
325            .map(|_| {
326                let stop = Arc::clone(&stop);
327                std::thread::spawn(move || {
328                    while !stop.load(std::sync::atomic::Ordering::Relaxed) {
329                        let _ = tagged("scan-test-busy-nothing");
330                        std::thread::sleep(std::time::Duration::from_micros(200));
331                    }
332                })
333            })
334            .collect();
335        let tracker = ScanTracker::new(&format!("scan-test-race-{}", std::process::id()));
336        for _ in 0..200 {
337            let mut child = spawn("exec sleep 4041", None);
338            let assigned = tracker.assign_process(child.id());
339            let _ = child.kill();
340            let _ = child.wait();
341            assert!(assigned.is_ok(), "{assigned:?}");
342        }
343        stop.store(true, std::sync::atomic::Ordering::Relaxed);
344        for t in busy {
345            let _ = t.join();
346        }
347    }
348
349    /// A root that exited is forgotten: a later process reusing its PID is
350    /// not taken for the agent's.
351    #[test]
352    fn an_exited_root_is_pruned_and_its_pid_not_trusted() {
353        let block = format!("scan-test-prune-{}", std::process::id());
354        let tracker = ScanTracker::new(&block);
355        let mut root = spawn("exec sleep 4031", None);
356        tracker.assign_process(root.id()).unwrap();
357        assert!(wait_for(|| tracker.member_count() == 1));
358        let _ = root.kill();
359        let _ = root.wait();
360        assert!(wait_for(|| tracker.member_count() == 0));
361        assert!(tracker.inner.roots.lock().unwrap().is_empty(), "the exited root was pruned");
362        assert!(tracker.assign_process(root.id()).is_err(), "a PID that isn't running can't be assigned");
363    }
364
365    /// Descendants of an assigned root count even without the tag (a
366    /// process that cleared its environment), and processes of other blocks
367    /// don't.
368    #[test]
369    fn roots_descendants_count_and_other_blocks_do_not() {
370        let block = format!("scan-test-roots-{}", std::process::id());
371        let tracker = ScanTracker::new(&block);
372        let mut root = spawn("env -i sleep 4011 & sleep 4012; wait", None);
373        tracker.assign_process(root.id()).unwrap();
374        let mut other = spawn("sleep 4013", Some("some-other-block"));
375        assert!(wait_for(|| commands(&tracker).iter().any(|c| c == "sleep 4011")), "{:?}", commands(&tracker));
376        assert!(!commands(&tracker).iter().any(|c| c == "sleep 4013"), "another block's process is not a member");
377        tracker.terminate();
378        assert!(wait_for(|| tracker.member_count() == 0), "left: {:?}", commands(&tracker));
379        let _ = root.wait();
380        let _ = other.kill();
381        let _ = other.wait();
382    }
383
384    /// Dropping the tracker (the agent's block is gone) ends what it left.
385    #[test]
386    fn drop_kills_what_is_left() {
387        let block = format!("scan-test-drop-{}", std::process::id());
388        let mut sh = spawn("trap '' TERM; (sleep 4021 >/dev/null 2>&1 < /dev/null &)", Some(&block));
389        let _ = sh.wait();
390        let tracker = ScanTracker::new(&block);
391        assert!(wait_for(|| tracker.member_count() == 1));
392        drop(tracker);
393        assert!(wait_for(|| tagged(&block).is_empty()), "left: {:?}", tagged(&block));
394    }
395}