Skip to main content

agentmux_procstats/
lib.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-process CPU and memory, read without elevation
5//! (SPEC_TOWER_TASK_MANAGER_PANE_2026_10_08.md §3, §4).
6//!
7//! One [`snapshot`] lists every process this user may see, with what the OS
8//! reports for it:
9//!
10//! | OS | Source | Other users' processes |
11//! |---|---|---|
12//! | Windows | one `NtQuerySystemInformation(SystemProcessInformation)` call | full (no per-process handle is opened) |
13//! | Linux | `/proc/<pid>/stat` + `status` | full, unless `/proc` is mounted `hidepid` |
14//! | macOS | `proc_listallpids` + `proc_pid_rusage` | name and parent only: CPU and memory are `None` |
15//!
16//! Nothing here asks for a privilege: no `SeDebugPrivilege`, no
17//! `task_for_pid`, no `CAP_SYS_PTRACE`. A value the OS won't give us is
18//! `None`, never 0.
19//!
20//! CPU is a cumulative time; [`RateMeter`] turns two samples into a rate.
21
22use std::collections::HashMap;
23use std::hash::Hash;
24use std::time::Instant;
25
26#[cfg(target_os = "linux")]
27mod linux;
28#[cfg(target_os = "linux")]
29use linux as os;
30
31#[cfg(target_os = "macos")]
32mod macos;
33#[cfg(target_os = "macos")]
34use macos as os;
35
36#[cfg(windows)]
37mod windows;
38#[cfg(windows)]
39use windows as os;
40#[cfg(windows)]
41pub use windows::{recent_parents, ParentTable};
42
43#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
44mod os {
45    pub fn snapshot() -> std::io::Result<Vec<super::ProcInfo>> {
46        Err(std::io::Error::new(
47            std::io::ErrorKind::Unsupported,
48            "no process reader for this OS",
49        ))
50    }
51    pub fn command_line(_pid: u32) -> Option<String> {
52        None
53    }
54    pub fn start_key(_pid: u32) -> Option<u64> {
55        None
56    }
57    pub fn write_bytes(_pid: u32) -> Option<u64> {
58        None
59    }
60    pub fn storage_write_bytes(_pid: u32) -> Option<i64> {
61        None
62    }
63    pub fn cpu_count() -> usize {
64        std::thread::available_parallelism()
65            .map(|n| n.get())
66            .unwrap_or(1)
67    }
68}
69
70/// What [`ProcInfo::mem_private`] measures on this OS — the number the OS's
71/// own task manager shows where it has one (spec §4.1).
72#[cfg(windows)]
73pub const MEMORY_METRIC: &str = "private working set";
74#[cfg(target_os = "macos")]
75pub const MEMORY_METRIC: &str = "memory footprint";
76#[cfg(not(any(windows, target_os = "macos")))]
77pub const MEMORY_METRIC: &str = "anonymous resident + swap";
78
79/// One process, as the OS reported it at the moment of the snapshot.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct ProcInfo {
82    pub pid: u32,
83    /// The parent the OS recorded. On Windows it is never updated, so it can
84    /// name a process that has exited or a newer one that reused its PID:
85    /// check [`ProcInfo::is_child_of`] before trusting it.
86    pub ppid: Option<u32>,
87    /// With `pid`, identifies this process across snapshots: a new process
88    /// that reuses the PID has a different key. Opaque (Windows: creation
89    /// time; Linux: start time in clock ticks since boot; macOS: the kernel's
90    /// unique id). 0 when unknown.
91    pub start_key: u64,
92    /// When it started, unix ms.
93    pub started_at_ms: Option<u64>,
94    /// The executable's name, without directory.
95    pub name: String,
96    /// User + kernel CPU time used so far, in nanoseconds.
97    pub cpu_ns: Option<u64>,
98    /// Private memory in bytes, as [`MEMORY_METRIC`] describes.
99    pub mem_private: Option<u64>,
100    /// Working set / resident set in bytes, shared pages included.
101    pub mem_resident: Option<u64>,
102    /// Committed private bytes (Windows only).
103    pub mem_commit: Option<u64>,
104}
105
106impl ProcInfo {
107    /// The key that tells this process apart from a later one with its PID.
108    pub fn key(&self) -> ProcKey {
109        ProcKey {
110            pid: self.pid,
111            start_key: self.start_key,
112        }
113    }
114
115    /// The OS couldn't tell us its CPU or memory (another user's process on
116    /// macOS).
117    pub fn measured(&self) -> bool {
118        self.cpu_ns.is_some() || self.mem_private.is_some()
119    }
120
121    /// Whether `parent` is really this process's parent: the PID matches and,
122    /// where both start times are known, the parent started first (a parent
123    /// that started later reused the PID of the real one).
124    pub fn is_child_of(&self, parent: &ProcInfo) -> bool {
125        if self.ppid != Some(parent.pid) || parent.pid == self.pid {
126            return false;
127        }
128        match (parent.started_at_ms, self.started_at_ms) {
129            (Some(p), Some(c)) => p <= c,
130            _ => true,
131        }
132    }
133}
134
135/// A process's identity across snapshots.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
137pub struct ProcKey {
138    pub pid: u32,
139    pub start_key: u64,
140}
141
142/// Every process this user may see. Processes that exit mid-read are left out.
143pub fn snapshot() -> std::io::Result<Vec<ProcInfo>> {
144    os::snapshot()
145}
146
147/// A process's full command line, read on demand (it may hold secrets, so it
148/// is never part of a [`snapshot`]). `None` when it has exited or the OS
149/// won't say.
150pub fn command_line(pid: u32) -> Option<String> {
151    os::command_line(pid)
152}
153
154/// Whether the process `key` names is still the one running under its PID
155/// (it hasn't exited, and no newer process has reused the PID). Check it
156/// before and after reading anything about a process by PID.
157pub fn is_running(key: ProcKey) -> bool {
158    os::start_key(key.pid) == Some(key.start_key)
159}
160
161/// The command line of exactly the process `key` names: `None` if it has
162/// exited or a newer process has its PID, checked both before and after the
163/// read, so a PID reused in between never hands back the successor's line.
164pub fn command_line_of(key: ProcKey) -> Option<String> {
165    if os::start_key(key.pid)? != key.start_key {
166        return None;
167    }
168    let line = os::command_line(key.pid)?;
169    (os::start_key(key.pid)? == key.start_key).then_some(line)
170}
171
172/// Bytes this process has written so far (cumulative; a rate needs two reads), read on demand.
173/// Windows: the bytes it passed to write calls (`WriteTransferCount`, which includes writes that
174/// stay in the cache). Linux: the same, `wchar` in `/proc/<pid>/io`.
175/// macOS: the bytes it wrote to disk (`ri_diskio_byteswritten`). `None` when the OS won't say
176/// (the process has exited, or belongs to another user).
177pub fn write_bytes(pid: u32) -> Option<u64> {
178    os::write_bytes(pid)
179}
180
181/// Bytes this process has caused to be written to storage so far (cumulative), read on demand: the part of
182/// [`write_bytes`] that reached the disk, so it leaves out writes the page cache coalesced or dropped. Linux:
183/// `write_bytes` less `cancelled_write_bytes` in `/proc/<pid>/io` (writeback avoided by truncating or deleting).
184/// macOS: `ri_diskio_byteswritten`. Windows has no such counter (`None`).
185///
186/// Signed on purpose: a process that truncates data another process dirtied is credited the cancellation but
187/// not the write (the kernel documents this "negative" I/O), so one process's value can be below zero. Add the
188/// values of a set of processes first and clamp the sum, never each one.
189pub fn storage_write_bytes(pid: u32) -> Option<i64> {
190    os::storage_write_bytes(pid)
191}
192
193/// Logical CPUs on the whole machine — what "percent of the machine" divides
194/// by (every processor group on Windows).
195pub fn cpu_count() -> usize {
196    os::cpu_count().max(1)
197}
198
199/// Turns cumulative CPU times into rates: the fraction of one core used
200/// since the previous round (1.0 = one core fully busy).
201///
202/// Each round, call [`RateMeter::sample`] for every key still alive, then
203/// [`RateMeter::finish`]; keys not sampled in a round are forgotten, so a PID
204/// reused by a new process (a new key) starts fresh.
205#[derive(Debug)]
206pub struct RateMeter<K> {
207    prev: HashMap<K, (u64, Instant)>,
208    next: HashMap<K, (u64, Instant)>,
209}
210
211impl<K> Default for RateMeter<K> {
212    fn default() -> Self {
213        Self {
214            prev: HashMap::new(),
215            next: HashMap::new(),
216        }
217    }
218}
219
220impl<K: Eq + Hash + Clone> RateMeter<K> {
221    pub fn new() -> Self {
222        Self::default()
223    }
224
225    /// Record `total_ns` for `key` at `now`; the rate since the previous
226    /// round, or `None` on a key's first round (or a counter that went
227    /// backwards).
228    pub fn sample(&mut self, key: K, total_ns: u64, now: Instant) -> Option<f64> {
229        let rate = self.prev.get(&key).and_then(|&(was, at)| {
230            let wall = now.checked_duration_since(at)?.as_nanos();
231            (wall > 0 && total_ns >= was).then(|| (total_ns - was) as f64 / wall as f64)
232        });
233        self.next.insert(key, (total_ns, now));
234        rate
235    }
236
237    /// End a round.
238    pub fn finish(&mut self) {
239        self.prev = std::mem::take(&mut self.next);
240    }
241
242    /// Keys remembered from the last finished round.
243    pub fn len(&self) -> usize {
244        self.prev.len()
245    }
246
247    pub fn is_empty(&self) -> bool {
248        self.prev.is_empty()
249    }
250}
251
252/// The executable name in a path, without directory (either separator).
253pub fn base_name(path: &str) -> &str {
254    path.rsplit(['/', '\\']).next().unwrap_or(path)
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use std::time::Duration;
261
262    fn proc(pid: u32, ppid: Option<u32>, started: Option<u64>) -> ProcInfo {
263        ProcInfo {
264            pid,
265            ppid,
266            start_key: started.unwrap_or(0),
267            started_at_ms: started,
268            name: String::new(),
269            cpu_ns: None,
270            mem_private: None,
271            mem_resident: None,
272            mem_commit: None,
273        }
274    }
275
276    #[test]
277    fn this_process_reports_the_bytes_it_has_written() {
278        let me = std::process::id();
279        let before = write_bytes(me);
280        // Windows and Linux count what is passed to write calls; macOS counts what reaches disk, which a test can't force.
281        #[cfg(any(windows, target_os = "linux"))]
282        {
283            use std::io::Write;
284            let path = std::env::temp_dir().join(format!("procstats-write-{me}.bin"));
285            let mut f = std::fs::File::create(&path).unwrap();
286            f.write_all(&vec![7u8; 4 * 1024 * 1024]).unwrap();
287            f.sync_all().unwrap();
288            drop(f);
289            let _ = std::fs::remove_file(&path);
290            let after = write_bytes(me).expect("write counters");
291            assert!(after >= before.expect("write counters") + 4 * 1024 * 1024, "{before:?} -> {after}");
292        }
293        #[cfg(not(any(windows, target_os = "linux")))]
294        let _ = before;
295    }
296
297    #[test]
298    fn rate_needs_two_rounds_and_is_a_fraction_of_one_core() {
299        let mut m = RateMeter::new();
300        let t0 = Instant::now();
301        assert_eq!(
302            m.sample("a", 1_000_000_000, t0),
303            None,
304            "first round has no rate"
305        );
306        m.finish();
307        // 1.5 s of CPU over 1 s of wall: one and a half cores.
308        let r = m
309            .sample("a", 2_500_000_000, t0 + Duration::from_secs(1))
310            .unwrap();
311        assert!((r - 1.5).abs() < 1e-9, "{r}");
312    }
313
314    #[test]
315    fn a_key_missing_from_a_round_starts_over() {
316        let mut m = RateMeter::new();
317        let t0 = Instant::now();
318        m.sample(1, 100, t0);
319        m.finish();
320        m.finish(); // key 1 not sampled: forgotten
321        assert_eq!(m.sample(1, 200, t0 + Duration::from_secs(2)), None);
322        assert!(m.is_empty(), "nothing finished yet this round");
323    }
324
325    #[test]
326    fn a_counter_that_goes_backwards_has_no_rate() {
327        let mut m = RateMeter::new();
328        let t0 = Instant::now();
329        m.sample(1, 500, t0);
330        m.finish();
331        assert_eq!(m.sample(1, 100, t0 + Duration::from_secs(1)), None);
332    }
333
334    #[test]
335    fn a_parent_that_started_after_its_child_is_a_reused_pid() {
336        let parent = proc(10, None, Some(2_000));
337        let child = proc(11, Some(10), Some(1_000));
338        assert!(!child.is_child_of(&parent));
339        let real_parent = proc(10, None, Some(500));
340        assert!(child.is_child_of(&real_parent));
341        assert!(!child.is_child_of(&proc(12, None, Some(0))), "wrong pid");
342        assert!(
343            proc(11, Some(10), None).is_child_of(&parent),
344            "unknown start times trust the pid"
345        );
346    }
347
348    #[test]
349    fn base_name_strips_either_separator() {
350        assert_eq!(base_name(r"C:\Program Files\nodejs\node.exe"), "node.exe");
351        assert_eq!(base_name("/usr/bin/node"), "node");
352        assert_eq!(base_name("node"), "node");
353    }
354
355    /// The real reader on this machine: it sees this test process, measured,
356    /// with a start time and a parent.
357    #[test]
358    fn snapshot_sees_this_process_with_cpu_and_memory() {
359        let me = std::process::id();
360        let all = snapshot().expect("snapshot");
361        assert!(all.len() > 1, "only {} processes", all.len());
362        let p = all
363            .iter()
364            .find(|p| p.pid == me)
365            .expect("this process is listed");
366        assert!(p.cpu_ns.is_some(), "{p:?}");
367        assert!(p.mem_private.unwrap_or(0) > 0, "{p:?}");
368        assert!(
369            p.mem_resident.unwrap_or(0) >= p.mem_private.unwrap_or(0) / 4,
370            "{p:?}"
371        );
372        assert!(p.ppid.is_some(), "{p:?}");
373        assert!(!p.name.is_empty(), "{p:?}");
374        let now_ms = std::time::SystemTime::now()
375            .duration_since(std::time::UNIX_EPOCH)
376            .unwrap()
377            .as_millis() as u64;
378        let started = p.started_at_ms.expect("start time");
379        assert!(
380            started <= now_ms + 5_000 && started > now_ms - 24 * 3600 * 1000,
381            "started {started}, now {now_ms}"
382        );
383        // Two snapshots agree on identity.
384        let again = snapshot().unwrap();
385        assert_eq!(again.iter().find(|q| q.pid == me).unwrap().key(), p.key());
386    }
387
388    #[test]
389    fn cpu_time_grows_while_this_process_spins() {
390        let me = std::process::id();
391        let cpu = || {
392            snapshot()
393                .unwrap()
394                .into_iter()
395                .find(|p| p.pid == me)
396                .and_then(|p| p.cpu_ns)
397                .unwrap()
398        };
399        let before = cpu();
400        let spin_until = Instant::now() + Duration::from_millis(300);
401        let mut x = 0u64;
402        while Instant::now() < spin_until {
403            x = x.wrapping_mul(6364136223846793005).wrapping_add(1);
404        }
405        std::hint::black_box(x);
406        let after = cpu();
407        // At least a third of the spin shows up (coarse clocks: 10-16 ms ticks).
408        assert!(
409            after >= before + 100_000_000,
410            "before {before} after {after}"
411        );
412        // And not absurdly more (a units bug, e.g. Mach ticks read as ns).
413        assert!(
414            after < before + 30_000_000_000,
415            "before {before} after {after}"
416        );
417    }
418
419    #[test]
420    fn command_line_of_this_process_names_its_executable() {
421        let line = command_line(std::process::id()).expect("own command line");
422        let exe = std::env::current_exe().unwrap();
423        let stem = exe.file_stem().unwrap().to_string_lossy().to_string();
424        assert!(line.contains(&stem), "{line:?} lacks {stem:?}");
425        assert_eq!(command_line(u32::MAX - 7), None);
426    }
427
428    #[test]
429    fn a_command_line_only_for_the_exact_process() {
430        let me = snapshot()
431            .unwrap()
432            .into_iter()
433            .find(|p| p.pid == std::process::id())
434            .unwrap();
435        assert!(command_line_of(me.key()).is_some(), "{me:?}");
436        let newer = ProcKey {
437            pid: me.pid,
438            start_key: me.start_key.wrapping_add(1),
439        };
440        assert_eq!(command_line_of(newer), None, "same PID, another process");
441    }
442
443    #[test]
444    fn cpu_count_is_at_least_what_this_process_may_use() {
445        let usable = std::thread::available_parallelism()
446            .map(|n| n.get())
447            .unwrap_or(1);
448        assert!(cpu_count() >= usable, "{} < {usable}", cpu_count());
449    }
450}
451
452// This test binary must hold this checkout's code, not another clone's from
453// a shared target directory (`agentmux_common::checkout`).
454#[cfg(test)]
455agentmux_common::checkout_guard!();
456
457/// The folder this library was compiled in, for the checkout guard of the
458/// test binaries that link it (`agentmux_common::checkout_guard!`).
459#[doc(hidden)]
460pub const CHECKOUT_DIR: &str = env!("CARGO_MANIFEST_DIR");