Skip to main content

pitchfork_cli/
procs.rs

1use crate::Result;
2use crate::settings::settings;
3#[cfg(windows)]
4use crate::shell::HideConsoleWindow;
5use miette::IntoDiagnostic;
6use once_cell::sync::Lazy;
7use std::collections::HashMap;
8#[cfg(target_os = "linux")]
9use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
10use std::sync::Mutex;
11use std::time::{Duration, Instant};
12use sysinfo::ProcessesToUpdate;
13#[cfg(windows)]
14use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE};
15#[cfg(windows)]
16use windows_sys::Win32::System::Threading::{
17    GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
18};
19
20/// Map from parent PID to its child PIDs.
21type ParentToChildren = HashMap<u32, Vec<u32>>;
22
23/// Map from PID to process name and optional executable path.
24type ProcessNames = HashMap<u32, (String, Option<String>)>;
25
26/// How often a full process-table refresh may run. High-frequency callers
27/// (web API polling, TUI frames) share one full scan instead of each paying
28/// the ~40ms /proc walk on every call. Targeted `refresh_pids` calls are not
29/// throttled. sysinfo's `cpu_usage()` is a delta between refreshes, so a
30/// longer window also smooths the reported CPU%.
31const FULL_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
32
33pub struct Procs {
34    system: Mutex<sysinfo::System>,
35    /// When the last full process-table refresh ran. `None` until the first
36    /// refresh forces the initial scan (the table starts empty).
37    last_full_refresh: Mutex<Option<Instant>>,
38}
39
40pub static PROCS: Lazy<Procs> = Lazy::new(Procs::new);
41
42/// How long a process-group kill waits, after its SIGKILL, for the group to be
43/// gone before reporting it stuck. Part of the longest a daemon's stop takes.
44pub const PROCESS_GROUP_SIGKILL_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
45
46/// How long a Windows stop waits, after terminating a daemon's job, for the
47/// processes in it to finish exiting and release what they hold. Part of the
48/// longest a daemon's stop takes; nothing waits for it elsewhere.
49pub const JOB_EXIT_WAIT: std::time::Duration = if cfg!(windows) {
50    std::time::Duration::from_secs(5)
51} else {
52    std::time::Duration::ZERO
53};
54
55impl Default for Procs {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl Procs {
62    pub fn new() -> Self {
63        // IMPORTANT: Do NOT call refresh_processes() or System::new_all() here.
64        //
65        // Both refresh the state of every process in the system, which takes
66        // ~500ms on a typical machine. Since PROCS is a Lazy static, the first
67        // access triggers this constructor — and `pitchfork cd` (which only
68        // needs to check if the supervisor PID is alive) would block for that
69        // duration on every directory change.
70        //
71        // See https://github.com/jdx/pitchfork/discussions/439
72        //
73        // Callers that need process info must call refresh_pids() (for specific
74        // PIDs) or refresh_processes() (for full-system stats) explicitly.
75        Self {
76            // `System::new()` is fallible only for the sake of unsupported
77            // platforms; it does not touch the OS on the ones we build for.
78            system: Mutex::new(
79                sysinfo::System::new().expect("sysinfo is supported on this platform"),
80            ),
81            last_full_refresh: Mutex::new(None),
82        }
83    }
84
85    fn lock_system(&self) -> std::sync::MutexGuard<'_, sysinfo::System> {
86        self.system.lock().unwrap_or_else(|poisoned| {
87            warn!("System mutex was poisoned, recovering");
88            poisoned.into_inner()
89        })
90    }
91
92    pub fn title(&self, pid: u32) -> Option<String> {
93        self.lock_system()
94            .process(sysinfo::Pid::from_u32(pid))
95            .map(|p| p.name().to_string_lossy().to_string())
96    }
97
98    /// Time the system booted, in seconds since the epoch.
99    ///
100    /// Constant for the lifetime of a boot, so recording it alongside a
101    /// daemon's PID makes it possible to tell later whether that record
102    /// belongs to the current boot. Note this is *not* comparable with
103    /// `start_time`, whose units are platform-specific.
104    ///
105    /// Returns 0 if the OS cannot report it. That never matches a real boot
106    /// time, so a record is treated as belonging to another boot, which is the
107    /// safe direction.
108    pub fn boot_time(&self) -> u64 {
109        sysinfo::System::boot_time().unwrap_or_else(|err| {
110            warn!("could not read the system boot time: {err}");
111            0
112        })
113    }
114
115    /// High-resolution kernel start token for the process.
116    ///
117    /// Combined with the PID this forms a stable identity for the lifetime of a
118    /// process. Unlike sysinfo's seconds-since-epoch value, this preserves the
119    /// native platform resolution so same-second PID reuse cannot compare equal.
120    pub fn start_time(&self, pid: u32) -> Option<u64> {
121        process_start_token(pid)
122    }
123
124    #[cfg(not(windows))]
125    fn start_time_matches(&self, pid: u32, expected: u64) -> bool {
126        self.start_time(pid) == Some(expected)
127    }
128
129    pub fn is_running(&self, pid: u32) -> bool {
130        // Use kill(pid, 0) on Unix for an O(1) liveness check that does not
131        // depend on the process cache being populated. This avoids the need
132        // for a full process refresh just to check a single PID.
133        // ESRCH = process does not exist; EPERM = process exists but owned
134        // by another user (still "running" from our perspective).
135        #[cfg(unix)]
136        {
137            unsafe {
138                if libc::kill(pid as i32, 0) == 0 {
139                    return true;
140                }
141                std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
142            }
143        }
144        #[cfg(not(unix))]
145        {
146            self.refresh_pids(&[pid]);
147            self.lock_system()
148                .process(sysinfo::Pid::from_u32(pid))
149                .is_some()
150        }
151    }
152
153    /// Walk the cached process snapshot to find all descendant PIDs.
154    /// Kept for diagnostics/status display; no longer used in the kill path.
155    #[allow(dead_code)]
156    pub fn all_children(&self, pid: u32) -> Vec<u32> {
157        let system = self.lock_system();
158        let mut children_map: ParentToChildren = HashMap::new();
159        for (child_pid, process) in system.processes() {
160            if let Some(parent) = process.parent() {
161                children_map
162                    .entry(parent.as_u32())
163                    .or_default()
164                    .push(child_pid.as_u32());
165            }
166        }
167        drop(system);
168        descendant_pids(pid, &children_map)
169    }
170    /// Collect minimal process tree information in a single lock.
171    ///
172    /// Returns a map of parent PID → child PIDs and a map of PID → (name, exe).
173    /// This avoids repeated mutex locking when traversing deep trees.
174    pub fn collect_process_tree_info(&self) -> (ParentToChildren, ProcessNames) {
175        let system = self.lock_system();
176        let all = system.processes();
177        let mut parent_to_children: ParentToChildren = HashMap::new();
178        let mut process_info: ProcessNames = HashMap::new();
179
180        for (pid, proc) in all {
181            let pid_u32 = pid.as_u32();
182            process_info.insert(
183                pid_u32,
184                (
185                    proc.name().to_string_lossy().to_string(),
186                    proc.exe().map(|e| e.to_string_lossy().to_string()),
187                ),
188            );
189
190            if let Some(ppid) = proc.parent() {
191                parent_to_children
192                    .entry(ppid.as_u32())
193                    .or_default()
194                    .push(pid_u32);
195            }
196        }
197
198        (parent_to_children, process_info)
199    }
200    pub async fn kill_process_group_async(
201        &self,
202        pid: u32,
203        stop_signal: i32,
204        stop_timeout: Option<std::time::Duration>,
205    ) -> Result<bool> {
206        tokio::task::spawn_blocking(move || {
207            PROCS.kill_process_group(pid, stop_signal, stop_timeout, None)
208        })
209        .await
210        .into_diagnostic()?
211    }
212
213    /// Kill a process group only while its leader still has `expected_start_time`.
214    ///
215    /// Identity is refreshed inside the blocking kill operation, immediately
216    /// before signaling. Linux holds a pidfd and Windows holds an open process
217    /// handle across termination so the validated PID cannot be recycled.
218    /// Unix platforms without a durable process handle re-verify the start
219    /// time inside the blocking operation, right before the signal — the
220    /// same check-then-signal atomicity tokio affords in one closure. Pass
221    /// `None` to fail closed (refuse to signal anything).
222    pub async fn kill_process_group_if_start_time_matches_async(
223        &self,
224        pid: u32,
225        expected_start_time: Option<u64>,
226        stop_signal: i32,
227        stop_timeout: Option<std::time::Duration>,
228    ) -> Result<bool> {
229        let Some(expected_start_time) = expected_start_time else {
230            warn!(
231                "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
232            );
233            return Ok(false);
234        };
235        tokio::task::spawn_blocking(move || {
236            PROCS.kill_process_group(pid, stop_signal, stop_timeout, Some(expected_start_time))
237        })
238        .await
239        .into_diagnostic()?
240    }
241
242    /// Kill a single process only if it is still the generation identified by
243    /// `expected_start_time`.
244    ///
245    /// This is the single-process counterpart of
246    /// [`Self::kill_process_group_if_start_time_matches_async`], for processes
247    /// that are not session leaders (the supervisor itself is started in the
248    /// caller's session, so signalling its group would hit the caller's shell).
249    /// A recorded PID whose process is gone may have been handed to an
250    /// unrelated process, e.g. after a reboot, so the kill refuses when the
251    /// live start time differs from the recorded one. Returns `Ok(false)` when
252    /// nothing was signalled.
253    ///
254    /// On Linux the identity check binds a pidfd to the expected generation
255    /// and every signal is sent through that pidfd, so a PID recycled after
256    /// the check can never be reached: the pidfd keeps referring to the dead
257    /// generation and the kernel answers `ESRCH`. Windows holds an open
258    /// process handle for the same effect. Other Unix platforms re-verify
259    /// immediately before signalling, leaving a window no wider than the
260    /// daemon kill path has there.
261    pub async fn kill_if_start_time_matches_async(
262        &self,
263        pid: u32,
264        expected_start_time: Option<u64>,
265        stop_signal: i32,
266        stop_timeout: Option<std::time::Duration>,
267    ) -> Result<bool> {
268        let Some(expected_start_time) = expected_start_time else {
269            warn!(
270                "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
271            );
272            return Ok(false);
273        };
274        tokio::task::spawn_blocking(move || {
275            PROCS.kill_if_start_time_matches(pid, expected_start_time, stop_signal, stop_timeout)
276        })
277        .await
278        .into_diagnostic()?
279    }
280
281    #[cfg(target_os = "linux")]
282    fn kill_if_start_time_matches(
283        &self,
284        pid: u32,
285        expected_start_time: u64,
286        stop_signal: i32,
287        stop_timeout: Option<std::time::Duration>,
288    ) -> Result<bool> {
289        let pidfd = match open_pidfd(pid) {
290            Ok(pidfd) => pidfd,
291            Err(err) if err.raw_os_error() == Some(libc::ESRCH) => {
292                debug!("process {pid} no longer exists");
293                return Ok(false);
294            }
295            Err(err) => {
296                return Err(miette::miette!(
297                    "cannot securely identify process {pid}: {err}"
298                ));
299            }
300        };
301        // The pidfd refers to whichever process owned the PID when it was
302        // opened. Checking the start token now proves that is the expected
303        // generation; from here on only the pidfd is signalled, never the
304        // number, so a later recycle of the PID cannot be reached.
305        if !self.verify_start_time_before_signal(pid, expected_start_time)? {
306            return Ok(false);
307        }
308        let target = [(pid, pidfd)];
309        let signal_name = signal_name(stop_signal);
310        debug!("sending {signal_name} to pinned process {pid}");
311        signal_pidfds(&target, stop_signal, signal_name)?;
312
313        // Same polling schedule as `kill`: fast checks first, then 50ms steps
314        // for the rest of the stop timeout, then SIGKILL.
315        let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
316        let fast_ms = 10u64;
317        let slow_ms = 50u64;
318        let total_ms = stop_timeout.as_millis().max(1) as u64;
319        let fast_count = ((total_ms / fast_ms) as usize).min(10);
320        let fast_total_ms = fast_ms * fast_count as u64;
321        let slow_count = (total_ms.saturating_sub(fast_total_ms) / slow_ms) as usize;
322        for i in 0..fast_count {
323            std::thread::sleep(std::time::Duration::from_millis(fast_ms));
324            if !pidfd_is_running(&target[0].1) {
325                debug!(
326                    "process {pid} terminated after {signal_name} ({} ms)",
327                    (i + 1) as u64 * fast_ms
328                );
329                return Ok(true);
330            }
331        }
332        for i in 0..slow_count {
333            std::thread::sleep(std::time::Duration::from_millis(slow_ms));
334            if !pidfd_is_running(&target[0].1) {
335                debug!(
336                    "process {pid} terminated after {signal_name} ({} ms)",
337                    fast_total_ms + (i + 1) as u64 * slow_ms
338                );
339                return Ok(true);
340            }
341        }
342
343        warn!(
344            "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
345            stop_timeout.as_millis()
346        );
347        signal_pidfds(&target, libc::SIGKILL, "SIGKILL")?;
348        // Brief wait for SIGKILL to take effect
349        std::thread::sleep(std::time::Duration::from_millis(100));
350        Ok(true)
351    }
352
353    #[cfg(not(target_os = "linux"))]
354    fn kill_if_start_time_matches(
355        &self,
356        pid: u32,
357        expected_start_time: u64,
358        stop_signal: i32,
359        stop_timeout: Option<std::time::Duration>,
360    ) -> Result<bool> {
361        // An open handle keeps the Windows process object, and with it the
362        // PID, from being recycled until the handle is closed, so the
363        // identity verified below still holds for the taskkill in `kill`.
364        #[cfg(windows)]
365        let _pin = open_process_handle(pid).ok();
366
367        if !self.verify_start_time_before_signal(pid, expected_start_time)? {
368            return Ok(false);
369        }
370        self.kill(pid, stop_signal, stop_timeout, Some(expected_start_time))
371    }
372
373    /// Confirm that `pid` is still the generation `expected_start_time`
374    /// describes, immediately before it is signalled.
375    ///
376    /// Three answers are possible and callers must not conflate them:
377    /// `Ok(true)` when the token matches; `Ok(false)` when the process is
378    /// gone or a different generation now owns the PID, meaning there is
379    /// nothing of ours left to signal; and `Err` when the process is alive
380    /// but its token cannot be read. The last case is *not* proof of
381    /// termination — treating it as such would let `supervisor stop` drop
382    /// the record of a supervisor that keeps running — so it is reported as
383    /// a failure and the record is left alone.
384    fn verify_start_time_before_signal(&self, pid: u32, expected_start_time: u64) -> Result<bool> {
385        match self.start_time(pid) {
386            Some(current) if current == expected_start_time => Ok(true),
387            Some(current) => {
388                warn!(
389                    "pid {pid} is not the recorded process (start time {current}, expected {expected_start_time}); not signalling it"
390                );
391                Ok(false)
392            }
393            None if self.is_running(pid) => Err(miette::miette!(
394                "cannot verify the identity of pid {pid}: its start time is unreadable; not signalling it"
395            )),
396            None => {
397                debug!("process {pid} no longer exists");
398                Ok(false)
399            }
400        }
401    }
402
403    /// Kill an entire process group with graceful shutdown strategy:
404    /// 1. Send the configured stop signal to the process group (-pgid) and
405    ///    wait up to the stop timeout for the WHOLE group to exit
406    /// 2. If any processes remain, send SIGKILL to the group and verify
407    ///
408    /// Since daemons are spawned with setsid(), the daemon PID == PGID,
409    /// so this atomically signals all descendant processes.
410    ///
411    /// The stop timeout is the graceful-shutdown budget for the entire group
412    /// (like systemd's TimeoutStopSec for a cgroup): members that are still
413    /// alive when it expires are SIGKILLed. Daemons whose teardown legitimately
414    /// takes longer (e.g. draining connections, stopping containers) should
415    /// raise `stop_signal.timeout` rather than rely on outliving the budget.
416    ///
417    /// Returns `Err` if the signal could not be sent (e.g. permission denied)
418    /// or if group members survived even SIGKILL (uninterruptible sleep).
419    #[cfg(unix)]
420    fn kill_process_group(
421        &self,
422        pid: u32,
423        stop_signal: i32,
424        stop_timeout: Option<std::time::Duration>,
425        expected_start_time: Option<u64>,
426    ) -> Result<bool> {
427        let pgid = pid as i32;
428        let signal_name = signal_name(stop_signal);
429
430        #[cfg(target_os = "linux")]
431        if let Some(expected) = expected_start_time {
432            return self.kill_process_group_with_pidfds(pid, expected, stop_signal, stop_timeout);
433        }
434
435        // A start-time check alone cannot prevent the numeric PID/PGID from
436        // being recycled before killpg. Linux closes that race with a pidfd.
437        // Other Unix platforms have no durable process handle, so they do the
438        // next best thing: re-read the start time fresh from the kernel here,
439        // inside the blocking operation and immediately before the signal, so
440        // the check-to-signal gap is just the adjacency of two syscalls in one
441        // thread — no await, no scheduler boundary. For that gap to matter, the
442        // kernel would have to wrap the entire sequential PID space (XNU
443        // allocates monotonically from lastpid and refuses IDs still in use as
444        // a proc, pgrp, or session) and hand the exact PGID to a new group
445        // leader between the two syscalls, which is not reachable in practice.
446        #[cfg(not(target_os = "linux"))]
447        if let Some(expected) = expected_start_time
448            && !self.start_time_matches(pid, expected)
449        {
450            debug!("process {pid} identity changed before killpg; refusing to signal it");
451            return Ok(false);
452        }
453
454        debug!("killing process group {pgid} with {signal_name}");
455
456        // Send the stop signal to the entire process group.
457        // killpg sends to all processes in the group atomically.
458        // We intentionally skip the zombie check here because the leader may be
459        // a zombie while children in the group are still running.
460        let ret = unsafe { libc::killpg(pgid, stop_signal) };
461        if ret == -1 {
462            let err = std::io::Error::last_os_error();
463            if err.raw_os_error() == Some(libc::ESRCH) {
464                debug!("process group {pgid} no longer exists");
465                return Ok(false);
466            }
467            if err.raw_os_error() == Some(libc::EPERM) {
468                return Err(miette::miette!(
469                    "failed to send {signal_name} to process group {pgid}: permission denied"
470                ));
471            }
472            warn!("failed to send {signal_name} to process group {pgid}: {err}");
473        }
474
475        // Wait for graceful shutdown: fast initial check then slower polling.
476        // Per-daemon timeout overrides the global setting.
477        //
478        // The wait must cover the ENTIRE group, not just the leader. The leader
479        // is often a thin shell (`sh -c ...`) that dies within milliseconds of
480        // the signal while its children are still shutting down gracefully
481        // (e.g. `docker compose up` waiting for its container to stop).
482        // Returning as soon as the leader dies lets a force-restart spawn a
483        // replacement that collides with the still-terminating old instance.
484        let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
485        let fast_ms = 10u64;
486        let slow_ms = 50u64;
487        let total_ms = stop_timeout.as_millis().max(1) as u64;
488        let fast_count = ((total_ms / fast_ms) as usize).min(10);
489        let fast_total_ms = fast_ms * fast_count as u64;
490        let remaining_ms = total_ms.saturating_sub(fast_total_ms);
491        let slow_count = (remaining_ms / slow_ms) as usize;
492
493        let fast_checks =
494            std::iter::repeat_n(std::time::Duration::from_millis(fast_ms), fast_count);
495        let slow_checks =
496            std::iter::repeat_n(std::time::Duration::from_millis(slow_ms), slow_count);
497        let mut elapsed_ms = 0u64;
498
499        for sleep_duration in fast_checks.chain(slow_checks) {
500            std::thread::sleep(sleep_duration);
501            elapsed_ms += sleep_duration.as_millis() as u64;
502            if process_group_terminated(pgid) {
503                debug!("process group {pgid} terminated after {signal_name} ({elapsed_ms} ms)",);
504                return Ok(true);
505            }
506        }
507
508        // SIGKILL the entire process group as last resort
509        warn!(
510            "process group {pgid} did not respond to {signal_name} after {}ms, sending SIGKILL",
511            stop_timeout.as_millis()
512        );
513        let ret = unsafe { libc::killpg(pgid, libc::SIGKILL) };
514        if ret == -1 {
515            let err = std::io::Error::last_os_error();
516            if err.raw_os_error() != Some(libc::ESRCH) {
517                warn!("failed to send SIGKILL to process group {pgid}: {err}");
518            }
519        }
520
521        // Wait for SIGKILL to take effect on the whole group (bounded: SIGKILL
522        // cannot be caught, so members disappear as soon as the kernel reaps
523        // them — anything left after this is stuck in uninterruptible sleep).
524        let sigkill_polls = PROCESS_GROUP_SIGKILL_WAIT.as_millis() / 50;
525        for _ in 0..sigkill_polls {
526            std::thread::sleep(std::time::Duration::from_millis(50));
527            if process_group_terminated(pgid) {
528                return Ok(true);
529            }
530        }
531        // Report failure so callers do not mark the daemon Stopped (and start
532        // a replacement) while a member is still alive.
533        Err(miette::miette!(
534            "process group {pgid} still has members after SIGKILL \
535             (possibly stuck in uninterruptible sleep)"
536        ))
537    }
538
539    /// Whether any signalable member of the daemon's process group is still
540    /// alive. The daemon PID == PGID because daemons are spawned with setsid().
541    pub fn process_group_alive(&self, pid: u32) -> bool {
542        #[cfg(unix)]
543        {
544            !process_group_terminated(pid as i32)
545        }
546        #[cfg(not(unix))]
547        {
548            self.is_running(pid)
549        }
550    }
551
552    /// Whether `pid` names a process that has not exited: unlike
553    /// [`Self::is_running`], an exited process its parent has not reaped yet
554    /// (a zombie) does not count.
555    pub fn is_live(&self, pid: u32) -> bool {
556        if !self.is_running(pid) {
557            return false;
558        }
559        self.refresh_pids(&[pid]);
560        self.lock_system()
561            .process(sysinfo::Pid::from_u32(pid))
562            .is_none_or(|p| !is_exited_status(p.status()))
563    }
564
565    /// Whether the process group `pgid` still has a member that has not
566    /// exited. Unlike [`Self::process_group_alive`], a group left holding
567    /// only zombies, which nothing reaps when the parent is gone and init
568    /// does not, does not count.
569    pub fn process_group_has_live_member(&self, pgid: u32) -> bool {
570        #[cfg(unix)]
571        {
572            // Only ESRCH proves the group gone: EPERM means it exists but
573            // belongs to another user, so look at its members either way.
574            if unsafe { libc::killpg(pgid as i32, 0) } != 0
575                && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
576            {
577                return false;
578            }
579            self.refresh_processes();
580            self.lock_system().processes().iter().any(|(pid, p)| {
581                !is_exited_status(p.status())
582                    && unsafe { libc::getpgid(pid.as_u32() as i32) } == pgid as i32
583            })
584        }
585        #[cfg(not(unix))]
586        {
587            self.is_live(pgid)
588        }
589    }
590
591    #[cfg(target_os = "linux")]
592    fn kill_process_group_with_pidfds(
593        &self,
594        pid: u32,
595        expected_start_time: u64,
596        _stop_signal: i32,
597        stop_timeout: Option<std::time::Duration>,
598    ) -> Result<bool> {
599        let leader = match open_pidfd(pid) {
600            Ok(pidfd) => pidfd,
601            Err(err) => {
602                warn!("cannot securely identify process group {pid}: {err}");
603                return Ok(false);
604            }
605        };
606        if !self.start_time_matches(pid, expected_start_time) {
607            debug!("process group {pid} leader identity changed before signaling");
608            return Ok(false);
609        }
610
611        let mut members = vec![(pid, leader)];
612        if let Err(err) = stop_pidfds(&members) {
613            let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
614            return Err(err);
615        }
616        if !pidfd_is_running(&members[0].1) {
617            debug!("process group {pid} leader exited before it could be frozen");
618            return Ok(false);
619        }
620
621        // Stop newly discovered members before rescanning. Once a scan adds
622        // nothing, every process capable of forking into this group is frozen,
623        // so the pinned set is complete and the PGID cannot be recycled.
624        loop {
625            let known_members = members.len();
626            let added = match extend_process_group_pidfds(pid as i32, &mut members) {
627                Ok(added) => added,
628                Err(err) => {
629                    let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
630                    return Err(miette::miette!(
631                        "failed to scan pinned process group {pid}: {err}"
632                    ));
633                }
634            };
635            if added == 0 {
636                break;
637            }
638            if let Err(err) = stop_pidfds(&members[known_members..]) {
639                let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
640                return Err(err);
641            }
642        }
643
644        warn!(
645            "force-terminating {} pinned orphan process(es) in group {pid}",
646            members.len()
647        );
648        if let Err(err) = signal_pidfds(&members, libc::SIGKILL, "SIGKILL") {
649            let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
650            return Err(err);
651        }
652
653        let exit_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
654        let checks = exit_timeout.as_millis().max(1).div_ceil(50) as usize;
655        for _ in 0..checks {
656            if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
657                return Ok(true);
658            }
659            std::thread::sleep(std::time::Duration::from_millis(50));
660        }
661        if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
662            return Ok(true);
663        }
664
665        warn!("one or more pinned processes in orphan group {pid} remained alive after SIGKILL");
666        let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
667        Ok(false)
668    }
669
670    #[cfg(not(unix))]
671    fn kill_process_group(
672        &self,
673        pid: u32,
674        stop_signal: i32,
675        stop_timeout: Option<std::time::Duration>,
676        expected_start_time: Option<u64>,
677    ) -> Result<bool> {
678        // Keep the Windows process object alive through taskkill so its
679        // numeric PID cannot be recycled after identity validation.
680        #[cfg(windows)]
681        let _identity_handle = if let Some(expected) = expected_start_time {
682            let handle = match open_process_handle(pid) {
683                Ok(handle) => handle,
684                Err(err) => {
685                    warn!("cannot securely identify process {pid}: {err}");
686                    return Ok(false);
687                }
688            };
689            if process_start_token_from_handle(handle.0) != Some(expected) {
690                debug!("process {pid} identity changed before taskkill");
691                return Ok(false);
692            }
693            Some(handle)
694        } else {
695            None
696        };
697
698        #[cfg(not(windows))]
699        if let Some(expected) = expected_start_time
700            && !self.start_time_matches(pid, expected)
701        {
702            debug!("process {pid} identity changed before termination");
703            return Ok(false);
704        }
705
706        self.kill(pid, stop_signal, stop_timeout, expected_start_time)
707    }
708
709    /// Kill a process with graceful shutdown strategy:
710    /// 1. Send the configured stop signal and wait up to ~3s (10ms intervals for first 100ms, then 50ms intervals)
711    /// 2. If still running, send SIGKILL to force termination
712    ///
713    /// This ensures fast-exiting processes don't wait unnecessarily,
714    /// while stubborn processes eventually get forcefully terminated.
715    ///
716    /// Returns `Err` if the signal could not be sent (e.g. permission denied
717    /// when targeting a process owned by another user/root).
718    ///
719    /// Signals by PID number, so callers must have pinned the process
720    /// identity first; on Linux the pidfd path in
721    /// `kill_if_start_time_matches` is used instead. When
722    /// `expected_start_time` is given, the start token is re-checked
723    /// immediately before the first signal and again before the SIGKILL
724    /// escalation: if the process exited and its PID was recycled in either
725    /// window, the newcomer is left alone.
726    #[cfg(not(target_os = "linux"))]
727    fn kill(
728        &self,
729        pid: u32,
730        stop_signal: i32,
731        stop_timeout: Option<std::time::Duration>,
732        expected_start_time: Option<u64>,
733    ) -> Result<bool> {
734        debug!("killing process {pid}");
735
736        #[cfg(windows)]
737        {
738            // The caller holds an open process handle while this runs, which
739            // keeps the PID from being recycled, so no re-check is needed.
740            let _ = expected_start_time;
741            // Windows has no signals. SIGINT is the one with a counterpart,
742            // Ctrl+C, so a daemon asking for it gets that first and until its
743            // stop timeout to exit; every other signal, and a daemon that is
744            // still running after the timeout, is terminated outright with
745            // its process tree. The timeout bounds only the graceful part.
746            //
747            // The tree is the daemon's job object (see `win_job`), opened now
748            // while the daemon is alive and its job can be found by name.
749            let job = open_process_handle(pid)
750                .ok()
751                .and_then(|process| crate::win_job::DaemonJob::open(pid, process.0));
752            if stop_signal == crate::config_types::StopSignal::SIGINT {
753                let stop_timeout =
754                    stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
755                if interrupt_and_wait(pid, stop_timeout) {
756                    debug!("process {pid} exited after Ctrl+C");
757                    // Whatever it started and left running goes with it.
758                    if job.as_ref().is_some_and(job_outlives_termination) {
759                        return Err(miette::miette!(
760                            "process {pid} exited after Ctrl+C, but processes it started may \
761                             still be running: its job was not terminated and emptied within {}s",
762                            JOB_EXIT_WAIT.as_secs()
763                        ));
764                    }
765                    return Ok(true);
766                }
767            }
768            // Walk the tree first, while the daemon is still there to walk it
769            // from: the processes an MSYS or Cygwin shell starts are not in
770            // the daemon's job, so terminating the job alone leaves them (and
771            // the ports they hold) behind.
772            // sysinfo's process.kill() only kills the main process, leaving
773            // child processes (e.g. python3 spawned by sh -c) orphaned and
774            // still holding ports. The /T flag kills all descendant processes.
775            debug!("forcing process tree termination for pid {pid}");
776            let output = std::process::Command::new("taskkill")
777                .args(["/F", "/T", "/PID"])
778                .arg(pid.to_string())
779                .hide_console_window()
780                .output();
781            let taskkill_succeeded = match output {
782                Ok(o) if o.status.success() => {
783                    debug!("taskkill /F /T /PID {pid} succeeded");
784                    true
785                }
786                Ok(o) => {
787                    debug!(
788                        "taskkill /F /T /PID {pid} exited with status {}: {}",
789                        o.status,
790                        String::from_utf8_lossy(&o.stderr).trim()
791                    );
792                    false
793                }
794                Err(e) => {
795                    debug!("failed to spawn taskkill for pid {pid}: {e}");
796                    false
797                }
798            };
799            // Then the job, for what the walk cannot reach: a process whose
800            // parent has already exited is still in it.
801            let job_outlived = job.as_ref().is_some_and(job_outlives_termination);
802            // Brief sleep to let the OS signal the process handle, giving
803            // tokio's child.wait() in the monitor task a chance to detect
804            // the exit and fire on_stop/on_exit hooks.
805            std::thread::sleep(std::time::Duration::from_millis(200));
806            if !taskkill_succeeded && self.is_running(pid) {
807                return Err(miette::miette!(
808                    "taskkill failed and process {pid} is still running"
809                ));
810            }
811            // A process still exiting can hold a port the next start needs,
812            // so the stop is not reported as done while one remains.
813            if job_outlived {
814                return Err(miette::miette!(
815                    "processes of daemon {pid} may still be running: its job was not \
816                     terminated and emptied within {}s",
817                    JOB_EXIT_WAIT.as_secs()
818                ));
819            }
820            Ok(true)
821        }
822
823        #[cfg(unix)]
824        {
825            let sysinfo_pid = sysinfo::Pid::from_u32(pid);
826            let signal_name = signal_name(stop_signal);
827            // Without pidfds there is no way to bind a signal to a process
828            // generation, so re-verify the start token immediately before
829            // the first signal. This shrinks the check-to-signal window to
830            // the two adjacent syscalls, the tightest this platform allows.
831            if let Some(expected) = expected_start_time
832                && !self.verify_start_time_before_signal(pid, expected)?
833            {
834                return Ok(false);
835            }
836            // Send stop signal for graceful shutdown using libc::kill directly
837            // so we can distinguish EPERM (permission denied) from ESRCH
838            // (process already gone — possible in a narrow race window).
839            debug!("sending {signal_name} to process {pid}");
840            let ret = unsafe { libc::kill(pid as i32, stop_signal) };
841            if ret == -1 {
842                let err = std::io::Error::last_os_error();
843                if err.raw_os_error() == Some(libc::ESRCH) {
844                    debug!("process {pid} no longer exists");
845                    return Ok(false);
846                }
847                if err.raw_os_error() == Some(libc::EPERM) {
848                    return Err(miette::miette!(
849                        "failed to send {signal_name} to process {pid}: permission denied"
850                    ));
851                }
852                return Err(miette::miette!(
853                    "failed to send {signal_name} to process {pid}: {err}"
854                ));
855            }
856
857            // Fast check: 10ms intervals, then slower 50ms polling for stop_timeout.
858            // Per-daemon timeout overrides the global setting.
859            let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
860            let fast_ms = 10u64;
861            let slow_ms = 50u64;
862            let total_ms = stop_timeout.as_millis().max(1) as u64;
863            let fast_count = ((total_ms / fast_ms) as usize).min(10);
864            let fast_total_ms = fast_ms * fast_count as u64;
865            let remaining_ms = total_ms.saturating_sub(fast_total_ms);
866            let slow_count = (remaining_ms / slow_ms) as usize;
867
868            for i in 0..fast_count {
869                std::thread::sleep(std::time::Duration::from_millis(fast_ms));
870                self.refresh_pids(&[pid]);
871                if self.is_terminated_or_zombie(sysinfo_pid) {
872                    debug!(
873                        "process {pid} terminated after {signal_name} ({} ms)",
874                        (i + 1) * fast_ms as usize
875                    );
876                    return Ok(true);
877                }
878            }
879
880            // Slower check: 50ms intervals for the remainder of stop_timeout
881            for i in 0..slow_count {
882                std::thread::sleep(std::time::Duration::from_millis(slow_ms));
883                self.refresh_pids(&[pid]);
884                if self.is_terminated_or_zombie(sysinfo_pid) {
885                    debug!(
886                        "process {pid} terminated after {signal_name} ({} ms)",
887                        fast_total_ms + (i + 1) as u64 * slow_ms
888                    );
889                    return Ok(true);
890                }
891            }
892
893            // SIGKILL as last resort after stop_timeout. The PID may have been
894            // recycled while we waited: the original exited and an unrelated
895            // process took its number, which the liveness polls above cannot
896            // tell apart. Re-check the generation before escalating.
897            if let Some(expected) = expected_start_time
898                && !self.start_time_matches(pid, expected)
899            {
900                debug!(
901                    "process {pid} exited during the stop timeout and its PID was recycled; not sending SIGKILL"
902                );
903                return Ok(true);
904            }
905            warn!(
906                "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
907                stop_timeout.as_millis()
908            );
909            let ret = unsafe { libc::kill(pid as i32, libc::SIGKILL) };
910            if ret == -1 {
911                let err = std::io::Error::last_os_error();
912                if err.raw_os_error() != Some(libc::ESRCH) {
913                    warn!("failed to send SIGKILL to process {pid}: {err}");
914                }
915            }
916
917            // Brief wait for SIGKILL to take effect
918            std::thread::sleep(std::time::Duration::from_millis(100));
919            Ok(true)
920        }
921    }
922
923    /// Check if a process is terminated or is a zombie.
924    /// On Linux, zombie processes still have /proc/[pid] entries but are effectively dead.
925    /// This prevents unnecessary signal escalation for processes that have already exited.
926    #[cfg(all(unix, not(target_os = "linux")))]
927    fn is_terminated_or_zombie(&self, sysinfo_pid: sysinfo::Pid) -> bool {
928        let system = self.lock_system();
929        match system.process(sysinfo_pid) {
930            None => true,
931            Some(process) => {
932                matches!(process.status(), sysinfo::ProcessStatus::Zombie)
933            }
934        }
935    }
936
937    pub(crate) fn refresh_processes(&self) {
938        let mut system = self.lock_system();
939        system.refresh_processes(ProcessesToUpdate::All, true);
940        // On Windows, refresh_processes() does not update CPU usage.
941        // sysinfo requires a separate refresh_cpu_usage() call to compute
942        // the CPU delta between two samples. The first call stores the
943        // baseline; subsequent calls return the actual percentage.
944        #[cfg(windows)]
945        system.refresh_cpu_usage();
946    }
947
948    /// Refresh only specific PIDs instead of all processes.
949    /// More efficient when you only need to check a small set of known PIDs.
950    pub(crate) fn refresh_pids(&self, pids: &[u32]) {
951        let sysinfo_pids: Vec<sysinfo::Pid> =
952            pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
953        self.lock_system()
954            .refresh_processes(ProcessesToUpdate::Some(&sysinfo_pids), true);
955    }
956
957    /// Full process-table refresh, throttled to at most once per
958    /// [`FULL_REFRESH_INTERVAL`] **among the callers that use this gated
959    /// path** (web API polling, TUI frames, process-tree endpoints). Callers
960    /// that bypass the gate — e.g. `refresh_processes()` directly in the
961    /// active-port probe — do not update `last_full_refresh`, so a gated
962    /// caller right after may still pay a scan. The first call always
963    /// refreshes.
964    ///
965    /// Callers that need to observe *new* descendants (e.g. the active-port
966    /// probe right after a daemon spawns) must still call `refresh_processes`
967    /// directly, since a throttled refresh may miss children forked since the
968    /// last scan.
969    ///
970    /// Lock order: this method holds `last_full_refresh` while
971    /// `refresh_processes` takes `system`. Never acquire `system` first and
972    /// then call this method, or the reverse order would deadlock.
973    pub(crate) fn refresh_if_stale(&self) {
974        let mut last = self
975            .last_full_refresh
976            .lock()
977            .unwrap_or_else(|poisoned| poisoned.into_inner());
978        if last.is_none_or(|t| t.elapsed() >= FULL_REFRESH_INTERVAL) {
979            self.refresh_processes();
980            *last = Some(Instant::now());
981        }
982    }
983
984    /// Get aggregated stats for multiple process trees in a single pass.
985    ///
986    /// Builds the parent→children map once (O(N)) and then BFS-es from each
987    /// root PID (O(D_i) per daemon). Total cost is O(N + ΣD_i) instead of
988    /// O(D × N) when collecting stats for each daemon separately.
989    pub fn get_batch_group_stats(&self, pids: &[u32]) -> Vec<(u32, Option<ProcessStats>)> {
990        if pids.is_empty() {
991            return Vec::new();
992        }
993
994        let system = self.lock_system();
995        let processes = system.processes();
996
997        let now = std::time::SystemTime::now()
998            .duration_since(std::time::UNIX_EPOCH)
999            .map(|d| d.as_secs())
1000            .unwrap_or(0);
1001
1002        // Build parent → children map once for all daemons
1003        let mut children_map: ParentToChildren = HashMap::new();
1004        for (child_pid, child) in processes {
1005            // Skip Linux userland threads: they report the same memory as their parent process,
1006            // so including them would cause massive double-counting.
1007            if child.thread_kind().is_some() {
1008                continue;
1009            }
1010            if let Some(ppid) = child.parent() {
1011                children_map
1012                    .entry(ppid.as_u32())
1013                    .or_default()
1014                    .push(child_pid.as_u32());
1015            }
1016        }
1017
1018        pids.iter()
1019            .map(|&pid| {
1020                let root_pid = sysinfo::Pid::from_u32(pid);
1021                let Some(root) = processes.get(&root_pid) else {
1022                    return (pid, None);
1023                };
1024
1025                let root_disk = root.disk_usage();
1026                let mut stats = ProcessStats {
1027                    cpu_percent: root.cpu_usage(),
1028                    memory_bytes: root.memory(),
1029                    uptime_secs: now.saturating_sub(root.start_time()),
1030                    disk_read_bytes: root_disk.read_bytes,
1031                    disk_write_bytes: root_disk.written_bytes,
1032                };
1033
1034                for child_pid in descendant_pids(pid, &children_map) {
1035                    if let Some(child) = processes.get(&sysinfo::Pid::from_u32(child_pid)) {
1036                        let disk = child.disk_usage();
1037                        stats.cpu_percent += child.cpu_usage();
1038                        stats.memory_bytes += child.memory();
1039                        stats.disk_read_bytes += disk.read_bytes;
1040                        stats.disk_write_bytes += disk.written_bytes;
1041                    }
1042                }
1043
1044                (pid, Some(stats))
1045            })
1046            .collect()
1047    }
1048    /// Refresh the process tree, then call [`Self::get_batch_group_stats`].
1049    ///
1050    /// Always performs a fresh full refresh. This is the correct entry point
1051    /// for callers that need a new sample rather than a cached one — notably
1052    /// the resource-limit checks, where counting the same cached CPU sample
1053    /// twice as two violations would silently weaken enforcement.
1054    ///
1055    /// Returns a PID → [`ProcessStats`] map so callers do not have to repeat
1056    /// the same `filter_map`/`collect` boilerplate.
1057    pub fn refresh_and_get_batch_stats(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1058        self.refresh_processes();
1059        self.get_batch_group_stats(pids)
1060            .into_iter()
1061            .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1062            .collect()
1063    }
1064
1065    /// Like [`Self::refresh_and_get_batch_stats`], but the full refresh is
1066    /// throttled to at most once per [`FULL_REFRESH_INTERVAL`]. Concurrent or
1067    /// frequent callers (web API polling, TUI frames) share a single scan and
1068    /// read the cached process table in between. Do not use this for resource
1069    /// enforcement: a cached CPU sample must not be counted as a new
1070    /// violation.
1071    pub fn refresh_and_get_batch_stats_if_stale(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1072        self.refresh_if_stale();
1073        self.get_batch_group_stats(pids)
1074            .into_iter()
1075            .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1076            .collect()
1077    }
1078
1079    /// Get process-tree stats for multiple root PIDs, omitting roots that no longer exist.
1080    pub fn get_batch_tree_stats_map(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1081        self.get_batch_group_stats(pids)
1082            .into_iter()
1083            .filter_map(|(pid, stats)| stats.map(|stats| (pid, stats)))
1084            .collect()
1085    }
1086
1087    /// Get process-tree stats (cpu%, memory bytes, uptime secs, disk I/O) for a given root PID.
1088    pub fn get_stats(&self, pid: u32) -> Option<ProcessStats> {
1089        self.get_batch_group_stats(&[pid])
1090            .into_iter()
1091            .next()
1092            .and_then(|(_, stats)| stats)
1093    }
1094
1095    /// Get extended process information for a given PID
1096    pub fn get_extended_stats(&self, pid: u32) -> Option<ExtendedProcessStats> {
1097        let system = self.lock_system();
1098        let processes = system.processes();
1099        let root_pid = sysinfo::Pid::from_u32(pid);
1100        let p = processes.get(&root_pid)?;
1101
1102        let now = std::time::SystemTime::now()
1103            .duration_since(std::time::UNIX_EPOCH)
1104            .map(|d| d.as_secs())
1105            .unwrap_or(0);
1106
1107        let root_disk = p.disk_usage();
1108        let mut aggregate_stats = ProcessStats {
1109            cpu_percent: p.cpu_usage(),
1110            memory_bytes: p.memory(),
1111            uptime_secs: now.saturating_sub(p.start_time()),
1112            disk_read_bytes: root_disk.read_bytes,
1113            disk_write_bytes: root_disk.written_bytes,
1114        };
1115
1116        let mut children_map: HashMap<sysinfo::Pid, Vec<sysinfo::Pid>> = HashMap::new();
1117        for (child_pid, child) in processes {
1118            if let Some(ppid) = child.parent() {
1119                children_map.entry(ppid).or_default().push(*child_pid);
1120            }
1121        }
1122
1123        let mut queue = std::collections::VecDeque::new();
1124        if let Some(direct_children) = children_map.get(&root_pid) {
1125            queue.extend(direct_children);
1126        }
1127        while let Some(child_pid) = queue.pop_front() {
1128            if let Some(child) = processes.get(&child_pid) {
1129                let disk = child.disk_usage();
1130                aggregate_stats.cpu_percent += child.cpu_usage();
1131                aggregate_stats.memory_bytes += child.memory();
1132                aggregate_stats.disk_read_bytes += disk.read_bytes;
1133                aggregate_stats.disk_write_bytes += disk.written_bytes;
1134            }
1135            if let Some(grandchildren) = children_map.get(&child_pid) {
1136                queue.extend(grandchildren);
1137            }
1138        }
1139
1140        Some(ExtendedProcessStats {
1141            name: p.name().to_string_lossy().to_string(),
1142            status: format!("{:?}", p.status()),
1143            cpu_percent: aggregate_stats.cpu_percent,
1144            memory_bytes: aggregate_stats.memory_bytes,
1145            virtual_memory_bytes: p.virtual_memory(),
1146            uptime_secs: aggregate_stats.uptime_secs,
1147            thread_count: p.tasks().map(|t| t.len()).unwrap_or(0),
1148        })
1149    }
1150}
1151
1152#[cfg(target_os = "linux")]
1153fn process_start_token(pid: u32) -> Option<u64> {
1154    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1155    let command_end = stat.rfind(')')?;
1156    // Fields after the command start at field 3 (state); starttime is field 22.
1157    stat.get(command_end + 1..)?
1158        .split_whitespace()
1159        .nth(19)?
1160        .parse()
1161        .ok()
1162}
1163
1164#[cfg(target_os = "macos")]
1165fn process_start_token(pid: u32) -> Option<u64> {
1166    let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::zeroed();
1167    let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
1168    let read = unsafe {
1169        libc::proc_pidinfo(
1170            pid as i32,
1171            libc::PROC_PIDTBSDINFO,
1172            0,
1173            info.as_mut_ptr().cast(),
1174            size,
1175        )
1176    };
1177    if read != size {
1178        return None;
1179    }
1180    let info = unsafe { info.assume_init() };
1181    info.pbi_start_tvsec
1182        .checked_mul(1_000_000)?
1183        .checked_add(info.pbi_start_tvusec)
1184}
1185
1186#[cfg(windows)]
1187fn process_start_token(pid: u32) -> Option<u64> {
1188    let handle = open_process_handle(pid).ok()?;
1189    process_start_token_from_handle(handle.0)
1190}
1191
1192#[cfg(windows)]
1193pub(crate) fn process_start_token_from_handle(handle: HANDLE) -> Option<u64> {
1194    let mut creation = FILETIME {
1195        dwLowDateTime: 0,
1196        dwHighDateTime: 0,
1197    };
1198    let mut exit = creation;
1199    let mut kernel = creation;
1200    let mut user = creation;
1201    let ok = unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
1202    if ok == 0 {
1203        return None;
1204    }
1205
1206    Some((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
1207}
1208
1209#[cfg(windows)]
1210struct ProcessHandle(HANDLE);
1211
1212#[cfg(windows)]
1213impl Drop for ProcessHandle {
1214    fn drop(&mut self) {
1215        unsafe {
1216            CloseHandle(self.0);
1217        }
1218    }
1219}
1220
1221#[cfg(windows)]
1222fn open_process_handle(pid: u32) -> std::io::Result<ProcessHandle> {
1223    let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
1224    if handle.is_null() {
1225        return Err(std::io::Error::last_os_error());
1226    }
1227    Ok(ProcessHandle(handle))
1228}
1229
1230/// Terminate `job` and wait for it to empty; true unless it is seen to empty,
1231/// so its processes may still be running.
1232#[cfg(windows)]
1233fn job_outlives_termination(job: &crate::win_job::DaemonJob) -> bool {
1234    // A failed termination proves nothing either way: the job may already be
1235    // empty, or still hold processes, so its count decides.
1236    debug!(
1237        "terminating daemon job; active_processes={:?}",
1238        job.active_processes()
1239    );
1240    let terminated = job.terminate();
1241    let emptied = job.wait_until_empty(JOB_EXIT_WAIT);
1242    debug!("terminated a daemon's job: {terminated}; emptied: {emptied}");
1243    !emptied
1244}
1245
1246/// Send Ctrl+C to the console of `pid` and wait up to `timeout` for it to exit.
1247///
1248/// Returns whether it exited. If not, the caller still has to terminate it,
1249/// including when no Ctrl+C was sent: the daemon shares the supervisor's
1250/// console, or `pitchfork interrupt` could not send it.
1251#[cfg(windows)]
1252fn interrupt_and_wait(pid: u32, timeout: Duration) -> bool {
1253    use crate::console_ctrl::EXIT_SHARED_CONSOLE;
1254    use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
1255    use windows_sys::Win32::System::Threading::{PROCESS_SYNCHRONIZE, WaitForSingleObject};
1256
1257    let started = Instant::now();
1258    debug!("stopping process {pid} with Ctrl+C; timeout={timeout:?}");
1259
1260    // Opened before the interrupt, so the wait below is for this process
1261    // even if it exits before the wait starts.
1262    let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
1263    if handle.is_null() {
1264        debug!(
1265            "cannot wait for process {pid}: {}",
1266            std::io::Error::last_os_error()
1267        );
1268        return false;
1269    }
1270    let handle = ProcessHandle(handle);
1271
1272    // The stop timeout covers sending Ctrl+C as well as the exit it asks for,
1273    // so a `pitchfork interrupt` that hangs cannot hold up the forced stop.
1274    // A timeout too long for an `Instant` (the setting accepts up to
1275    // u64::MAX seconds) waits as long as Win32 allows short of forever.
1276    let deadline = Instant::now().checked_add(timeout);
1277    let millis_left = || {
1278        let Some(deadline) = deadline else {
1279            return u32::MAX - 1;
1280        };
1281        let left = deadline.saturating_duration_since(Instant::now());
1282        u32::try_from(left.as_millis()).unwrap_or(u32::MAX - 1)
1283    };
1284
1285    let mut helper = match std::process::Command::new(&*crate::env::PITCHFORK_BIN)
1286        .args(["interrupt", "--pid"])
1287        .arg(pid.to_string())
1288        .arg("--supervisor-pid")
1289        .arg(std::process::id().to_string())
1290        .stdin(std::process::Stdio::null())
1291        .stdout(std::process::Stdio::null())
1292        .stderr(std::process::Stdio::piped())
1293        .hide_console_window()
1294        .spawn()
1295    {
1296        Ok(helper) => helper,
1297        Err(e) => {
1298            debug!("failed to spawn pitchfork interrupt for pid {pid}: {e}");
1299            return false;
1300        }
1301    };
1302    debug!(
1303        "spawned interrupt helper {} for pid {pid} after {:?}",
1304        helper.id(),
1305        started.elapsed()
1306    );
1307    let helper_handle = std::os::windows::io::AsRawHandle::as_raw_handle(&helper);
1308    let wait = unsafe { WaitForSingleObject(helper_handle as HANDLE, millis_left()) };
1309    if wait != WAIT_OBJECT_0 {
1310        if wait == WAIT_FAILED {
1311            debug!(
1312                "interrupt helper wait for pid {pid} failed: {}",
1313                std::io::Error::last_os_error()
1314            );
1315        }
1316        debug!(
1317            "pitchfork interrupt for pid {pid} did not finish after {:?}; wait={wait:#x}",
1318            started.elapsed()
1319        );
1320        let _ = helper.kill();
1321        let _ = helper.wait();
1322        return false;
1323    }
1324    match helper.wait_with_output() {
1325        Ok(o) if o.status.success() => {
1326            debug!(
1327                "sent Ctrl+C to process {pid}; interrupt helper finished after {:?}",
1328                started.elapsed()
1329            );
1330        }
1331        Ok(o) if o.status.code() == Some(EXIT_SHARED_CONSOLE) => {
1332            debug!("process {pid} shares the supervisor's console; not sending Ctrl+C");
1333            return false;
1334        }
1335        Ok(o) => {
1336            debug!(
1337                "pitchfork interrupt for pid {pid} exited with status {}: {}",
1338                o.status,
1339                String::from_utf8_lossy(&o.stderr).trim()
1340            );
1341            return false;
1342        }
1343        Err(e) => {
1344            debug!("failed to wait for pitchfork interrupt for pid {pid}: {e}");
1345            return false;
1346        }
1347    }
1348
1349    let wait = unsafe { WaitForSingleObject(handle.0, millis_left()) };
1350    if wait == WAIT_FAILED {
1351        debug!(
1352            "process wait for pid {pid} failed: {}",
1353            std::io::Error::last_os_error()
1354        );
1355    }
1356    debug!(
1357        "process {pid} wait after Ctrl+C ended after {:?}; wait={wait:#x}",
1358        started.elapsed()
1359    );
1360    wait == WAIT_OBJECT_0
1361}
1362
1363#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1364fn process_start_token(pid: u32) -> Option<u64> {
1365    let mut system = sysinfo::System::new();
1366    let sysinfo_pid = sysinfo::Pid::from_u32(pid);
1367    system.refresh_processes(ProcessesToUpdate::Some(&[sysinfo_pid]), true);
1368    system
1369        .process(sysinfo_pid)
1370        .map(|process| process.start_time())
1371}
1372
1373#[cfg(target_os = "linux")]
1374fn open_pidfd(pid: u32) -> std::io::Result<OwnedFd> {
1375    let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
1376    if fd < 0 {
1377        return Err(std::io::Error::last_os_error());
1378    }
1379    Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) })
1380}
1381
1382#[cfg(target_os = "linux")]
1383fn pidfd_is_running(pidfd: &OwnedFd) -> bool {
1384    match try_pidfd_is_running(pidfd) {
1385        Ok(running) => running,
1386        Err(err) => {
1387            warn!("failed to poll pidfd {}: {err}", pidfd.as_raw_fd());
1388            true
1389        }
1390    }
1391}
1392
1393#[cfg(target_os = "linux")]
1394fn try_pidfd_is_running(pidfd: &OwnedFd) -> std::io::Result<bool> {
1395    let mut pollfd = libc::pollfd {
1396        fd: pidfd.as_raw_fd(),
1397        events: libc::POLLIN,
1398        revents: 0,
1399    };
1400    let result = unsafe { libc::poll(&mut pollfd, 1, 0) };
1401    if result < 0 {
1402        return Err(std::io::Error::last_os_error());
1403    }
1404    Ok(result == 0)
1405}
1406
1407#[cfg(target_os = "linux")]
1408fn signal_pidfds(members: &[(u32, OwnedFd)], signal: i32, signal_name: &str) -> Result<()> {
1409    for (pid, pidfd) in members {
1410        if !pidfd_is_running(pidfd) {
1411            continue;
1412        }
1413        let result = unsafe {
1414            libc::syscall(
1415                libc::SYS_pidfd_send_signal,
1416                pidfd.as_raw_fd(),
1417                signal,
1418                std::ptr::null::<libc::siginfo_t>(),
1419                0,
1420            )
1421        };
1422        if result == -1 {
1423            let err = std::io::Error::last_os_error();
1424            if err.raw_os_error() == Some(libc::ESRCH) {
1425                continue;
1426            }
1427            return Err(miette::miette!(
1428                "failed to send {signal_name} to pinned process {pid}: {err}"
1429            ));
1430        }
1431    }
1432    Ok(())
1433}
1434
1435#[cfg(target_os = "linux")]
1436fn stop_pidfds(members: &[(u32, OwnedFd)]) -> Result<()> {
1437    signal_pidfds(members, libc::SIGSTOP, "SIGSTOP")?;
1438    for _ in 0..200 {
1439        if members.iter().all(|(pid, pidfd)| {
1440            !pidfd_is_running(pidfd) || matches!(linux_process_state(*pid), Some('T' | 't'))
1441        }) {
1442            return Ok(());
1443        }
1444        std::thread::sleep(std::time::Duration::from_millis(5));
1445    }
1446    Err(miette::miette!(
1447        "timed out while freezing orphan process group"
1448    ))
1449}
1450
1451#[cfg(target_os = "linux")]
1452fn extend_process_group_pidfds(
1453    pgid: i32,
1454    members: &mut Vec<(u32, OwnedFd)>,
1455) -> std::io::Result<usize> {
1456    let entries = std::fs::read_dir("/proc")?;
1457    let mut added = 0;
1458    for entry in entries {
1459        let entry = entry?;
1460        let Some(pid) = entry
1461            .file_name()
1462            .to_str()
1463            .and_then(|name| name.parse::<u32>().ok())
1464        else {
1465            continue;
1466        };
1467        let Some(observed_identity) = linux_process_identity(pid) else {
1468            continue;
1469        };
1470        if observed_identity.0 != pgid {
1471            continue;
1472        }
1473        let mut already_pinned = false;
1474        for (known_pid, pidfd) in members.iter() {
1475            if *known_pid == pid && try_pidfd_is_running(pidfd)? {
1476                already_pinned = true;
1477                break;
1478            }
1479        }
1480        if already_pinned {
1481            continue;
1482        }
1483
1484        let pidfd = match open_pidfd(pid) {
1485            Ok(pidfd) => pidfd,
1486            Err(err) if err.raw_os_error() == Some(libc::ESRCH) => continue,
1487            Err(err) => return Err(err),
1488        };
1489        if linux_process_identity(pid) != Some(observed_identity) {
1490            return Err(std::io::Error::other(format!(
1491                "process {pid} identity changed while pinning group {pgid}"
1492            )));
1493        }
1494        members.push((pid, pidfd));
1495        added += 1;
1496    }
1497    Ok(added)
1498}
1499
1500#[cfg(target_os = "linux")]
1501fn linux_process_identity(pid: u32) -> Option<(i32, u64)> {
1502    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1503    let command_end = stat.rfind(')')?;
1504    let fields: Vec<_> = stat.get(command_end + 1..)?.split_whitespace().collect();
1505    // Fields after the command start at field 3. pgrp is field 5 and the
1506    // scheduler-tick start token is field 22.
1507    Some((fields.get(2)?.parse().ok()?, fields.get(19)?.parse().ok()?))
1508}
1509
1510#[cfg(target_os = "linux")]
1511fn linux_process_state(pid: u32) -> Option<char> {
1512    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1513    let command_end = stat.rfind(')')?;
1514    stat.get(command_end + 1..)?
1515        .split_whitespace()
1516        .next()?
1517        .chars()
1518        .next()
1519}
1520
1521/// Walk only the requested descendants, visiting each PID once.
1522///
1523/// A process snapshot is not necessarily a tree: Windows retains the parent
1524/// PID after it exits, and PID reuse can introduce cycles. An ancestry walk
1525/// through an unrelated cycle used to spin while holding the system mutex.
1526/// See https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-process#parentprocessid.
1527fn descendant_pids(root: u32, children_map: &ParentToChildren) -> Vec<u32> {
1528    let mut seen = std::collections::HashSet::from([root]);
1529    let mut queue = std::collections::VecDeque::from([root]);
1530    let mut descendants = Vec::new();
1531
1532    while let Some(parent) = queue.pop_front() {
1533        if let Some(children) = children_map.get(&parent) {
1534            for &child in children {
1535                if seen.insert(child) {
1536                    descendants.push(child);
1537                    queue.push_back(child);
1538                }
1539            }
1540        }
1541    }
1542
1543    descendants
1544}
1545
1546#[derive(Debug, Clone, Copy)]
1547pub struct ProcessStats {
1548    pub cpu_percent: f32,
1549    pub memory_bytes: u64,
1550    pub uptime_secs: u64,
1551    pub disk_read_bytes: u64,
1552    pub disk_write_bytes: u64,
1553}
1554
1555impl ProcessStats {
1556    pub fn memory_display(&self) -> String {
1557        format_bytes(self.memory_bytes)
1558    }
1559
1560    pub fn cpu_display(&self) -> String {
1561        format!("{:.1}%", self.cpu_percent)
1562    }
1563
1564    pub fn uptime_display(&self) -> String {
1565        format_duration(self.uptime_secs)
1566    }
1567
1568    pub fn disk_read_display(&self) -> String {
1569        format_bytes_per_sec(self.disk_read_bytes)
1570    }
1571
1572    pub fn disk_write_display(&self) -> String {
1573        format_bytes_per_sec(self.disk_write_bytes)
1574    }
1575}
1576
1577#[derive(Debug, Clone)]
1578pub struct ExtendedProcessStats {
1579    pub name: String,
1580    pub status: String,
1581    pub cpu_percent: f32,
1582    pub memory_bytes: u64,
1583    pub virtual_memory_bytes: u64,
1584    pub uptime_secs: u64,
1585    pub thread_count: usize,
1586}
1587
1588fn format_bytes(bytes: u64) -> String {
1589    humanbyte::to_string(bytes, humanbyte::Format::IEC)
1590}
1591
1592pub(crate) fn format_duration(secs: u64) -> String {
1593    if secs < 60 {
1594        format!("{secs}s")
1595    } else if secs < 3600 {
1596        format!("{}m {}s", secs / 60, secs % 60)
1597    } else if secs < 86400 {
1598        let hours = secs / 3600;
1599        let mins = (secs % 3600) / 60;
1600        format!("{hours}h {mins}m")
1601    } else {
1602        let days = secs / 86400;
1603        let hours = (secs % 86400) / 3600;
1604        format!("{days}d {hours}h")
1605    }
1606}
1607
1608fn format_bytes_per_sec(bytes: u64) -> String {
1609    format!("{}/s", humanbyte::to_string(bytes, humanbyte::Format::IEC))
1610}
1611
1612/// Check whether a process group has no remaining members that we could
1613/// still be waiting on.
1614///
1615/// `killpg(pgid, 0)` probes for members without delivering a signal:
1616/// - success: at least one member remains that we may signal — keep waiting.
1617/// - ESRCH: the group is empty.
1618/// - EPERM: members remain, but none that we may signal (e.g. a root-owned
1619///   helper spawned inside the group). Our stop signal and SIGKILL never
1620///   reached them, so waiting longer cannot make progress — treat the group
1621///   as terminated, matching the previous leader-only behavior.
1622///
1623/// Unreaped zombies still count as members, but they are reaped promptly
1624/// (the leader by the supervisor's monitoring task via `child.wait()`,
1625/// orphans by init or the supervisor's PID-1 reaper), so the group empties
1626/// as soon as every member has actually exited.
1627#[cfg(unix)]
1628fn process_group_terminated(pgid: i32) -> bool {
1629    unsafe { libc::killpg(pgid, 0) != 0 }
1630}
1631
1632#[cfg(unix)]
1633fn signal_name(sig: i32) -> &'static str {
1634    match sig {
1635        libc::SIGHUP => "SIGHUP",
1636        libc::SIGINT => "SIGINT",
1637        libc::SIGQUIT => "SIGQUIT",
1638        libc::SIGTERM => "SIGTERM",
1639        libc::SIGUSR1 => "SIGUSR1",
1640        libc::SIGUSR2 => "SIGUSR2",
1641        libc::SIGKILL => "SIGKILL",
1642        _ => "UNKNOWN",
1643    }
1644}
1645
1646/// Whether a process in this state has exited and only waits to be reaped.
1647fn is_exited_status(status: sysinfo::ProcessStatus) -> bool {
1648    matches!(
1649        status,
1650        sysinfo::ProcessStatus::Zombie | sysinfo::ProcessStatus::Dead
1651    )
1652}
1653
1654#[cfg(test)]
1655mod format_tests {
1656    use super::*;
1657
1658    #[test]
1659    fn process_start_time_check_rejects_mismatch() {
1660        let procs = Procs::new();
1661        let pid = std::process::id();
1662        procs.refresh_pids(&[pid]);
1663        let actual = procs
1664            .start_time(pid)
1665            .expect("current process should have a start time");
1666
1667        assert_ne!(procs.start_time(pid), Some(actual.saturating_add(1)));
1668    }
1669
1670    #[test]
1671    fn test_format_bytes() {
1672        assert_eq!(format_bytes(512), "512 B");
1673        assert_eq!(format_bytes(1024), "1.0 KiB");
1674        assert_eq!(format_bytes(1536), "1.5 KiB");
1675        assert_eq!(format_bytes(50 * 1024 * 1024), "50.0 MiB");
1676        assert_eq!(format_bytes(3 * 1024 * 1024 * 1024), "3.0 GiB");
1677        // rolls over past GiB instead of showing e.g. "1100.0GB"
1678        assert_eq!(format_bytes(1100 * 1024 * 1024 * 1024), "1.1 TiB");
1679    }
1680
1681    #[test]
1682    fn test_format_bytes_per_sec() {
1683        assert_eq!(format_bytes_per_sec(512), "512 B/s");
1684        assert_eq!(format_bytes_per_sec(1536), "1.5 KiB/s");
1685        assert_eq!(format_bytes_per_sec(2 * 1024 * 1024), "2.0 MiB/s");
1686    }
1687}
1688
1689#[cfg(test)]
1690mod process_tree_tests {
1691    use super::{ParentToChildren, descendant_pids};
1692    use std::time::Duration;
1693
1694    // Keep a future traversal regression from hanging the test process itself.
1695    fn assert_descendant_walk(root: u32, edges: &[(u32, &[u32])], expected: &[u32]) {
1696        let children: ParentToChildren = edges
1697            .iter()
1698            .map(|&(pid, children)| (pid, children.to_vec()))
1699            .collect();
1700        let (send, recv) = std::sync::mpsc::channel();
1701        std::thread::spawn(move || {
1702            let _ = send.send(descendant_pids(root, &children));
1703        });
1704        let mut actual = recv
1705            .recv_timeout(Duration::from_secs(10))
1706            .expect("process snapshot traversal must terminate even when parent PIDs cycle");
1707        actual.sort_unstable();
1708        assert_eq!(actual, expected);
1709    }
1710
1711    #[test]
1712    fn descendants_ignore_unrelated_parent_cycles() {
1713        assert_descendant_walk(
1714            1,
1715            &[(1, &[2, 3]), (2, &[4]), (9, &[10]), (10, &[9])],
1716            &[2, 3, 4],
1717        );
1718    }
1719
1720    #[test]
1721    fn descendants_do_not_include_the_root_when_parent_pids_cycle() {
1722        assert_descendant_walk(1, &[(1, &[2]), (2, &[3]), (3, &[1])], &[2, 3]);
1723    }
1724
1725    #[test]
1726    fn descendants_visit_each_pid_once_for_self_links_and_duplicate_edges() {
1727        assert_descendant_walk(1, &[(1, &[1, 2, 2]), (2, &[3]), (3, &[3])], &[2, 3]);
1728    }
1729
1730    #[test]
1731    fn descendants_keep_live_children_of_an_absent_parent() {
1732        assert_descendant_walk(1, &[(1, &[2]), (2, &[3]), (8, &[9])], &[2, 3]);
1733        assert_descendant_walk(7, &[(1, &[2])], &[]);
1734    }
1735}
1736
1737#[cfg(all(test, unix))]
1738mod tests {
1739    use super::*;
1740
1741    use std::os::unix::process::CommandExt;
1742    use std::process::{Child, Command, Stdio};
1743    use std::time::{Duration, Instant};
1744
1745    struct ChildGuard(Child);
1746
1747    impl Drop for ChildGuard {
1748        fn drop(&mut self) {
1749            let pid = self.0.id() as i32;
1750            // The test process is started in its own session, so PID == PGID.
1751            let _ = unsafe { libc::killpg(pid, libc::SIGKILL) };
1752            let _ = self.0.wait();
1753        }
1754    }
1755
1756    #[tokio::test]
1757    async fn orphan_identity_checked_group_kill_rejects_mismatch() {
1758        let mut command = Command::new("sleep");
1759        command
1760            .arg("30")
1761            .stdin(Stdio::null())
1762            .stdout(Stdio::null())
1763            .stderr(Stdio::null());
1764        unsafe {
1765            command.pre_exec(|| {
1766                if libc::setsid() == -1 {
1767                    return Err(std::io::Error::last_os_error());
1768                }
1769                Ok(())
1770            });
1771        }
1772
1773        let child = command.spawn().expect("failed to spawn test process");
1774        let pid = child.id();
1775        let _child = ChildGuard(child);
1776
1777        PROCS.refresh_pids(&[pid]);
1778        let actual_start_time = PROCS
1779            .start_time(pid)
1780            .expect("test process should have a start time");
1781
1782        let killed = PROCS
1783            .kill_process_group_if_start_time_matches_async(
1784                pid,
1785                Some(actual_start_time.saturating_add(1)),
1786                libc::SIGTERM,
1787                Some(Duration::from_millis(100)),
1788            )
1789            .await
1790            .expect("identity-checked kill should not error");
1791
1792        assert!(!killed);
1793        assert!(PROCS.is_running(pid), "mismatched process must survive");
1794    }
1795
1796    /// On Unix platforms without a durable process handle the generation
1797    /// check runs inside the blocking operation, immediately before the
1798    /// signal: a matching generation is signalled, a mismatched one is
1799    /// refused at the last moment.
1800    #[cfg(all(unix, not(target_os = "linux")))]
1801    #[tokio::test]
1802    async fn identity_checked_group_kill_reverifies_inside_blocking_op() {
1803        let mut command = Command::new("sleep");
1804        command
1805            .arg("30")
1806            .stdin(Stdio::null())
1807            .stdout(Stdio::null())
1808            .stderr(Stdio::null());
1809        unsafe {
1810            command.pre_exec(|| {
1811                if libc::setsid() == -1 {
1812                    return Err(std::io::Error::last_os_error());
1813                }
1814                Ok(())
1815            });
1816        }
1817
1818        let child = command.spawn().expect("failed to spawn test process");
1819        let pid = child.id();
1820        let mut child = ChildGuard(child);
1821
1822        PROCS.refresh_pids(&[pid]);
1823        let actual_start_time = PROCS
1824            .start_time(pid)
1825            .expect("test process should have a start time");
1826
1827        let killed = PROCS
1828            .kill_process_group_if_start_time_matches_async(
1829                pid,
1830                Some(actual_start_time),
1831                libc::SIGTERM,
1832                Some(Duration::from_millis(100)),
1833            )
1834            .await
1835            .expect("identity-checked kill should not error");
1836
1837        assert!(killed, "matching generation must be signalled");
1838        // A terminated child remains visible to kill(pid, 0) until its parent
1839        // reaps it. Poll with a deadline so a missed signal still fails.
1840        let deadline = Instant::now() + Duration::from_secs(2);
1841        while child.0.try_wait().unwrap().is_none() {
1842            assert!(Instant::now() < deadline, "signalled child must exit");
1843            tokio::time::sleep(Duration::from_millis(10)).await;
1844        }
1845        assert!(
1846            !PROCS.is_running(pid),
1847            "signalled process group must be gone"
1848        );
1849    }
1850
1851    #[test]
1852    fn get_stats_includes_descendant_rss() {
1853        let mut command = Command::new("sh");
1854        command
1855            .args(["-c", "sleep 30 & wait"])
1856            .stdin(Stdio::null())
1857            .stdout(Stdio::null())
1858            .stderr(Stdio::null());
1859        unsafe {
1860            command.pre_exec(|| {
1861                if libc::setsid() == -1 {
1862                    return Err(std::io::Error::last_os_error());
1863                }
1864                Ok(())
1865            });
1866        }
1867
1868        let parent = command.spawn().expect("failed to spawn process tree");
1869        let parent_pid = parent.id();
1870        let _parent = ChildGuard(parent);
1871
1872        let procs = Procs::new();
1873        let deadline = Instant::now() + Duration::from_secs(5);
1874        let mut child_pids = Vec::new();
1875        while Instant::now() < deadline {
1876            procs.refresh_processes();
1877            child_pids = procs.all_children(parent_pid);
1878            if !child_pids.is_empty() {
1879                break;
1880            }
1881            std::thread::sleep(Duration::from_millis(50));
1882        }
1883        assert!(
1884            !child_pids.is_empty(),
1885            "test process tree did not appear under parent pid {parent_pid}"
1886        );
1887
1888        procs.refresh_processes();
1889        child_pids = procs.all_children(parent_pid);
1890        assert!(
1891            !child_pids.is_empty(),
1892            "test process tree disappeared under parent pid {parent_pid}"
1893        );
1894        let root_pid = sysinfo::Pid::from_u32(parent_pid);
1895        let direct_memory = {
1896            let system = procs.lock_system();
1897            system
1898                .process(root_pid)
1899                .expect("parent process should exist")
1900                .memory()
1901        };
1902        let descendant_memory = {
1903            let system = procs.lock_system();
1904            child_pids
1905                .iter()
1906                .filter_map(|pid| system.process(sysinfo::Pid::from_u32(*pid)))
1907                .map(|process| process.memory())
1908                .sum::<u64>()
1909        };
1910        assert!(
1911            descendant_memory > 0,
1912            "descendants {child_pids:?} should have nonzero RSS"
1913        );
1914
1915        let stats = procs
1916            .get_stats(parent_pid)
1917            .expect("parent process should have aggregate stats");
1918
1919        assert_eq!(
1920            stats.memory_bytes,
1921            direct_memory + descendant_memory,
1922            "get_stats should include descendant RSS for parent pid {parent_pid}; \
1923             descendants: {child_pids:?}, direct RSS: {direct_memory}, \
1924             descendant RSS: {descendant_memory}, reported RSS: {}",
1925            stats.memory_bytes
1926        );
1927    }
1928
1929    #[test]
1930    fn full_refresh_is_throttled_by_ttl() {
1931        let procs = Procs::new();
1932
1933        // First call always refreshes: the table starts empty.
1934        assert!(
1935            procs.last_full_refresh.lock().unwrap().is_none(),
1936            "fresh Procs should have no recorded refresh"
1937        );
1938        procs.refresh_if_stale();
1939        let first = procs.last_full_refresh.lock().unwrap().unwrap();
1940        assert!(first.elapsed() < FULL_REFRESH_INTERVAL);
1941
1942        // A second call within the TTL window must NOT refresh again: the
1943        // recorded timestamp must stay identical (a refresh would advance it).
1944        procs.refresh_if_stale();
1945        let second = procs.last_full_refresh.lock().unwrap().unwrap();
1946        assert_eq!(
1947            second, first,
1948            "refresh_if_stale within TTL must skip the refresh and keep the timestamp"
1949        );
1950
1951        // Simulate an expired TTL: force the recorded timestamp into the past,
1952        // then confirm the next call refreshes and advances the timestamp.
1953        let expired = Instant::now()
1954            .checked_sub(FULL_REFRESH_INTERVAL + Duration::from_secs(1))
1955            .expect("system has been up long enough to backdate by 6s");
1956        *procs.last_full_refresh.lock().unwrap() = Some(expired);
1957        procs.refresh_if_stale();
1958        let third = procs.last_full_refresh.lock().unwrap().unwrap();
1959        assert!(
1960            third > expired,
1961            "refresh_if_stale after expired TTL must refresh and advance the timestamp"
1962        );
1963        assert!(
1964            third.elapsed() < FULL_REFRESH_INTERVAL,
1965            "fresh timestamp after expired-TTL refresh should be recent"
1966        );
1967    }
1968}