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