Skip to main content

agentmux_srv_core/backend/process_tracker/
cgroup_linux.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Linux tracker: one cgroup v2 per agent, under a systemd user scope srv
5//! puts itself in at startup with `Delegate=yes`, so srv may create and
6//! manage cgroups below it.
7//!
8//! A cgroup holds every descendant of what it was given, whatever they do:
9//! `setsid`, double forks and reparenting don't leave it (process groups and
10//! sessions can't hold an agent's tree: Claude Code and bashwrap each start
11//! new sessions). `cgroup.kill` ends all of them at once.
12//! See `docs/analysis/agent-spawned-process-tracking-2026-10-07.md`.
13
14use std::path::{Path, PathBuf};
15
16use super::{TrackedProcess, TrackerHandle, TrackingConfidence};
17
18const CGROUP_FS: &str = "/sys/fs/cgroup";
19
20/// srv's delegated scope directory, or `None` when it couldn't get one (no
21/// cgroup v2, no systemd user manager): trackers then fall back.
22static ROOT: tokio::sync::OnceCell<Option<PathBuf>> = tokio::sync::OnceCell::const_new();
23
24/// The directory per-agent cgroups are created in, once [`init`] succeeded.
25pub fn root() -> Option<&'static Path> {
26    ROOT.get().and_then(|r| r.as_deref())
27}
28
29/// Move srv into its own delegated systemd user scope
30/// (`agentmux-srv-<pid>.scope`). Call once at startup, before any agent
31/// spawns. Idempotent; never fails startup.
32pub async fn init() {
33    ROOT.get_or_init(|| async {
34        match setup().await {
35            Ok(dir) => {
36                tracing::info!(cgroup = %dir.display(), "[process-tracker] agent processes tracked by cgroup");
37                Some(dir)
38            }
39            Err(e) => {
40                tracing::warn!(error = %e, "[process-tracker] no delegated cgroup; agent process tracking falls back");
41                None
42            }
43        }
44    })
45    .await;
46}
47
48async fn setup() -> Result<PathBuf, String> {
49    if !Path::new(CGROUP_FS).join("cgroup.controllers").exists() {
50        return Err("cgroup v2 is not mounted at /sys/fs/cgroup".into());
51    }
52    let unit = format!("agentmux-srv-{}.scope", std::process::id());
53    if !own_cgroup()?.ends_with(&format!("/{unit}")) {
54        start_transient_scope(&unit).await?;
55        let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
56        while !own_cgroup()?.ends_with(&format!("/{unit}")) {
57            if std::time::Instant::now() >= until {
58                return Err(format!("systemd did not move srv into {unit}"));
59            }
60            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
61        }
62    }
63    let dir = Path::new(CGROUP_FS).join(own_cgroup()?.trim_start_matches('/'));
64    // Prove delegation: a child cgroup can be made and removed.
65    let probe = dir.join("probe");
66    std::fs::create_dir(&probe).map_err(|e| format!("create a cgroup in {}: {e}", dir.display()))?;
67    let _ = std::fs::remove_dir(&probe);
68    Ok(dir)
69}
70
71/// This process's cgroup v2 path (`/user.slice/…`).
72fn own_cgroup() -> Result<String, String> {
73    let text = std::fs::read_to_string("/proc/self/cgroup").map_err(|e| format!("read /proc/self/cgroup: {e}"))?;
74    text.lines()
75        .find_map(|l| l.strip_prefix("0::"))
76        .map(str::to_string)
77        .ok_or_else(|| "no cgroup v2 entry in /proc/self/cgroup".into())
78}
79
80/// Ask the user's systemd manager for a transient scope holding this
81/// process, delegated to us (what `systemd-run --user --scope -p
82/// Delegate=yes` does).
83async fn start_transient_scope(unit: &str) -> Result<(), String> {
84    use zbus::zvariant::Value;
85    let conn = zbus::Connection::session().await.map_err(|e| format!("session bus: {e}"))?;
86    let props: Vec<(&str, Value)> = vec![
87        ("Description", Value::from("AgentMux srv and the agents it runs")),
88        ("PIDs", Value::from(vec![std::process::id()])),
89        ("Delegate", Value::from(true)),
90    ];
91    let aux: Vec<(&str, Vec<(&str, Value)>)> = Vec::new();
92    conn.call_method(
93        Some("org.freedesktop.systemd1"),
94        "/org/freedesktop/systemd1",
95        Some("org.freedesktop.systemd1.Manager"),
96        "StartTransientUnit",
97        &(unit, "fail", props, aux),
98    )
99    .await
100    .map_err(|e| format!("StartTransientUnit {unit}: {e}"))?;
101    Ok(())
102}
103
104/// One agent's cgroup.
105pub struct CgroupTracker {
106    dir: PathBuf,
107}
108
109impl CgroupTracker {
110    pub fn new(root: &Path, block_id: &str) -> Result<Self, String> {
111        let name: String = block_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect();
112        let dir = root.join(format!("agent-{name}"));
113        match std::fs::create_dir(&dir) {
114            Ok(()) => {}
115            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
116            Err(e) => return Err(format!("create {}: {e}", dir.display())),
117        }
118        Ok(Self { dir })
119    }
120
121    fn pids(&self) -> Vec<u32> {
122        pids_in(&self.dir)
123    }
124}
125
126fn pids_in(dir: &Path) -> Vec<u32> {
127    std::fs::read_to_string(dir.join("cgroup.procs"))
128        .unwrap_or_default()
129        .lines()
130        .filter_map(|l| l.trim().parse().ok())
131        .collect()
132}
133
134/// `usage_usec` from a `cpu.stat`.
135fn usage_usec(stat: &str) -> Option<u64> {
136    stat.lines().find_map(|l| l.strip_prefix("usage_usec ")).and_then(|v| v.trim().parse().ok())
137}
138
139fn populated(dir: &Path) -> bool {
140    std::fs::read_to_string(dir.join("cgroup.events"))
141        .map(|t| t.lines().any(|l| l == "populated 1"))
142        .unwrap_or(false)
143}
144
145/// Kill everything in `dir`: `cgroup.kill` (kernel 5.14+), else SIGKILL each
146/// member until none is left.
147fn kill_all(dir: &Path) {
148    if std::fs::write(dir.join("cgroup.kill"), "1").is_ok() {
149        return;
150    }
151    for _ in 0..5 {
152        let pids = pids_in(dir);
153        if pids.is_empty() {
154            return;
155        }
156        for pid in pids {
157            signal(pid, libc::SIGKILL);
158        }
159        std::thread::sleep(std::time::Duration::from_millis(20));
160    }
161}
162
163fn signal(pid: u32, sig: libc::c_int) {
164    // SAFETY: kill(2) with a pid read from cgroup.procs and a constant signal.
165    unsafe {
166        libc::kill(pid as libc::pid_t, sig);
167    }
168}
169
170/// What each of `pids` is, as the process table shows it.
171///
172/// `ProcessRefreshKind::nothing()` is "everything off except tasks": on Linux that
173/// reads every THREAD of every process as well (a `/proc/<pid>/task/<tid>/stat`
174/// each), and an agent's processes are Node apps with dozens. Nothing here reads
175/// thread data, so it is switched off: a 40-thread process lists in 0.43 ms
176/// instead of 10.6 ms, and the listing is called about 13 times a second with 12
177/// agents (SPEC_SRV_PROCESS_LISTING_WITHOUT_THREADS_2026_10_18.md).
178fn describe_pids(pids: &[u32]) -> Vec<TrackedProcess> {
179    let list: Vec<sysinfo::Pid> = pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
180    let mut sys = sysinfo::System::new();
181    sys.refresh_processes_specifics(
182        sysinfo::ProcessesToUpdate::Some(&list),
183        true,
184        sysinfo::ProcessRefreshKind::nothing().without_tasks().with_cmd(sysinfo::UpdateKind::Always).with_memory(),
185    );
186    sys.processes()
187        .iter()
188        .map(|(pid, p)| {
189            let cmd: Vec<String> = p.cmd().iter().map(|a| a.to_string_lossy().into_owned()).collect();
190            TrackedProcess {
191                pid: pid.as_u32(),
192                command: if cmd.is_empty() { p.name().to_string_lossy().into_owned() } else { cmd.join(" ") },
193                rss_bytes: p.memory(),
194                started_at_ms: p.start_time() * 1000,
195                parent_pid: p.parent().map(|pp| pp.as_u32()),
196                exe: cmd.first().cloned().unwrap_or_else(|| p.name().to_string_lossy().into_owned()),
197            }
198        })
199        .collect()
200}
201
202impl TrackerHandle for CgroupTracker {
203    fn assign_process(&self, pid: u32) -> Result<(), String> {
204        std::fs::write(self.dir.join("cgroup.procs"), pid.to_string())
205            .map_err(|e| format!("move pid {pid} into {}: {e}", self.dir.display()))
206    }
207
208    fn list_members(&self) -> Vec<TrackedProcess> {
209        let pids = self.pids();
210        if pids.is_empty() {
211            return Vec::new();
212        }
213        describe_pids(&pids)
214    }
215
216    fn kill_tree(&self) {
217        kill_all(&self.dir);
218    }
219
220    fn kill_pid(&self, pid: u32) -> bool {
221        if !self.pids().contains(&pid) {
222            return false;
223        }
224        signal(pid, libc::SIGKILL);
225        true
226    }
227
228    fn confidence(&self) -> TrackingConfidence {
229        TrackingConfidence::High
230    }
231
232    fn terminate(&self) -> bool {
233        for pid in self.pids() {
234            signal(pid, libc::SIGTERM);
235        }
236        true
237    }
238
239    fn member_count(&self) -> usize {
240        self.pids().len()
241    }
242
243    fn member_pids(&self) -> Vec<u32> {
244        self.pids()
245    }
246
247    /// `cpu.stat`'s `usage_usec` exists whether or not the cpu controller is
248    /// enabled, and counts members that have exited.
249    fn cpu_time_ns(&self) -> Option<u64> {
250        let stat = std::fs::read_to_string(self.dir.join("cpu.stat")).ok()?;
251        usage_usec(&stat).map(|us| us * 1000)
252    }
253
254    fn spawn_target(&self) -> Option<PathBuf> {
255        Some(self.dir.join("cgroup.procs"))
256    }
257}
258
259impl Drop for CgroupTracker {
260    /// The agent is gone: end whatever it left and remove its cgroup, which
261    /// the kernel allows only once it's empty.
262    fn drop(&mut self) {
263        let dir = self.dir.clone();
264        kill_all(&dir);
265        std::thread::spawn(move || {
266            let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
267            while populated(&dir) && std::time::Instant::now() < until {
268                std::thread::sleep(std::time::Duration::from_millis(20));
269            }
270            if let Err(e) = std::fs::remove_dir(&dir) {
271                tracing::warn!(cgroup = %dir.display(), error = %e, "[process-tracker] could not remove an agent's cgroup");
272            }
273        });
274    }
275}
276
277/// Make a child join `procs` (a `cgroup.procs` file) before it execs, so it
278/// is tracked before it runs any code of its own and before it can fork.
279pub fn join_before_exec(cmd: &mut tokio::process::Command, procs: PathBuf) {
280    let Ok(path) = std::ffi::CString::new(procs.into_os_string().into_encoded_bytes()) else { return };
281    // SAFETY: the hook only calls open/write/close, which are
282    // async-signal-safe, on memory allocated before the fork.
283    unsafe {
284        cmd.pre_exec(move || {
285            let fd = libc::open(path.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC);
286            if fd >= 0 {
287                // "0" moves the writing process: this child.
288                libc::write(fd, b"0".as_ptr().cast(), 1);
289                libc::close(fd);
290            }
291            // Failing to join is not fatal: the parent assigns the PID right
292            // after spawn as well.
293            Ok(())
294        });
295    }
296}
297
298/// [`join_before_exec`] for a PTY spawn (portable-pty has no pre-exec hook):
299/// run the command through `sh`, which joins and then `exec`s it, so the
300/// program starts already in the cgroup, as the same process.
301pub fn join_before_exec_pty(cmd: &mut portable_pty::CommandBuilder, procs: PathBuf) {
302    let argv = cmd.get_argv_mut();
303    if argv.is_empty() {
304        return; // the user's default shell: never an agent
305    }
306    let mut wrapped: Vec<std::ffi::OsString> = vec![
307        "/bin/sh".into(),
308        "-c".into(),
309        r#"echo 0 > "$0" 2>/dev/null; exec "$@""#.into(),
310        procs.into_os_string(),
311    ];
312    wrapped.append(argv);
313    *argv = wrapped;
314}
315
316#[cfg(test)]
317mod tests {
318    /// A process is one entry, however many threads it has: the test process
319    /// has a thread per test and a runtime, and still lists exactly once.
320    #[test]
321    fn a_process_with_many_threads_lists_once() {
322        let _threads: Vec<_> = (0..8).map(|_| std::thread::spawn(|| std::thread::sleep(std::time::Duration::from_secs(5)))).collect();
323        let me = std::process::id();
324        let listed = describe_pids(&[me]);
325        let pids: Vec<u32> = listed.iter().map(|p| p.pid).collect();
326        assert_eq!(pids, vec![me], "one entry for this process, not one per thread: {pids:?}");
327    }
328
329    /// Without thread data the listing still says what it always did: the
330    /// command line, the parent, the start time and the memory.
331    #[test]
332    fn the_listing_still_reports_command_parent_start_and_memory() {
333        let mut child = std::process::Command::new("sleep").arg("3077").spawn().unwrap();
334        let pid = child.id();
335        let listed = describe_pids(&[pid]);
336        let _ = child.kill();
337        let _ = child.wait();
338        assert_eq!(listed.len(), 1, "{listed:?}");
339        let p = &listed[0];
340        assert_eq!(p.pid, pid);
341        assert_eq!(p.command, "sleep 3077");
342        assert_eq!(p.exe, "sleep");
343        assert_eq!(p.parent_pid, Some(std::process::id()));
344        assert!(p.rss_bytes > 0, "memory: {}", p.rss_bytes);
345        assert!(p.started_at_ms > 0);
346    }
347
348    use super::*;
349
350    #[test]
351    fn usage_usec_is_read_from_cpu_stat() {
352        let stat = "usage_usec 1234567
353user_usec 1000000
354system_usec 234567
355";
356        assert_eq!(usage_usec(stat), Some(1_234_567));
357        assert_eq!(usage_usec("user_usec 5
358"), None);
359    }
360
361    /// A delegated scope for this test binary, or `None` where there is no
362    /// systemd user manager (CI containers): the tests then skip.
363    async fn test_root() -> Option<&'static Path> {
364        init().await;
365        root()
366    }
367
368    fn sh(script: &str, procs: Option<PathBuf>) -> tokio::process::Child {
369        let mut cmd = tokio::process::Command::new("sh");
370        cmd.args(["-c", script]).kill_on_drop(true);
371        if let Some(p) = procs {
372            join_before_exec(&mut cmd, p);
373        }
374        cmd.spawn().expect("spawn sh")
375    }
376
377    async fn wait_for(mut f: impl FnMut() -> bool) -> bool {
378        let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
379        while !f() {
380            if std::time::Instant::now() >= until {
381                return false;
382            }
383            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
384        }
385        true
386    }
387
388    /// The command lines of the tracker's members, as `list_members` reports them.
389    fn commands(tracker: &CgroupTracker) -> Vec<String> {
390        tracker.list_members().into_iter().map(|p| p.command).collect()
391    }
392
393    /// The launcher's cleanup after srv died (`agent_roots::kill_orphans`):
394    /// `cgroup.kill` ends an agent's CLI and whatever detached from it, and
395    /// leaves the rest of srv's scope alone.
396    #[tokio::test]
397    async fn the_launchers_cleanup_kills_agent_cgroups_only() {
398        let Some(root) = test_root().await else { return };
399        // A scope of its own inside the test's, so other tests' agent
400        // cgroups aren't touched.
401        let scope = root.join(format!("cleanup-{}", std::process::id()));
402        std::fs::create_dir_all(&scope).unwrap();
403        let agent = CgroupTracker::new(&scope, "cli").unwrap();
404        let other = scope.join("other");
405        std::fs::create_dir_all(&other).unwrap();
406        let _cli = sh("setsid sleep 3041 & sleep 3042", agent.spawn_target());
407        let _bystander = sh("exec sleep 3043", Some(other.join("cgroup.procs")));
408        let started = wait_for(|| agent.pids().len() >= 3 && pids_in(&other).len() == 1).await;
409
410        let killed = agentmux_common::agent_roots::kill_agent_cgroups(&scope);
411        let emptied = wait_for(|| agent.pids().is_empty()).await;
412        let bystanders = pids_in(&other).len();
413
414        // Clean up before asserting, so a failure leaves nothing running.
415        let _ = std::fs::write(other.join("cgroup.kill"), "1");
416        wait_for(|| pids_in(&other).is_empty()).await;
417        drop(agent);
418        let _ = std::fs::remove_dir(&other);
419        let _ = std::fs::remove_dir(&scope);
420
421        assert!(started);
422        assert_eq!(killed, 1);
423        assert!(emptied, "the agent cgroup is empty");
424        assert_eq!(bystanders, 1, "the rest of the scope is untouched");
425    }
426
427    /// The case process groups can't hold: a `setsid` daemon, a double
428    /// fork, and a plain child all stay in the agent's cgroup, are listed,
429    /// and end with `kill_tree`.
430    #[tokio::test]
431    async fn every_descendant_is_tracked_and_killed_however_it_detaches() {
432        let Some(root) = test_root().await else {
433            eprintln!("skipped: no delegated cgroup here");
434            return;
435        };
436        let tracker = CgroupTracker::new(root, "test-detaching-descendants").unwrap();
437        let mut child = sh(
438            "setsid sleep 3001 & (sleep 3002 &); sleep 3003 & echo started; wait",
439            tracker.spawn_target(),
440        );
441        // Wait for the commands themselves, not for a member count: four members
442        // are reached while `setsid` has not yet exec'd into `sleep` (it then
443        // reads `setsid sleep 3001`).
444        let expected = ["sleep 3001", "sleep 3002", "sleep 3003"];
445        let all_listed = || {
446            let listed = commands(&tracker);
447            expected.iter().all(|s| listed.iter().any(|c| c == s))
448        };
449        assert!(wait_for(all_listed).await, "listed: {:?}", commands(&tracker));
450        assert!(tracker.member_count() >= 4, "members: {:?}", tracker.pids());
451        tracker.kill_tree();
452        assert!(wait_for(|| !populated(&tracker.dir)).await, "left: {:?}", tracker.pids());
453        let _ = child.wait().await;
454    }
455
456    /// An agent CLI leads its own process group (`place_spawn`) and joins its
457    /// agent cgroup before it runs: the two don't get in each other's way.
458    #[tokio::test]
459    async fn a_group_leader_still_joins_its_cgroup_before_exec() {
460        use std::os::unix::process::CommandExt as _;
461        let Some(root) = test_root().await else { return };
462        let tracker = CgroupTracker::new(root, "group-leader").unwrap();
463        let mut cmd = tokio::process::Command::new("sh");
464        cmd.args(["-c", "sleep 3051 & wait"]).kill_on_drop(true).process_group(0);
465        join_before_exec(&mut cmd, tracker.spawn_target().unwrap());
466        let child = cmd.spawn().expect("spawn sh");
467        let pid = child.id().unwrap();
468        assert!(wait_for(|| tracker.pids().len() >= 2).await, "the CLI and its child are in the agent cgroup");
469        assert_eq!(unsafe { libc::getpgid(pid as i32) }, pid as i32, "and the CLI leads its own group");
470        let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).unwrap();
471        assert!(own.trim().ends_with("/agent-group-leader"), "{own}");
472        drop(child);
473        drop(tracker);
474    }
475
476    /// `terminate` asks politely: a process that exits on SIGTERM is gone
477    /// without a kill.
478    #[tokio::test]
479    async fn terminate_sends_sigterm_to_every_member() {
480        let Some(root) = test_root().await else { return };
481        let tracker = CgroupTracker::new(root, "test-terminate").unwrap();
482        let _child = sh("setsid sleep 3011 & sleep 3012", tracker.spawn_target());
483        // Wait for both sleeps, not for two members: `terminate` signals the
484        // members of the moment, and a `sleep` the shell forks just after it
485        // would outlive it.
486        let both_listed = || {
487            let listed = commands(&tracker);
488            ["sleep 3011", "sleep 3012"].iter().all(|s| listed.iter().any(|c| c == s))
489        };
490        assert!(wait_for(both_listed).await, "listed: {:?}", commands(&tracker));
491        tracker.terminate();
492        assert!(wait_for(|| tracker.member_count() == 0).await, "left: {:?}", tracker.pids());
493    }
494
495    /// Dropping the tracker (the agent's block is gone) ends what's left and
496    /// removes the cgroup.
497    #[tokio::test]
498    async fn drop_kills_what_is_left_and_removes_the_cgroup() {
499        let Some(root) = test_root().await else { return };
500        let tracker = CgroupTracker::new(root, "test-drop").unwrap();
501        let dir = tracker.dir.clone();
502        let _child = sh("trap '' TERM; setsid sleep 3021 & sleep 3022", tracker.spawn_target());
503        assert!(wait_for(|| pids_in(&dir).len() >= 2).await);
504        drop(tracker);
505        assert!(wait_for(|| !dir.exists()).await, "cgroup still there: {:?}", pids_in(&dir));
506    }
507
508    /// A PTY-style spawn wrapped by `join_before_exec_pty` starts in the
509    /// cgroup as the same process, with its own argv.
510    #[tokio::test]
511    async fn a_wrapped_pty_command_joins_before_it_runs() {
512        let Some(root) = test_root().await else { return };
513        let tracker = CgroupTracker::new(root, "test-pty-wrap").unwrap();
514        let mut b = portable_pty::CommandBuilder::new("sleep");
515        b.arg("3041");
516        join_before_exec_pty(&mut b, tracker.spawn_target().unwrap());
517        let argv: Vec<String> = b.get_argv().iter().map(|a| a.to_string_lossy().into_owned()).collect();
518        let mut child = tokio::process::Command::new(&argv[0]).args(&argv[1..]).kill_on_drop(true).spawn().unwrap();
519        let pid = child.id().unwrap();
520        // The wrapper joins the cgroup before it execs, so the member is first
521        // `/bin/sh -c echo 0 > ...` and only then `sleep 3041`: wait for the
522        // exec, in the same pid.
523        let exec_done = || tracker.list_members().first().is_some_and(|p| p.pid == pid && p.command == "sleep 3041");
524        assert!(wait_for(exec_done).await, "members: {:?}", commands(&tracker));
525        assert_eq!(tracker.pids(), vec![pid], "exec'd in place: no child process");
526        tracker.kill_tree();
527        let _ = child.wait().await;
528    }
529
530    /// `assign_process` after spawn tracks a child spawned without the
531    /// pre-exec hook (the PTY path), and `kill_pid` only touches members.
532    #[tokio::test]
533    async fn assign_after_spawn_and_kill_pid_only_members() {
534        let Some(root) = test_root().await else { return };
535        let tracker = CgroupTracker::new(root, "test-assign").unwrap();
536        // `exec`, so the shell is the sleep: dash forks a plain `sleep` either
537        // before or after the move below, and the member list would depend on which.
538        let mut child = sh("exec sleep 3031", None);
539        let pid = child.id().unwrap();
540        tracker.assign_process(pid).unwrap();
541        assert_eq!(tracker.pids(), vec![pid]);
542        assert!(!tracker.kill_pid(1), "pid 1 is not a member");
543        assert!(tracker.kill_pid(pid));
544        let _ = child.wait().await;
545        assert!(wait_for(|| tracker.member_count() == 0).await);
546    }
547}