Skip to main content

agentmux_srv_core/backend/
own_instance.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which processes belong to THIS AgentMux instance.
5//!
6//! The commit attribution log (`sysinfo::log_memory_attribution`) used to add up
7//! every process named `agentmux*` on the machine, so a stable install running
8//! beside a `task dev` build, or two channels, were mixed into one number.
9//! An instance is its launcher and everything under it: the launcher starts srv
10//! and the CEF host, and the host starts the GPU, utility and renderer
11//! processes. This module finds that tree from srv's own pid, as a pure
12//! function over a process table so it can be tested without a real one.
13//! docs/specs/SPEC_INSTANCE_MEMORY_ATTRIBUTION_2026_10_18.md
14
15use std::collections::{HashMap, HashSet};
16
17/// One row of the process table.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ProcNode {
20    pub pid: u32,
21    pub parent: Option<u32>,
22    /// Whether the process is named `agentmux*`.
23    pub is_agentmux: bool,
24    /// When it started, unix ms; `None` when unknown. A parent link can be
25    /// stale (on Windows it is never updated and can name a newer process that
26    /// reused the parent's pid), and a parent that started after its child is
27    /// exactly that.
28    pub started_at_ms: Option<u64>,
29}
30
31impl ProcNode {
32    /// Whether `parent` is really this process's parent: the link names its pid
33    /// and, where both start times are known, the parent did not start later
34    /// (the rule `agentmux_procstats::ProcInfo::is_child_of` applies).
35    fn is_child_of(&self, parent: &ProcNode) -> bool {
36        if self.parent != Some(parent.pid) || parent.pid == self.pid {
37            return false;
38        }
39        match (parent.started_at_ms, self.started_at_ms) {
40            (Some(p), Some(c)) => p <= c,
41            _ => true,
42        }
43    }
44}
45
46/// The pids of the instance `self_pid` (srv) belongs to: the topmost `agentmux*`
47/// ancestor reached by walking up from srv (the launcher; srv itself when its
48/// parent isn't AgentMux, as when it is run by hand), and every process below
49/// it. The walk stops at the first parent that isn't `agentmux*`, so the
50/// terminal, `task` or AppImageLauncher that started the instance is not part
51/// of it. Empty when `self_pid` isn't in the table.
52///
53/// Another AgentMux started from inside this one, say an agent running
54/// `task dev` in a pane's shell, is below this instance's root too, but it is
55/// its own instance: an `agentmux*` process whose parent is not `agentmux*`
56/// is a launcher, so it and everything under it are left out.
57///
58/// The table's parent links can be stale (a parent that exited and whose pid
59/// was reused), so the upward walk is bounded by the table's size and a seen
60/// set rather than trusted to end.
61pub fn own_instance_pids(nodes: &[ProcNode], self_pid: u32) -> HashSet<u32> {
62    let by_pid: HashMap<u32, &ProcNode> = nodes.iter().map(|n| (n.pid, n)).collect();
63    let Some(&start) = by_pid.get(&self_pid) else {
64        return HashSet::new();
65    };
66
67    let mut root = start;
68    let mut seen = HashSet::from([start.pid]);
69    while let Some(parent) = root.parent.and_then(|p| by_pid.get(&p).copied()) {
70        if !root.is_child_of(parent) || !parent.is_agentmux || !seen.insert(parent.pid) {
71            break;
72        }
73        root = parent;
74    }
75
76    let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
77    for n in nodes {
78        // Only a link to a parent that could really be the parent.
79        if let Some(parent) = n.parent.and_then(|p| by_pid.get(&p)) {
80            if n.is_child_of(parent) {
81                children.entry(parent.pid).or_default().push(n.pid);
82            }
83        }
84    }
85    let mut own = HashSet::from([root.pid]);
86    let mut queue = vec![root.pid];
87    while let Some(pid) = queue.pop() {
88        let parent_is_agentmux = by_pid.get(&pid).is_some_and(|p| p.is_agentmux);
89        for &child in children.get(&pid).into_iter().flatten() {
90            // A nested launcher: AgentMux started by something that isn't AgentMux.
91            let nested_root = !parent_is_agentmux && by_pid.get(&child).is_some_and(|c| c.is_agentmux);
92            if !nested_root && own.insert(child) {
93                queue.push(child);
94            }
95        }
96    }
97    own
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    fn n(pid: u32, parent: Option<u32>, is_agentmux: bool) -> ProcNode {
105        ProcNode { pid, parent, is_agentmux, started_at_ms: None }
106    }
107
108    fn started(mut node: ProcNode, at_ms: u64) -> ProcNode {
109        node.started_at_ms = Some(at_ms);
110        node
111    }
112
113    /// A stable install (launcher 100) beside a dev build (launcher 200), each
114    /// with srv, a CEF host and a renderer under the host: the case that mixed.
115    fn two_instances() -> Vec<ProcNode> {
116        vec![
117            n(1, None, false),
118            n(100, Some(1), true),
119            n(101, Some(100), true), // stable srv
120            n(102, Some(100), true), // stable cef host
121            n(103, Some(102), true), // stable renderer
122            n(200, Some(1), true),
123            n(201, Some(200), true), // dev srv
124            n(202, Some(200), true), // dev cef host
125            n(203, Some(202), true), // dev renderer
126            n(300, Some(201), false), // a dev agent's shell
127        ]
128    }
129
130    #[test]
131    fn two_instances_side_by_side_are_told_apart_from_srv() {
132        let t = two_instances();
133        assert_eq!(own_instance_pids(&t, 201), HashSet::from([200, 201, 202, 203, 300]));
134        assert_eq!(own_instance_pids(&t, 101), HashSet::from([100, 101, 102, 103]));
135    }
136
137    #[test]
138    fn an_agentmux_started_from_a_pane_of_this_one_is_its_own_instance() {
139        // An agent's shell (300, under srv 201) runs `task dev` (301), which
140        // starts a launcher (400) with its own srv (401) and host (402).
141        let mut t = two_instances();
142        t.extend([
143            n(301, Some(300), false),
144            n(400, Some(301), true),
145            n(401, Some(400), true),
146            n(402, Some(400), true),
147        ]);
148        let outer = own_instance_pids(&t, 201);
149        assert_eq!(outer, HashSet::from([200, 201, 202, 203, 300, 301]));
150        assert!(![400, 401, 402].iter().any(|p| outer.contains(p)), "the nested instance is not the outer one's");
151        // And from the nested srv, only the nested tree.
152        assert_eq!(own_instance_pids(&t, 401), HashSet::from([400, 401, 402]));
153    }
154
155    #[test]
156    fn a_stale_parent_link_to_a_reused_pid_does_not_cross_into_another_instance() {
157        // srv 201's launcher (200) started at t=1000. A process that started
158        // later at t=5000 now has the pid of srv 301's long-gone parent, 400,
159        // and is itself an agentmux* launcher with its own srv: 301's recorded
160        // parent (400) is a reused pid, not its parent.
161        let t = vec![
162            started(n(400, None, true), 5_000), // a NEWER process reusing pid 400
163            started(n(401, Some(400), true), 5_100), // its real child
164            started(n(301, Some(400), true), 1_000), // the stale link: started before 400
165            started(n(302, Some(301), true), 1_100),
166        ];
167        // From 301: the walk up refuses 400 (it started after 301), so 301 is
168        // its own root, with its child 302 and without 400's real tree.
169        assert_eq!(own_instance_pids(&t, 301), HashSet::from([301, 302]));
170        // From 401: its tree is 400 and 401 only; 301 is not 400's child.
171        assert_eq!(own_instance_pids(&t, 401), HashSet::from([400, 401]));
172    }
173
174    #[test]
175    fn a_parent_that_started_first_or_at_the_same_time_is_trusted() {
176        let t = vec![
177            started(n(10, None, true), 1_000),
178            started(n(11, Some(10), true), 1_000),
179            started(n(12, Some(11), true), 2_000),
180        ];
181        assert_eq!(own_instance_pids(&t, 12), HashSet::from([10, 11, 12]));
182    }
183
184    #[test]
185    fn the_same_tree_is_found_from_any_member() {
186        let t = two_instances();
187        assert_eq!(own_instance_pids(&t, 203), own_instance_pids(&t, 201));
188        assert_eq!(own_instance_pids(&t, 200), own_instance_pids(&t, 201));
189    }
190
191    #[test]
192    fn the_walk_up_stops_at_the_first_parent_that_isnt_agentmux() {
193        // An AppImage: AppImageLauncher (not agentmux*) starts the launcher.
194        let t = vec![n(1, None, false), n(50, Some(1), false), n(60, Some(50), true), n(61, Some(60), true)];
195        let own = own_instance_pids(&t, 61);
196        assert_eq!(own, HashSet::from([60, 61]));
197        assert!(!own.contains(&50) && !own.contains(&1));
198    }
199
200    #[test]
201    fn srv_run_by_hand_is_its_own_instance() {
202        let t = vec![n(1, None, false), n(70, Some(1), true), n(71, Some(70), false)];
203        assert_eq!(own_instance_pids(&t, 70), HashSet::from([70, 71]));
204    }
205
206    #[test]
207    fn an_unknown_pid_or_a_missing_parent_is_handled() {
208        let t = two_instances();
209        assert!(own_instance_pids(&t, 9999).is_empty());
210        // The parent exited: srv's link points at a pid that isn't in the table.
211        let orphan = vec![n(80, Some(7777), true), n(81, Some(80), true)];
212        assert_eq!(own_instance_pids(&orphan, 80), HashSet::from([80, 81]));
213    }
214
215    #[test]
216    fn stale_links_that_form_a_cycle_end() {
217        // A reused pid can make a parent link loop back down.
218        let t = vec![n(10, Some(11), true), n(11, Some(10), true), n(12, Some(11), true)];
219        let own = own_instance_pids(&t, 12);
220        assert!(own.contains(&12) && own.len() <= 3);
221    }
222}