Skip to main content

agentmux_srv/bootstrap/
watchers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6/// Start a ppid polling watchdog on Linux/macOS.
7/// If the parent process dies, getppid() changes (reparented to init/launchd).
8/// This is safer than PR_SET_PDEATHSIG which tracks the parent *thread*, not process,
9/// and can fire spuriously with async runtimes like Tokio.
10///
11/// `original_ppid` is the parent read at startup, not a fresh getppid(): a
12/// fallback can start after the parent already died and srv was reparented,
13/// and a fresh baseline would then never change. Checks once before sleeping.
14#[cfg(any(target_os = "linux", target_os = "macos"))]
15fn start_ppid_watchdog(original_ppid: u32) {
16    std::thread::spawn(move || {
17        loop {
18            let current_ppid = unsafe { libc::getppid() } as u32;
19            if current_ppid != original_ppid {
20                eprintln_lossy!(
21                    "parent process died (ppid changed {} -> {}), shutting down",
22                    original_ppid, current_ppid
23                );
24                std::process::exit(0);
25            }
26            std::thread::sleep(std::time::Duration::from_secs(2));
27        }
28    });
29}
30
31/// Event-driven parent process watcher using kqueue (macOS) or pidfd (Linux).
32/// Monitors a specific PID and exits when that process terminates.
33/// Falls back to PPID polling on older Linux kernels without pidfd support.
34#[cfg(target_os = "macos")]
35fn start_parent_watcher(parent_pid: u32) {
36    std::thread::spawn(move || {
37        unsafe {
38            let kq = libc::kqueue();
39            if kq < 0 {
40                eprintln_lossy!(
41                    "kqueue() failed (errno={}), falling back to ppid watchdog",
42                    *libc::__error()
43                );
44                let _ = kq;
45                start_ppid_watchdog(parent_pid);
46                return;
47            }
48
49            // Register EVFILT_PROC + NOTE_EXIT on the parent PID.
50            let mut changelist: [libc::kevent; 1] = std::mem::zeroed();
51            changelist[0] = libc::kevent {
52                ident: parent_pid as usize,
53                filter: libc::EVFILT_PROC,
54                flags: libc::EV_ADD | libc::EV_ONESHOT,
55                fflags: libc::NOTE_EXIT,
56                data: 0,
57                udata: std::ptr::null_mut(),
58            };
59
60            let ret = libc::kevent(
61                kq,
62                changelist.as_ptr(),
63                1,
64                std::ptr::null_mut(),
65                0,
66                std::ptr::null(),
67            );
68
69            if ret < 0 {
70                let errno = *libc::__error();
71                libc::close(kq);
72                if errno == libc::ESRCH {
73                    // Parent already dead
74                    eprintln_lossy!(
75                        "parent process {} already exited (ESRCH during kqueue registration), shutting down",
76                        parent_pid
77                    );
78                    std::process::exit(0);
79                }
80                eprintln_lossy!(
81                    "kevent() registration failed (errno={}), falling back to ppid watchdog",
82                    errno
83                );
84                start_ppid_watchdog(parent_pid);
85                return;
86            }
87
88            eprintln_lossy!("kqueue EVFILT_PROC registered for parent pid {}", parent_pid);
89
90            // Race condition guard: check if the parent is still alive after registering.
91            // If it died between our registration and this check, we might miss the event.
92            if libc::kill(parent_pid as i32, 0) != 0 && *libc::__error() == libc::ESRCH {
93                libc::close(kq);
94                eprintln_lossy!(
95                    "parent process {} already exited (post-registration check), shutting down",
96                    parent_pid
97                );
98                std::process::exit(0);
99            }
100
101            // Block until the parent exits. A signal srv catches (SIGCHLD
102            // from any exiting child) can interrupt the wait with EINTR
103            // while the parent is alive: wait again.
104            let mut eventlist: [libc::kevent; 1] = std::mem::zeroed();
105            let waited = loop {
106                let n = libc::kevent(
107                    kq,
108                    std::ptr::null(),
109                    0,
110                    eventlist.as_mut_ptr(),
111                    1,
112                    std::ptr::null(),
113                );
114                if n > 0 {
115                    break Ok(());
116                }
117                if n == 0 {
118                    continue;
119                }
120                let err = std::io::Error::last_os_error();
121                if err.raw_os_error() != Some(libc::EINTR) {
122                    break Err(err);
123                }
124            };
125            libc::close(kq);
126
127            match waited {
128                Ok(()) => {
129                    eprintln_lossy!(
130                        "parent process {} exited (kqueue EVFILT_PROC), shutting down",
131                        parent_pid
132                    );
133                    std::process::exit(0);
134                }
135                Err(e) => {
136                    // A failed wait says nothing about the parent: keep
137                    // watching it the slow way rather than shutting down.
138                    eprintln_lossy!(
139                        "kevent() wait failed ({}), falling back to ppid watchdog",
140                        e
141                    );
142                    start_ppid_watchdog(parent_pid);
143                }
144            }
145        }
146    });
147}
148
149/// Event-driven parent process watcher using pidfd_open (Linux 5.3+).
150/// Falls back to PPID polling on older kernels without pidfd support.
151#[cfg(target_os = "linux")]
152fn start_parent_watcher(parent_pid: u32) {
153    std::thread::spawn(move || {
154        unsafe {
155            // Try pidfd_open (syscall 434 on x86_64, 434 on aarch64)
156            let pidfd = libc::syscall(libc::SYS_pidfd_open, parent_pid as libc::c_int, 0 as libc::c_int);
157
158            if pidfd < 0 {
159                let errno = *libc::__errno_location();
160                if errno == libc::ESRCH {
161                    // Parent already dead
162                    eprintln_lossy!(
163                        "parent process {} already exited (ESRCH from pidfd_open), shutting down",
164                        parent_pid
165                    );
166                    std::process::exit(0);
167                }
168                // ENOSYS means kernel doesn't support pidfd_open — fall back
169                eprintln_lossy!(
170                    "pidfd_open() failed (errno={}), falling back to ppid watchdog",
171                    errno
172                );
173                start_ppid_watchdog(parent_pid);
174                return;
175            }
176
177            let pidfd = pidfd as libc::c_int;
178
179            // Race condition guard: verify parent is still alive
180            if libc::kill(parent_pid as i32, 0) != 0 && *libc::__errno_location() == libc::ESRCH {
181                libc::close(pidfd);
182                eprintln_lossy!(
183                    "parent process {} already exited (post-pidfd check), shutting down",
184                    parent_pid
185                );
186                std::process::exit(0);
187            }
188
189            let waited = wait_for_pidfd_exit(pidfd);
190            libc::close(pidfd);
191
192            match waited {
193                Ok(()) => {
194                    eprintln_lossy!(
195                        "parent process {} exited (pidfd poll), shutting down",
196                        parent_pid
197                    );
198                    std::process::exit(0);
199                }
200                Err(e) => {
201                    // A failed wait says nothing about the parent: keep
202                    // watching it the slow way rather than shutting down.
203                    eprintln_lossy!(
204                        "poll() on pidfd failed ({}), falling back to ppid watchdog",
205                        e
206                    );
207                    start_ppid_watchdog(parent_pid);
208                }
209            }
210        }
211    });
212}
213
214/// Blocks until the process behind `pidfd` exits.
215///
216/// poll() is never restarted after a signal handler runs (signal(7)), and
217/// srv catches SIGCHLD, which every exiting child sends. When the kernel
218/// delivers one to this thread, poll() fails with EINTR while the parent is
219/// still alive, so retry; only a readable pidfd means the parent exited.
220#[cfg(target_os = "linux")]
221fn wait_for_pidfd_exit(pidfd: libc::c_int) -> std::io::Result<()> {
222    let mut pfd = libc::pollfd {
223        fd: pidfd,
224        events: libc::POLLIN,
225        revents: 0,
226    };
227    loop {
228        let ret = unsafe { libc::poll(&mut pfd, 1, -1) }; // infinite timeout
229        if ret > 0 {
230            return Ok(());
231        }
232        if ret == 0 {
233            continue;
234        }
235        let err = std::io::Error::last_os_error();
236        if err.raw_os_error() != Some(libc::EINTR) {
237            return Err(err);
238        }
239    }
240}
241
242/// Step -1: Crash monitor branch — must be checked before any other initialization.
243/// The monitor process runs a blocking minidumper::Server and exits when the
244/// main process disconnects. It does not run any backend logic.
245///
246/// Returns `true` if this process was the crash-monitor branch (in which case
247/// `main()` must return immediately without doing anything else).
248pub fn maybe_run_crash_monitor() -> bool {
249    #[cfg(windows)]
250    {
251        let args: Vec<String> = std::env::args().collect();
252        if args.iter().any(|a| a == "--crash-monitor") {
253            // The srv this monitor serves: it names the socket the two talk over.
254            let parent_pid = args
255                .iter()
256                .position(|a| a == "--parent-pid")
257                .and_then(|i| args.get(i + 1))
258                .and_then(|v| v.parse().ok());
259            crate::crash_monitor::run_monitor(parent_pid);
260            return true;
261        }
262    }
263    false
264}
265
266/// Step 0: Start parent process watcher BEFORE tokio runtime does real work (Linux/macOS only).
267/// On Windows, the frontend uses a Job Object with KILL_ON_JOB_CLOSE instead.
268/// Uses getppid() to get the parent PID, then kqueue/pidfd to watch it (event-driven,
269/// zero CPU). Falls back to PPID polling if kqueue/pidfd setup fails or parent is init/launchd.
270pub fn install_process_watchers() {
271    #[cfg(any(target_os = "linux", target_os = "macos"))]
272    {
273        let ppid = unsafe { libc::getppid() } as u32;
274        if ppid <= 1 {
275            // Parent is init/launchd — can't meaningfully watch it, use polling fallback
276            start_ppid_watchdog(ppid);
277        } else {
278            start_parent_watcher(ppid);
279        }
280    }
281}
282
283/// Step 0b: Attach out-of-process crash dump handler (Windows only).
284/// Spawns self with --crash-monitor and installs a VEH handler.
285/// The returned guard must stay alive — dropping it uninstalls the VEH handler.
286/// Non-fatal: if the monitor fails to start, the process continues normally
287/// and WER LocalDumps still captures __fastfail crashes independently.
288#[cfg(windows)]
289pub fn install_crash_guard() -> Option<crate::crash_monitor::CrashHandlerGuard> {
290    crate::crash_monitor::spawn_and_attach()
291}
292
293#[cfg(all(test, target_os = "linux"))]
294mod tests {
295    use super::wait_for_pidfd_exit;
296    use std::process::Command;
297    use std::sync::mpsc;
298    use std::time::Duration;
299
300    extern "C" fn ignore_signal(_: libc::c_int) {}
301
302    /// On 2026-10-14 srv exited while its launcher was alive: a signal it
303    /// catches landed on the watcher thread, poll() returned EINTR, and the
304    /// watcher took that for the launcher exiting. The whole app quit.
305    #[test]
306    fn a_signal_does_not_end_the_wait_only_the_process_exiting_does() {
307        // A caught signal without SA_RESTART, as srv's SIGCHLD is to poll().
308        unsafe {
309            let mut action: libc::sigaction = std::mem::zeroed();
310            action.sa_sigaction = ignore_signal as *const () as usize;
311            libc::sigemptyset(&mut action.sa_mask);
312            assert_eq!(
313                libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
314                0
315            );
316        }
317
318        let mut parent = Command::new("sleep")
319            .arg("60")
320            .spawn()
321            .expect("spawn sleep");
322        let pidfd = unsafe { libc::syscall(libc::SYS_pidfd_open, parent.id() as libc::c_int, 0) };
323        if pidfd < 0 {
324            let err = std::io::Error::last_os_error();
325            parent.kill().unwrap();
326            parent.wait().unwrap();
327            // A kernel before 5.3, or a seccomp policy that blocks it: srv
328            // uses the ppid watchdog there, and there is no pidfd to test.
329            if matches!(err.raw_os_error(), Some(libc::ENOSYS) | Some(libc::EPERM)) {
330                eprintln!("skipping: pidfd_open unavailable ({err})");
331                return;
332            }
333            panic!("pidfd_open: {err}");
334        }
335        let pidfd = pidfd as libc::c_int;
336
337        let (thread_tx, thread_rx) = mpsc::channel();
338        let (done_tx, done_rx) = mpsc::channel();
339        std::thread::spawn(move || {
340            thread_tx.send(unsafe { libc::pthread_self() }).unwrap();
341            done_tx
342                .send(wait_for_pidfd_exit(pidfd).map_err(|e| e.to_string()))
343                .unwrap();
344        });
345        let waiter = thread_rx.recv().unwrap();
346
347        for _ in 0..10 {
348            std::thread::sleep(Duration::from_millis(20));
349            assert_eq!(unsafe { libc::pthread_kill(waiter, libc::SIGUSR1) }, 0);
350        }
351        let early = done_rx.recv_timeout(Duration::from_millis(300));
352        assert!(
353            early.is_err(),
354            "the wait ended while the process was alive: {early:?}"
355        );
356
357        parent.kill().unwrap();
358        parent.wait().unwrap();
359        let result = done_rx
360            .recv_timeout(Duration::from_secs(5))
361            .expect("the wait never ended");
362        unsafe { libc::close(pidfd) };
363        assert_eq!(result, Ok(()));
364    }
365}