From e3f858bb4cc80835a0ecbe5c17a5cf037b3215c3 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Thu, 3 Dec 2026 18:30:31 +1100 Subject: [PATCH] fix(staged): detach local agents from the terminal and stop them on every exit Local ACP agents now start in a session of their own (`setsid()` in `pre_exec`), so they have no controlling terminal. Before, an agent started through an interactive login shell (or any shell it started) shared Staged's session and could make itself the terminal's foreground process group. Staged, run from a terminal, was then stopped with SIGTTOU/SIGTTIN and looked like it was "quitting" when sessions were resumed. Remote (Blox) proxies keep `process_group(0)`, so the SIGINT the driver sends them still works. `libc` moves to the `cfg(unix)` dependencies. Detaching agents also takes away the cleanup the terminal used to do (SIGHUP when it closes, SIGINT on Ctrl-C). So every way out of Staged now stops agents explicitly, through a new `acp_client::agent_reaper`: - Session end and normal quit: `AgentGroup::stop` sends SIGTERM to the agent's group (`kill(-pgid)`) and to every descendant, including children that left the group via `setsid` (found by walking ppid links in a libproc / `/proc` snapshot). It waits a 1 s grace, then SIGKILLs whatever is left. Processes are remembered by (pid, start time), so a recycled pid is never signalled. An `AgentGroup` dropped without `stop` (error paths) SIGKILLs its group. - SIGINT, SIGTERM, SIGHUP: tokio signal handlers run the normal shutdown (`shutdown_cleanup`, then `app.exit(128+n)`). A second signal, or 15 s without exiting, forces `process::exit`. - Panic: the watchdog below covers it. With no watchdog, a fatal panic hook and `RunEvent::Exit` reap in process (`reap_now_if_unwatched`). - Hard death (SIGKILL, abort, crash): a watchdog process. Staged re-execs its own binary with `--staged-agent-reaper` and keeps the write end of a pipe to the watchdog's stdin. Every group Staged starts or stops is announced over it (`L`/`R`/`U `). When the pipe reaches EOF, the watchdog SIGTERMs, waits 2 s, then SIGKILLs every group still registered, and exits. Why a pipe-holding watchdog for hard death: - macOS has no PR_SET_PDEATHSIG. - An agent seeing its stdin close says nothing about the tool shells and MCP servers it started. - Nothing inside Staged runs after SIGKILL. - The kernel closes Staged's end of the pipe however Staged dies, so EOF is a death signal that pid reuse cannot fool. A kqueue NOTE_EXIT on Staged's pid could be fooled that way, and it would still need a separate channel for the registrations. The pipe carries them too. - The write end is O_CLOEXEC, so no agent inherits it and holds it open. How the watchdog is hardened: - It runs in its own session. - It ignores INT/TERM/HUP/QUIT/PIPE/TTIN/TTOU, set before exec, so Ctrl-C, a closed terminal or a `kill` meant for Staged cannot take it down first. - It closes inherited descriptors. - It re-walks the watched groups every 500 ms. An agent notices Staged's death at the same moment as the watchdog and may exit first. Its detached children are then re-parented to launchd, and only an earlier walk still ties them to it (found by the end-to-end run below). - If it dies under a running Staged, it is restarted (up to 3 times) and every group is replayed. Remote proxies are registered as remote groups. On Staged's death they get SIGKILL only, never SIGINT, so remote turns keep running, as on a quit. Their ordinary teardown stays with the driver. Startup orphan reaping is not done. Telling an orphan of a previous Staged from an agent of a concurrently running one would need persisted state. The watchdog makes that state unnecessary for every case except the watchdog and Staged being SIGKILLed together. Verified against the real app binary with a fake `claude-agent-acp`, checked with `ps`. The fake agent leaves behind a TERM-ignoring child and a setsid-detached grandchild pair. Agents were checked to lead their own session with no tty. For each exit path, the whole tree was gone after Staged went and no watchdog was left: - session end (the other session's tree was untouched); - Cmd-Q / Apple Event quit; - SIGTERM, SIGINT, SIGHUP; - terminal close (SIGHUP via a pty); - SIGKILL; - SIGABRT; - killing the watchdog, then SIGKILLing Staged (the watchdog was restarted). Not covered: - Staged and the watchdog both being SIGKILLed at once (`kill -9 -1`, or a `pkill -9 -f` that matches both). - A descendant that detaches and is orphaned within 500 ms of Staged's death. Signed-off-by: Matt Toohey Co-Authored-By: Claude Opus 5.5 --- apps/staged/src-tauri/Cargo.toml | 2 +- apps/staged/src-tauri/src/agent_watchdog.rs | 70 ++++ apps/staged/src-tauri/src/app_lifecycle.rs | 11 +- .../src/app_lifecycle/exit_signals.rs | 73 ++++ apps/staged/src-tauri/src/lib.rs | 7 + apps/staged/src-tauri/src/main.rs | 10 + crates/acp-client/Cargo.toml | 2 - crates/acp-client/src/agent_reaper.rs | 305 ++++++++++++++++ .../src/agent_reaper/process_tree.rs | 341 ++++++++++++++++++ crates/acp-client/src/agent_reaper/tests.rs | 331 +++++++++++++++++ .../acp-client/src/agent_reaper/watchdog.rs | 278 ++++++++++++++ crates/acp-client/src/driver.rs | 68 +++- crates/acp-client/src/driver/attach.rs | 6 + .../acp-client/src/driver/remote_process.rs | 4 + crates/acp-client/src/lib.rs | 1 + 15 files changed, 1489 insertions(+), 20 deletions(-) create mode 100644 apps/staged/src-tauri/src/agent_watchdog.rs create mode 100644 apps/staged/src-tauri/src/app_lifecycle/exit_signals.rs create mode 100644 crates/acp-client/src/agent_reaper.rs create mode 100644 crates/acp-client/src/agent_reaper/process_tree.rs create mode 100644 crates/acp-client/src/agent_reaper/tests.rs create mode 100644 crates/acp-client/src/agent_reaper/watchdog.rs diff --git a/apps/staged/src-tauri/Cargo.toml b/apps/staged/src-tauri/Cargo.toml index 7771aa15d..59e5d062d 100644 --- a/apps/staged/src-tauri/Cargo.toml +++ b/apps/staged/src-tauri/Cargo.toml @@ -44,7 +44,7 @@ dirs = "7.0" tauri-plugin-clipboard-manager = "2.4.1" tauri-plugin-window-state = "2.5.0" reqwest = { version = "0.13.5", features = ["json"] } -tokio = { version = "1.53.1", features = ["sync", "process", "io-util", "macros", "rt-multi-thread", "time", "fs"] } +tokio = { version = "1.53.1", features = ["sync", "process", "io-util", "macros", "rt-multi-thread", "time", "fs", "signal"] } tauri-plugin-opener = "2" tauri-plugin-dialog = "2" tauri-plugin-process = "2" diff --git a/apps/staged/src-tauri/src/agent_watchdog.rs b/apps/staged/src-tauri/src/agent_watchdog.rs new file mode 100644 index 000000000..0f64a4f5c --- /dev/null +++ b/apps/staged/src-tauri/src/agent_watchdog.rs @@ -0,0 +1,70 @@ +//! Making sure local agents never outlive Staged. +//! +//! Local agents run in sessions of their own, off Staged's terminal (see +//! `acp_client::agent_reaper`), so nothing stops them for free when Staged +//! goes. A session ending and a quit stop them through the driver; this +//! module covers the rest: +//! +//! - [`start`] starts the watchdog — this binary re-run with +//! [`WATCHDOG_ARG`] (see `main`) — which stops every agent still running +//! when Staged's end of its pipe closes, however Staged died: SIGKILL, an +//! abort, a crash, a panic, a signal. +//! - A fatal panic, and the end of every exit that goes through the event +//! loop, stop the agents in process should the watchdog not be running +//! ([`reap_now_if_unwatched`]). +//! - SIGINT, SIGTERM and SIGHUP quit through the ordinary shutdown (see +//! `app_lifecycle::exit_signals`), so sessions are recorded as stopped by +//! the quit rather than found orphaned on the next launch. + +use std::thread::ThreadId; +use std::time::Duration; + +pub use acp_client::agent_reaper::WATCHDOG_ARG; +use acp_client::agent_reaper::{reap_now_if_unwatched, start_watchdog}; + +/// How long agents get between SIGTERM and SIGKILL when Staged stops them +/// itself on its way out, with no watchdog to do it after the exit. +const IN_PROCESS_GRACE: Duration = Duration::from_millis(500); + +/// Start the watchdog and the fatal-panic fallback. Call once, on the main +/// thread, before any agent can start. The outcome is for the log, which is +/// not set up yet. +pub fn start() -> Result<(), String> { + stop_agents_on_a_fatal_panic(std::thread::current().id()); + let program = std::env::current_exe() + .map_err(|error| format!("cannot find Staged's own binary: {error}"))?; + start_watchdog(&program) + .map_err(|error| format!("cannot start {} {WATCHDOG_ARG}: {error}", program.display())) +} + +/// Log what [`start`] returned. +pub fn log_start(started: &Result<(), String>) { + match started { + Ok(()) => log::info!("Agent reaper watchdog started"), + Err(error) => log::warn!( + "Agent reaper watchdog not started ({error}); agents will only be stopped on exits \ + Staged sees" + ), + } +} + +/// The end of an exit Staged sees: stop whatever agents the shutdown left, +/// unless the watchdog will. +pub fn on_exit() { + if reap_now_if_unwatched(IN_PROCESS_GRACE) { + log::warn!("Stopped agents left running at exit without the watchdog"); + } +} + +/// A panic that ends the process — one on `main_thread`, or any when panics +/// abort — stops the agents in process when there is no watchdog. A panic on +/// another thread leaves Staged running, and its agents with it. +fn stop_agents_on_a_fatal_panic(main_thread: ThreadId) { + let report_panic = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + report_panic(info); + if cfg!(panic = "abort") || std::thread::current().id() == main_thread { + reap_now_if_unwatched(IN_PROCESS_GRACE); + } + })); +} diff --git a/apps/staged/src-tauri/src/app_lifecycle.rs b/apps/staged/src-tauri/src/app_lifecycle.rs index 52bbb2678..ec25b1b3e 100644 --- a/apps/staged/src-tauri/src/app_lifecycle.rs +++ b/apps/staged/src-tauri/src/app_lifecycle.rs @@ -18,9 +18,12 @@ //! **Quitting with sessions running asks first, then stops them cleanly.** //! [`request_quit`] gates on active sessions and asks; [`shutdown_cleanup`] //! cancels sessions with [`CompletionReason::AppQuit`] and stops actions. That -//! cancel is the only thing that shuts an agent down: ACP children are spawned -//! with `process_group(0)` and `kill_on_drop`, and `process::exit` runs no -//! destructors, so a bare exit leaves the agent CLIs running. Blox sessions are +//! cancel is what shuts an agent down cleanly: local ACP agents run in +//! sessions of their own, off Staged's terminal, and `process::exit` runs no +//! destructors. Whatever a quit leaves running — or a death the app never +//! sees, SIGKILL or a crash — the agent reaper's watchdog stops once the +//! process is gone (see [`crate::agent_watchdog`]); SIGINT, SIGTERM and SIGHUP +//! come through here as a quit (see [`exit_signals`]). Blox sessions are //! the exception: their agent runs on the workstation, so a quit *detaches* //! them instead — it kills only the local `blox acp` proxy, sending no //! `session/cancel`, and leaves the row `disconnected` with the turn still @@ -67,6 +70,8 @@ use crate::session_commands::{self, ActiveSessionInfo}; use crate::session_runner::SessionRegistry; use crate::store::{CompletionReason, Session, SessionStatus, Store}; +#[cfg(unix)] +pub(crate) mod exit_signals; pub(crate) mod window_raise; pub mod window_reveal; pub(crate) mod window_use; diff --git a/apps/staged/src-tauri/src/app_lifecycle/exit_signals.rs b/apps/staged/src-tauri/src/app_lifecycle/exit_signals.rs new file mode 100644 index 000000000..3fee53216 --- /dev/null +++ b/apps/staged/src-tauri/src/app_lifecycle/exit_signals.rs @@ -0,0 +1,73 @@ +//! SIGINT, SIGTERM and SIGHUP: quit the way a confirmed quit does. +//! +//! Ctrl-C in the terminal Staged was started from, the terminal closing, or a +//! plain `kill`. Local agents no longer share Staged's terminal (they run in +//! sessions of their own), so those signals no longer reach them; and left to +//! their default action they would end Staged without recording anything, +//! leaving its sessions for the next launch to find orphaned. So the first +//! one runs [`shutdown_cleanup`] — no confirmation, the signal is the answer +//! — and exits. A second signal, or a shutdown that overruns +//! [`FORCED_EXIT_AFTER`], exits at once; the agent reaper's watchdog stops +//! whatever agents are left once the process is gone. + +use std::time::Duration; + +use tauri::AppHandle; +use tokio::signal::unix::{signal, Signal, SignalKind}; + +use super::shutdown_cleanup; + +/// How long a signalled quit may take before the process exits anyway. Well +/// past the shutdown's own budgets, which are what a healthy quit spends. +const FORCED_EXIT_AFTER: Duration = Duration::from_secs(15); + +/// Start listening for the signals. Call from inside the async runtime's +/// reach (`setup`), once. +pub(crate) fn install(app: &AppHandle) { + let app = app.clone(); + tauri::async_runtime::spawn(async move { + let listeners = ( + signal(SignalKind::interrupt()), + signal(SignalKind::terminate()), + signal(SignalKind::hangup()), + ); + let (Ok(mut interrupt), Ok(mut terminate), Ok(mut hangup)) = listeners else { + log::warn!("Cannot listen for SIGINT/SIGTERM/SIGHUP; they will end Staged at once"); + return; + }; + + let (name, number) = next_signal(&mut interrupt, &mut terminate, &mut hangup).await; + log::info!("Received {name}; quitting and stopping sessions"); + let quitting = app.clone(); + std::thread::spawn(move || { + shutdown_cleanup(&quitting); + quitting.exit(128 + number); + }); + + let why = tokio::select! { + (name, _) = next_signal(&mut interrupt, &mut terminate, &mut hangup) => { + format!("received {name} again") + } + () = tokio::time::sleep(FORCED_EXIT_AFTER) => { + format!("the quit took longer than {}s", FORCED_EXIT_AFTER.as_secs()) + } + }; + log::warn!("Exiting at once: {why}"); + crate::agent_watchdog::on_exit(); + log::logger().flush(); + crate::app_log::flush_terminal(); + std::process::exit(128 + number); + }); +} + +async fn next_signal( + interrupt: &mut Signal, + terminate: &mut Signal, + hangup: &mut Signal, +) -> (&'static str, i32) { + tokio::select! { + _ = interrupt.recv() => ("SIGINT", libc::SIGINT), + _ = terminate.recv() => ("SIGTERM", libc::SIGTERM), + _ = hangup.recv() => ("SIGHUP", libc::SIGHUP), + } +} diff --git a/apps/staged/src-tauri/src/lib.rs b/apps/staged/src-tauri/src/lib.rs index dced71d6c..2f5963b1e 100644 --- a/apps/staged/src-tauri/src/lib.rs +++ b/apps/staged/src-tauri/src/lib.rs @@ -8,6 +8,7 @@ pub mod acp_tools; pub mod acp_tools_reconciler; pub mod actions; pub mod agent; +pub mod agent_watchdog; pub mod app_lifecycle; mod app_log; pub mod background_sync; @@ -1920,6 +1921,8 @@ pub fn run() { // to the page in an initialization script, and windows are built before // `setup` runs; it starts answering in `setup`. The script names the // address only to the app's own pages, whose origin the config decides. + // First, so no agent can start unwatched. + let agent_watchdog = agent_watchdog::start(); let context = tauri::generate_context!(); let media_index = Arc::new(note_media::serving::MediaIndex::default()); let media_stream = note_media::stream::MediaStream::bind(); @@ -2502,6 +2505,9 @@ pub fn run() { } app.handle().plugin(app_log::plugin())?; + agent_watchdog::log_start(&agent_watchdog); + #[cfg(unix)] + app_lifecycle::exit_signals::install(app.handle()); Ok(()) }) .on_menu_event(|app, event| { @@ -2878,6 +2884,7 @@ pub fn run() { // the agent and action child processes. tauri::RunEvent::Exit => { app_lifecycle::shutdown_cleanup(app_handle); + agent_watchdog::on_exit(); // Every exit through this loop passes here last. app_log::flush_terminal(); } diff --git a/apps/staged/src-tauri/src/main.rs b/apps/staged/src-tauri/src/main.rs index df98b2cf9..0df99602c 100644 --- a/apps/staged/src-tauri/src/main.rs +++ b/apps/staged/src-tauri/src/main.rs @@ -2,5 +2,15 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { + // The agent reaper's watchdog is this binary re-run (see + // `staged_lib::agent_watchdog`); it must not start the app. + #[cfg(unix)] + if std::env::args_os().nth(1).as_deref() + == Some(std::ffi::OsStr::new( + staged_lib::agent_watchdog::WATCHDOG_ARG, + )) + { + acp_client::agent_reaper::run_watchdog(); + } staged_lib::run(); } diff --git a/crates/acp-client/Cargo.toml b/crates/acp-client/Cargo.toml index 8a21c978d..b615dcf4f 100644 --- a/crates/acp-client/Cargo.toml +++ b/crates/acp-client/Cargo.toml @@ -21,6 +21,4 @@ tokio = { version = "1", features = ["test-util"] } [target.'cfg(unix)'.dependencies] nix = { version = "0.31", features = ["signal"] } - -[target.'cfg(target_os = "macos")'.dependencies] libc = "0.2" diff --git a/crates/acp-client/src/agent_reaper.rs b/crates/acp-client/src/agent_reaper.rs new file mode 100644 index 000000000..466aded52 --- /dev/null +++ b/crates/acp-client/src/agent_reaper.rs @@ -0,0 +1,305 @@ +//! Making sure agent processes never outlive Staged. +//! +//! A local agent is started in a session of its own (`setsid()`, see +//! `AcpDriver::open_connection`), so it has no controlling terminal and +//! cannot take Staged's: an interactive login shell, or any shell the agent +//! starts, would otherwise make itself the terminal's foreground group and get +//! Staged stopped with `SIGTTOU`/`SIGTTIN`. That also takes away the cleanup +//! the terminal used to do — SIGHUP when it closes, SIGINT on Ctrl-C — so +//! every way out of Staged now stops agents explicitly: +//! +//! - **A session ending, and a quit.** [`AgentGroup::stop`] sends the agent's +//! group and every descendant SIGTERM, waits out a short grace, then +//! SIGKILLs whatever is left. Dropping an [`AgentGroup`] that was never +//! stopped SIGKILLs the lot. +//! - **Staged dying any other way** — a panic, a signal, SIGKILL, a crash. +//! Every group is announced to a watchdog process (see [`watchdog`]) that +//! stops whatever is still announced when Staged's end of a pipe closes. +//! macOS has no `PR_SET_PDEATHSIG`, and an agent noticing its stdin close +//! says nothing about the tool shells and MCP servers it started. +//! - **No watchdog** (it failed to start, or was killed and could not be +//! restarted): [`reap_now_if_unwatched`] does the same in process, for the +//! exits Staged still sees. +//! +//! Remote (Blox) proxies are registered too, as [`GroupKind::Remote`]: on +//! Staged's death they are SIGKILLed, never interrupted — SIGINT to the +//! `blox acp` proxy stops the remote agent along with every turn on it, and a +//! quit leaves remote turns running (see `SessionRegistry::detach`). Their +//! ordinary teardown stays with the driver. + +use std::collections::BTreeMap; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +#[cfg(unix)] +mod process_tree; +#[cfg(unix)] +mod watchdog; + +#[cfg(unix)] +pub use watchdog::run_watchdog; + +/// The argument that turns Staged's binary into the watchdog: `main` hands +/// over to [`run_watchdog`] when it is the first argument. +pub const WATCHDOG_ARG: &str = "--staged-agent-reaper"; + +/// How a group is stopped once Staged is gone. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GroupKind { + /// A local agent: SIGTERM, a grace, then SIGKILL. + Local, + /// A remote proxy: SIGKILL only, so its remote agent keeps running. + Remote, +} + +/// How often the watchdog may be restarted after it went away under a +/// running Staged, before the in-process fallback is all that is left. +const MAX_WATCHDOG_RESTARTS: u32 = 3; + +#[derive(Default)] +struct State { + /// Every group currently Staged's. + groups: BTreeMap, + #[cfg(unix)] + watchdog: Option, + /// What [`start_watchdog`] was given, to restart it from. + program: Option, + restarts: u32, +} + +static STATE: Mutex = Mutex::new(State { + groups: BTreeMap::new(), + #[cfg(unix)] + watchdog: None, + program: None, + restarts: 0, +}); + +fn state() -> MutexGuard<'static, State> { + // A panic while holding it leaves nothing half-done worth refusing. + STATE + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +impl State { + /// Tell the watchdog, restarting it (and telling the new one everything) + /// if it has gone. + #[cfg(unix)] + fn announce(&mut self, command: watchdog::WatchCommand) { + let Some(link) = self.watchdog.as_mut() else { + return; + }; + let Err(error) = link.send(command) else { + return; + }; + log::warn!("The agent reaper watchdog stopped listening ({error}); restarting it"); + self.watchdog = None; + self.restart_watchdog(); + } + + #[cfg(unix)] + fn restart_watchdog(&mut self) { + if self.restarts >= MAX_WATCHDOG_RESTARTS { + log::warn!( + "Not restarting the agent reaper watchdog again; agents will only be stopped \ + on exits Staged sees" + ); + return; + } + let Some(program) = self.program.clone() else { + return; + }; + self.restarts += 1; + match watchdog::Link::spawn(&program) { + Ok(link) => { + self.watchdog = Some(link); + self.replay(); + } + Err(error) => log::warn!("Failed to restart the agent reaper watchdog: {error}"), + } + } + + /// Announce every current group to a freshly started watchdog. + #[cfg(unix)] + fn replay(&mut self) { + let groups: Vec<(i32, GroupKind)> = self.groups.iter().map(|(&g, &k)| (g, k)).collect(); + for (pgid, kind) in groups { + self.announce(watchdog::WatchCommand::Watch(pgid, kind)); + } + } + + #[cfg(unix)] + fn watchdog_running(&mut self) -> bool { + self.watchdog + .as_mut() + .is_some_and(watchdog::Link::is_running) + } +} + +/// Start the watchdog that stops agents if Staged dies: `program` (Staged's +/// own binary) run with [`WATCHDOG_ARG`]. Call once, early; groups registered +/// before it starts are announced to it. +pub fn start_watchdog(program: &Path) -> io::Result<()> { + #[cfg(unix)] + { + let link = watchdog::Link::spawn(program)?; + let mut state = state(); + state.program = Some(program.to_path_buf()); + state.watchdog = Some(link); + state.replay(); + Ok(()) + } + #[cfg(not(unix))] + { + let _ = program; + Err(io::Error::new( + io::ErrorKind::Unsupported, + "the agent reaper watchdog needs Unix", + )) + } +} + +/// Whether the watchdog is running, so an unseen death of Staged would still +/// stop its agents. +pub fn watchdog_running() -> bool { + #[cfg(unix)] + { + state().watchdog_running() + } + #[cfg(not(unix))] + { + false + } +} + +/// Stop every registered agent group now, blocking, unless the watchdog is +/// running and will do it once this process is gone. For the exits Staged +/// sees (the end of shutdown, a fatal panic) when it may have no watchdog. +/// Local groups get up to `grace` between SIGTERM and SIGKILL. Returns +/// whether it reaped anything. +pub fn reap_now_if_unwatched(grace: Duration) -> bool { + #[cfg(unix)] + { + let groups: Vec<(i32, GroupKind, Vec)> = { + let mut state = state(); + if state.watchdog_running() { + return false; + } + state + .groups + .iter() + .map(|(&g, &k)| (g, k, Vec::new())) + .collect() + }; + if groups.is_empty() { + return false; + } + process_tree::reap_blocking(&groups, grace); + true + } + #[cfg(not(unix))] + { + let _ = grace; + false + } +} + +/// One agent (or proxy) process group this Staged started, registered with +/// the watchdog for as long as it lives. The group's id is the leader's pid: +/// local agents lead a session of their own, remote proxies a group. +pub(crate) struct AgentGroup { + pgid: Option, + kind: GroupKind, + /// Stopped already: nothing left for `Drop` to kill. + stopped: bool, +} + +impl AgentGroup { + /// Register the group a just-spawned local agent leads. + pub(crate) fn local(pid: Option) -> Self { + Self::register(pid, GroupKind::Local) + } + + /// Register the group a just-spawned remote proxy leads. + pub(crate) fn remote(pid: Option) -> Self { + Self::register(pid, GroupKind::Remote) + } + + fn register(pid: Option, kind: GroupKind) -> Self { + let pgid = pid + .and_then(|pid| i32::try_from(pid).ok()) + .filter(|&pgid| pgid > 1); + if let Some(pgid) = pgid { + let mut state = state(); + state.groups.insert(pgid, kind); + #[cfg(unix)] + state.announce(watchdog::WatchCommand::Watch(pgid, kind)); + } + Self { + pgid, + kind, + stopped: false, + } + } + + /// Stop a local agent and everything it started: SIGTERM to its group + /// and every descendant, up to `grace` for them to go, then SIGKILL to + /// whatever is left — the SIGKILL goes out even when the agent exited in + /// time, for the descendants that did not. Reaps `child`. + pub(crate) async fn stop(&mut self, child: &mut tokio::process::Child, grace: Duration) { + #[cfg(unix)] + if let (Some(pgid), GroupKind::Local) = (self.pgid, self.kind) { + let tracked = process_tree::group_and_descendants(&process_tree::snapshot(), pgid); + process_tree::signal_group_and(pgid, &tracked, libc::SIGTERM); + let deadline = tokio::time::Instant::now() + grace; + loop { + // Reap the agent as soon as it goes, so it is not counted as + // running in its group as a zombie. + let _ = child.try_wait(); + let table = process_tree::snapshot(); + if !process_tree::any_running(&table, pgid, &tracked) + || tokio::time::Instant::now() >= deadline + { + let targets = process_tree::closure(&table, pgid, &tracked); + process_tree::signal_group_and(pgid, &targets, libc::SIGKILL); + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + self.stopped = true; + } + #[cfg(not(unix))] + let _ = grace; + let _ = child.kill().await; + } + + #[cfg(test)] + pub(crate) fn pgid(&self) -> Option { + self.pgid + } +} + +impl Drop for AgentGroup { + fn drop(&mut self) { + let Some(pgid) = self.pgid else { + return; + }; + // A local agent dropped without `stop` (an error path between spawn + // and the connection) still takes everything it started with it. + // Remote proxies have their own teardown, which has already run. + #[cfg(unix)] + if self.kind == GroupKind::Local && !self.stopped { + process_tree::kill_now(pgid); + } + let mut state = state(); + state.groups.remove(&pgid); + #[cfg(unix)] + state.announce(watchdog::WatchCommand::Forget(pgid)); + } +} + +#[cfg(all(test, unix))] +mod tests; diff --git a/crates/acp-client/src/agent_reaper/process_tree.rs b/crates/acp-client/src/agent_reaper/process_tree.rs new file mode 100644 index 000000000..91a0b28fe --- /dev/null +++ b/crates/acp-client/src/agent_reaper/process_tree.rs @@ -0,0 +1,341 @@ +//! Finding and signalling everything an agent process group started. +//! +//! A local agent is a session leader (see [`super`]), so its process group id +//! is its pid and everything it starts lands in that group — unless something +//! moves itself out: Node's `spawn(..., { detached: true })` calls `setsid()`, +//! and an MCP server or tool runner may do the same. A group signal misses +//! those, so the group is widened with every descendant of its members, found +//! by walking parent links in a snapshot of the process table. The walk only +//! sees descendants whose ancestors are still alive, so it is taken *before* +//! anything is signalled: once the agent dies, its detached children are +//! re-parented to launchd and look like nobody's. +//! +//! Each process found is remembered with its start time, and a later signal +//! goes to it only while a process with that pid *and* that start time +//! exists, so a pid recycled in between is never hit. + +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +use super::GroupKind; + +/// One row of the process table. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) struct Proc { + pub(super) pid: i32, + pub(super) ppid: i32, + pub(super) pgid: i32, + /// Opaque start time; only compared for equality. + pub(super) start: u64, + pub(super) zombie: bool, +} + +/// How often a reap re-reads the process table while waiting out its grace. +const POLL_INTERVAL: Duration = Duration::from_millis(25); + +/// The current process table. Empty when it cannot be read, which leaves the +/// group signals to do the work on their own. +#[cfg(target_os = "macos")] +pub(super) fn snapshot() -> Vec { + use std::mem::size_of; + + let mut capacity = 2048usize; + let pids = loop { + let mut pids: Vec = vec![0; capacity]; + let Ok(bytes) = libc::c_int::try_from(capacity * size_of::()) else { + return Vec::new(); + }; + // SAFETY: the buffer holds `capacity` pids, and `bytes` says so. + let count = unsafe { libc::proc_listallpids(pids.as_mut_ptr().cast(), bytes) }; + let Ok(count) = usize::try_from(count) else { + return Vec::new(); + }; + // A full buffer may have been cut short; ask again with more room. + if count < capacity { + pids.truncate(count); + break pids; + } + capacity *= 2; + }; + + let info_size = size_of::() as libc::c_int; + pids.into_iter() + .filter(|&pid| pid > 0) + .filter_map(|pid| { + // SAFETY: an all-zero `proc_bsdinfo` is a valid value (plain + // integers and byte arrays), and the call writes at most + // `info_size` bytes into it. + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let written = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdinfo).cast(), + info_size, + ) + }; + (written == info_size).then(|| Proc { + pid, + ppid: info.pbi_ppid as i32, + pgid: info.pbi_pgid as i32, + start: info.pbi_start_tvsec.wrapping_mul(1_000_000) ^ info.pbi_start_tvusec, + zombie: info.pbi_status == libc::SZOMB, + }) + }) + .collect() +} + +/// The current process table, from `/proc`. +#[cfg(target_os = "linux")] +pub(super) fn snapshot() -> Vec { + let Ok(entries) = std::fs::read_dir("/proc") else { + return Vec::new(); + }; + entries + .filter_map(|entry| { + let entry = entry.ok()?; + let pid: i32 = entry.file_name().to_str()?.parse().ok()?; + let stat = std::fs::read_to_string(entry.path().join("stat")).ok()?; + parse_linux_stat(pid, &stat) + }) + .collect() +} + +/// One `/proc//stat` line. The command name is parenthesised and may hold +/// spaces and parentheses itself, so fields are counted from the last `)`. +#[cfg(any(target_os = "linux", test))] +fn parse_linux_stat(pid: i32, stat: &str) -> Option { + let rest = &stat[stat.rfind(')')? + 1..]; + let fields: Vec<&str> = rest.split_whitespace().collect(); + // After the name: state(0) ppid(1) pgrp(2) session(3) ... starttime(19). + Some(Proc { + pid, + ppid: fields.get(1)?.parse().ok()?, + pgid: fields.get(2)?.parse().ok()?, + start: fields.get(19)?.parse().ok()?, + zombie: *fields.first()? == "Z", + }) +} + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +pub(super) fn snapshot() -> Vec { + Vec::new() +} + +/// Every process in group `pgid`, plus every descendant of one, wherever its +/// own group or session now is. Never this process, nor pid 1. +pub(super) fn group_and_descendants(table: &[Proc], pgid: i32) -> Vec { + closure(table, pgid, &[]) +} + +/// [`group_and_descendants`], widened with whatever of `known` (processes +/// seen in an earlier walk) is still the same process, and their +/// descendants: a detached child whose parent has since exited has been +/// re-parented to launchd, and only an earlier walk can still tie it to the +/// group. +pub(super) fn closure(table: &[Proc], pgid: i32, known: &[Proc]) -> Vec { + let own_pid = std::process::id() as i32; + let mut children: HashMap> = HashMap::new(); + for proc in table { + children.entry(proc.ppid).or_default().push(proc); + } + let mut found: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut queue: Vec<&Proc> = table + .iter() + .filter(|row| { + row.pgid == pgid + || known + .iter() + .any(|proc| proc.pid == row.pid && proc.start == row.start) + }) + .collect(); + while let Some(proc) = queue.pop() { + if proc.pid <= 1 || proc.pid == own_pid || !seen.insert(proc.pid) { + continue; + } + found.push(*proc); + if let Some(kids) = children.get(&proc.pid) { + queue.extend(kids.iter().copied()); + } + } + found +} + +/// Whether `proc` (the same process, not just the same pid) is alive in +/// `table`. +fn still_running(table: &[Proc], proc: &Proc) -> bool { + table + .iter() + .any(|row| row.pid == proc.pid && row.start == proc.start && !row.zombie) +} + +/// Whether anything of group `pgid` — a member, or one of `tracked` — is still +/// running. +pub(super) fn any_running(table: &[Proc], pgid: i32, tracked: &[Proc]) -> bool { + table.iter().any(|row| row.pgid == pgid && !row.zombie) + || tracked.iter().any(|proc| still_running(table, proc)) +} + +/// Send `signal` to group `pgid` and to every process in `targets` outside it +/// (the group signal already reaches the rest). +pub(super) fn signal_group_and(pgid: i32, targets: &[Proc], signal: libc::c_int) { + if pgid > 1 { + // SAFETY: plain syscall. ESRCH (an empty group) is the expected outcome + // once everything is gone. + unsafe { libc::kill(-pgid, signal) }; + } + for proc in targets.iter().filter(|proc| proc.pgid != pgid) { + // SAFETY: plain syscall, to a pid seen alive with this start time + // moments ago. + unsafe { libc::kill(proc.pid, signal) }; + } +} + +/// SIGKILL group `pgid` and everything it started, now. Remote proxies are +/// only ever stopped this way here (see [`GroupKind::Remote`]). +pub(super) fn kill_now(pgid: i32) { + let table = snapshot(); + let targets = group_and_descendants(&table, pgid); + signal_group_and(pgid, &targets, libc::SIGKILL); +} + +/// Stop every group in `groups` and everything they started, blocking: local +/// groups get SIGTERM, up to `grace` to go, then SIGKILL; remote groups get +/// SIGKILL straight away. Each group comes with the processes earlier walks +/// found in it (see [`closure`]). Returns how many processes were signalled +/// at first. +pub(super) fn reap_blocking(groups: &[(i32, GroupKind, Vec)], grace: Duration) -> usize { + let table = snapshot(); + let tracked: Vec<(i32, GroupKind, Vec)> = groups + .iter() + .map(|(pgid, kind, known)| { + let (pgid, kind) = (*pgid, *kind); + let targets = closure(&table, pgid, known); + let signal = match kind { + GroupKind::Local => libc::SIGTERM, + GroupKind::Remote => libc::SIGKILL, + }; + signal_group_and(pgid, &targets, signal); + (pgid, kind, targets) + }) + .collect(); + let signalled = tracked.iter().map(|(_, _, targets)| targets.len()).sum(); + + let deadline = Instant::now() + grace; + let mut table = snapshot(); + while Instant::now() < deadline + && tracked + .iter() + .any(|(pgid, _, targets)| any_running(&table, *pgid, targets)) + { + std::thread::sleep(POLL_INTERVAL); + table = snapshot(); + } + for (pgid, _, targets) in &tracked { + let targets = closure(&table, *pgid, targets); + signal_group_and(*pgid, &targets, libc::SIGKILL); + } + signalled +} + +#[cfg(test)] +mod tests { + use super::*; + + fn proc(pid: i32, ppid: i32, pgid: i32) -> Proc { + Proc { + pid, + ppid, + pgid, + start: pid as u64 * 10, + zombie: false, + } + } + + #[test] + fn descendants_that_left_the_group_are_still_found() { + let table = [ + proc(1, 0, 1), + proc(100, 50, 100), // the agent, a session leader + proc(101, 100, 100), // its CLI child + proc(200, 101, 200), // a detached bash tool (own session) + proc(201, 200, 200), // that tool's child + proc(300, 50, 300), // unrelated sibling of the agent + proc(301, 1, 100), // a group member re-parented to launchd + proc(302, 301, 302), // and its detached child + ]; + let mut pids: Vec = group_and_descendants(&table, 100) + .iter() + .map(|proc| proc.pid) + .collect(); + pids.sort_unstable(); + assert_eq!(pids, vec![100, 101, 200, 201, 301, 302]); + } + + #[test] + fn processes_seen_earlier_are_still_found_after_their_parent_exited() { + // The agent (100) has exited; its detached child (200) was re-parented + // to launchd, and only an earlier walk knows it was the agent's. + let table = [ + proc(1, 0, 1), + proc(200, 1, 200), + proc(201, 200, 200), + proc(300, 1, 300), + ]; + let known = [proc(200, 100, 200)]; + let mut pids: Vec = closure(&table, 100, &known) + .iter() + .map(|proc| proc.pid) + .collect(); + pids.sort_unstable(); + assert_eq!(pids, vec![200, 201]); + assert!(group_and_descendants(&table, 100).is_empty()); + } + + #[test] + fn running_ignores_zombies_and_recycled_pids() { + let tracked = [proc(200, 100, 200)]; + let mut zombie = proc(100, 50, 100); + zombie.zombie = true; + assert!(!any_running(&[zombie], 100, &tracked)); + // pid 200 is back, but as a different process. + let mut recycled = proc(200, 1, 999); + recycled.start += 1; + assert!(!any_running(&[recycled], 100, &tracked)); + assert!(any_running(&[proc(200, 1, 200)], 100, &tracked)); + assert!(closure(&[recycled], 100, &tracked).is_empty()); + } + + #[test] + fn linux_stat_lines_are_read_past_awkward_names() { + let stat = "4242 (we(i)rd name) S 17 4242 4242 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 \ + 98765 0 0"; + assert_eq!( + parse_linux_stat(4242, stat), + Some(Proc { + pid: 4242, + ppid: 17, + pgid: 4242, + start: 98765, + zombie: false, + }) + ); + } + + #[cfg(any(target_os = "macos", target_os = "linux"))] + #[test] + fn the_snapshot_sees_this_process() { + let own = std::process::id() as i32; + let table = snapshot(); + let row = table + .iter() + .find(|proc| proc.pid == own) + .expect("this process is listed"); + // SAFETY: plain syscalls. + assert_eq!(row.ppid, unsafe { libc::getppid() }); + assert_eq!(row.pgid, unsafe { libc::getpgrp() }); + assert!(!row.zombie); + } +} diff --git a/crates/acp-client/src/agent_reaper/tests.rs b/crates/acp-client/src/agent_reaper/tests.rs new file mode 100644 index 000000000..ea5473807 --- /dev/null +++ b/crates/acp-client/src/agent_reaper/tests.rs @@ -0,0 +1,331 @@ +//! End-to-end checks with real processes: a fake agent that leads a session +//! of its own, like a real local agent, and starts the kinds of descendants +//! real ones do. + +use super::process_tree::{kill_now, snapshot}; +use super::watchdog::{Link, WatchCommand}; +use super::*; + +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Instant; + +/// Set in the environment of the test binary re-run as the watchdog. +const WATCHDOG_ENTRY_ENV: &str = "ACP_CLIENT_TEST_RUN_AGENT_REAPER"; + +/// Not a test: the entry point the watchdog test re-runs this binary into. +#[test] +fn watchdog_entry() { + if std::env::var_os(WATCHDOG_ENTRY_ENV).is_some() { + run_watchdog(); + } +} + +/// The fake agent. `$1` is a file it writes one pid per line to, in no +/// particular order: +/// - a plain group member, which honours SIGTERM; +/// - a group member that ignores SIGTERM; +/// - a detached child (`setsid()`, as Node's `detached: true` does) that +/// ignores SIGTERM, and that child's own child; +/// - the leader itself, which ignores SIGTERM too. +const FAKE_AGENT: &str = r#" +out="$1" +sh -c 'echo $$ >> "$0"; exec sleep 300' "$out" & +sh -c 'trap "" TERM; echo $$ >> "$0"; exec sleep 300' "$out" & +perl -e ' + use POSIX (); + POSIX::setsid(); + $SIG{TERM} = "IGNORE"; + open(my $fh, ">>", $ARGV[0]) or die; $fh->autoflush(1); + print $fh "$$\n"; + my $kid = fork(); + if ($kid == 0) { print $fh "$$\n"; close $fh; exec "sleep", "300"; } + close $fh; + sleep 300; +' "$out" & +sleep 0.2 +trap '' TERM +echo $$ >> "$out" +wait +"#; + +/// How many pids [`FAKE_AGENT`] reports. +const FAKE_AGENT_PIDS: usize = 5; + +struct FakeAgent { + pids: Vec, + leader: i32, + pid_file: PathBuf, +} + +impl FakeAgent { + /// The command, started the way the driver starts a local agent. + fn command() -> (std::process::Command, PathBuf) { + static NEXT: AtomicU32 = AtomicU32::new(0); + let pid_file = std::env::temp_dir().join(format!( + "acp-client-agent-reaper-{}-{}.pids", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_file(&pid_file); + let mut cmd = std::process::Command::new("sh"); + cmd.args(["-c", FAKE_AGENT, "fake-agent"]) + .arg(&pid_file) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + // SAFETY: async-signal-safe calls only. SIGTERM is reset in case the + // test runner was started with it ignored. + unsafe { + cmd.pre_exec(|| { + libc::setsid(); + libc::signal(libc::SIGTERM, libc::SIG_DFL); + Ok(()) + }); + } + (cmd, pid_file) + } + + /// Wait for every pid to be reported. `leader` is the pid spawned. + fn wait_for_pids(pid_file: PathBuf, leader: u32) -> Self { + let leader = leader as i32; + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let pids: Vec = std::fs::read_to_string(&pid_file) + .unwrap_or_default() + .lines() + .filter_map(|line| line.trim().parse().ok()) + .collect(); + if pids.len() >= FAKE_AGENT_PIDS { + assert!(pids.contains(&leader), "{leader} is among {pids:?}"); + return Self { + pids, + leader, + pid_file, + }; + } + assert!( + Instant::now() < deadline, + "the fake agent reported only {pids:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn leader(&self) -> i32 { + self.leader + } + + fn running(&self) -> Vec { + let table = snapshot(); + self.pids + .iter() + .copied() + .filter(|&pid| table.iter().any(|row| row.pid == pid && !row.zombie)) + .collect() + } + + fn wait_until_all_gone(&self) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let running = self.running(); + if running.is_empty() { + return; + } + assert!( + Instant::now() < deadline, + "still running after 10 s: {running:?} (of {:?})", + self.pids + ); + std::thread::sleep(Duration::from_millis(25)); + } + } +} + +impl Drop for FakeAgent { + fn drop(&mut self) { + // Whatever a failing test left behind, the same way the code under + // test would have stopped it. + let leader = self.leader(); + if !self.running().is_empty() { + kill_now(leader); + for &pid in &self.pids { + // SAFETY: plain syscall. + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + } + let _ = std::fs::remove_file(&self.pid_file); + } +} + +fn registered(pgid: i32) -> bool { + state().groups.contains_key(&pgid) +} + +#[tokio::test] +async fn stopping_a_local_agent_takes_every_descendant_with_it() { + let (cmd, pid_file) = FakeAgent::command(); + let mut child = tokio::process::Command::from(cmd) + .spawn() + .expect("sh spawns"); + let mut group = AgentGroup::local(child.id()); + let agent = FakeAgent::wait_for_pids(pid_file, child.id().expect("running")); + assert_eq!(group.pgid(), Some(agent.leader())); + assert!(registered(agent.leader())); + assert_eq!(agent.running().len(), FAKE_AGENT_PIDS); + + let started = Instant::now(); + group.stop(&mut child, Duration::from_millis(300)).await; + assert!( + started.elapsed() >= Duration::from_millis(300), + "SIGTERM-ignoring processes got the grace first" + ); + assert!(child.try_wait().expect("waitable").is_some(), "reaped"); + agent.wait_until_all_gone(); + + drop(group); + assert!(!registered(agent.leader())); +} + +#[test] +fn dropping_an_unstopped_local_agent_kills_every_descendant() { + let (mut cmd, pid_file) = FakeAgent::command(); + let mut child = cmd.spawn().expect("sh spawns"); + let group = AgentGroup::local(Some(child.id())); + let agent = FakeAgent::wait_for_pids(pid_file, child.id()); + assert_eq!(agent.running().len(), FAKE_AGENT_PIDS); + + drop(group); + let _ = child.wait(); + agent.wait_until_all_gone(); + assert!(!registered(agent.leader())); +} + +/// What [`reap_now_if_unwatched`] runs, on this test's group alone: the +/// global registry also holds the groups of driver tests running alongside. +#[test] +fn the_blocking_reap_stops_every_descendant() { + let (mut cmd, pid_file) = FakeAgent::command(); + let mut child = cmd.spawn().expect("sh spawns"); + let agent = FakeAgent::wait_for_pids(pid_file, child.id()); + + let signalled = super::process_tree::reap_blocking( + &[(agent.leader(), GroupKind::Local, Vec::new())], + Duration::from_millis(200), + ); + assert_eq!(signalled, FAKE_AGENT_PIDS); + let _ = child.wait(); + agent.wait_until_all_gone(); +} + +/// The watchdog is this test binary re-run into [`watchdog_entry`]. +fn spawn_test_watchdog() -> Link { + let mut cmd = std::process::Command::new(std::env::current_exe().expect("test binary")); + cmd.args([ + "agent_reaper::tests::watchdog_entry", + "--exact", + "--nocapture", + "--test-threads=1", + ]) + .env(WATCHDOG_ENTRY_ENV, "1"); + Link::spawn_command(cmd).expect("the watchdog starts") +} + +#[test] +fn the_watchdog_stops_watched_groups_when_its_pipe_closes_and_spares_forgotten_ones() { + let mut link = spawn_test_watchdog(); + + let (mut watched_cmd, watched_pids) = FakeAgent::command(); + let mut watched_child = watched_cmd.spawn().expect("sh spawns"); + let (mut forgotten_cmd, forgotten_pids) = FakeAgent::command(); + let mut forgotten_child = forgotten_cmd.spawn().expect("sh spawns"); + let watched = FakeAgent::wait_for_pids(watched_pids, watched_child.id()); + let forgotten = FakeAgent::wait_for_pids(forgotten_pids, forgotten_child.id()); + + link.send(WatchCommand::Watch(watched.leader(), GroupKind::Local)) + .expect("sent"); + link.send(WatchCommand::Watch(forgotten.leader(), GroupKind::Local)) + .expect("sent"); + link.send(WatchCommand::Forget(forgotten.leader())) + .expect("sent"); + // Still running while Staged is: nothing is stopped early. + std::thread::sleep(Duration::from_millis(200)); + assert!(link.is_running()); + assert_eq!(watched.running().len(), FAKE_AGENT_PIDS); + + // The watchdog is in a session of its own. + let watchdog_pid = link.pid() as i32; + // SAFETY: plain syscall. + assert_eq!(unsafe { libc::getsid(watchdog_pid) }, watchdog_pid); + + let status = link.close_and_wait().expect("the watchdog exits"); + assert!(status.success(), "{status:?}"); + let _ = watched_child.wait(); + watched.wait_until_all_gone(); + assert_eq!( + forgotten.running().len(), + FAKE_AGENT_PIDS, + "a forgotten group is left alone" + ); + + kill_now(forgotten.leader()); + let _ = forgotten_child.wait(); + forgotten.wait_until_all_gone(); +} + +#[test] +fn the_watchdog_ignores_termination_signals() { + let link = spawn_test_watchdog(); + let pid = link.pid() as i32; + for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] { + // SAFETY: plain syscall. + unsafe { libc::kill(pid, signal) }; + } + std::thread::sleep(Duration::from_millis(200)); + let mut link = link; + assert!(link.is_running(), "survived SIGINT, SIGTERM and SIGHUP"); + let status = link.close_and_wait().expect("the watchdog exits"); + assert!(status.success(), "{status:?}"); +} + +/// The race the watchdog's tracking is for: an agent notices Staged's death +/// (its stdin closing) as soon as the watchdog does and exits, and the child +/// it detached is re-parented to launchd before the watchdog walks the tree. +/// Only an earlier walk still ties that child to the agent. +#[test] +fn the_watchdog_stops_detached_children_the_agent_left_behind_before_staged_died() { + let mut link = spawn_test_watchdog(); + let (mut cmd, pid_file) = FakeAgent::command(); + let mut child = cmd.spawn().expect("sh spawns"); + let agent = FakeAgent::wait_for_pids(pid_file, child.id()); + link.send(WatchCommand::Watch(agent.leader(), GroupKind::Local)) + .expect("sent"); + // Long enough for the watchdog to have walked the group. + std::thread::sleep(Duration::from_millis(1500)); + + // The agent and its group go first, leaving the detached pair orphaned. + // SAFETY: plain syscall. + unsafe { libc::kill(-agent.leader(), libc::SIGKILL) }; + let _ = child.wait(); + let deadline = Instant::now() + Duration::from_secs(10); + while agent.running().len() != 2 { + assert!( + Instant::now() < deadline, + "only the detached pair should be left: {:?}", + agent.running() + ); + std::thread::sleep(Duration::from_millis(25)); + } + let orphaned = snapshot(); + assert!( + agent.running().iter().all(|pid| orphaned + .iter() + .any(|row| row.pid == *pid && row.pgid != agent.leader())), + "what is left is outside the agent's group" + ); + + let status = link.close_and_wait().expect("the watchdog exits"); + assert!(status.success(), "{status:?}"); + agent.wait_until_all_gone(); +} diff --git a/crates/acp-client/src/agent_reaper/watchdog.rs b/crates/acp-client/src/agent_reaper/watchdog.rs new file mode 100644 index 000000000..515d42dc8 --- /dev/null +++ b/crates/acp-client/src/agent_reaper/watchdog.rs @@ -0,0 +1,278 @@ +//! The watchdog process that stops agents when Staged dies. +//! +//! Staged starts it once (its own binary, re-run with [`WATCHDOG_ARG`]) and +//! keeps the write end of a pipe to its stdin, over which it announces every +//! agent process group it starts and stops. The read end ends when Staged's +//! last copy of the write end closes, which the kernel does however Staged +//! goes: a quit, a panic, a signal, SIGKILL, a crash. The watchdog then stops +//! every group still announced and exits. +//! +//! The pipe, rather than watching Staged's pid (kqueue `NOTE_EXIT`), because +//! it carries the registrations too and cannot be fooled by pid reuse; and a +//! separate process because nothing inside Staged runs after SIGKILL. The +//! write end is `O_CLOEXEC` (Rust creates every pipe that way), so no agent +//! inherits it and keeps the read end from ending. +//! +//! The watchdog runs in a session of its own and ignores the terminal and +//! termination signals, so Ctrl-C, a closed terminal or a `kill` meant for +//! Staged cannot take it down first. Its only way out is the pipe ending. + +use std::collections::BTreeMap; +use std::io::{self, BufRead, Write}; +use std::path::Path; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::time::Duration; + +use super::{process_tree, GroupKind, WATCHDOG_ARG}; + +/// How long agents get to exit on SIGTERM once Staged is gone, before +/// SIGKILL. +const WATCHDOG_GRACE: Duration = Duration::from_secs(2); + +/// What the watchdog ignores: everything a terminal, a `kill` or a closed +/// pipe would otherwise end it with before Staged's pipe closes. +const IGNORED_SIGNALS: [libc::c_int; 7] = [ + libc::SIGINT, + libc::SIGTERM, + libc::SIGHUP, + libc::SIGQUIT, + libc::SIGPIPE, + libc::SIGTTIN, + libc::SIGTTOU, +]; + +/// A running watchdog, as Staged holds it. +pub(super) struct Link { + child: Child, + stdin: ChildStdin, +} + +impl Link { + /// Start the watchdog: `program` with [`WATCHDOG_ARG`]. + pub(super) fn spawn(program: &Path) -> io::Result { + let mut cmd = Command::new(program); + cmd.arg(WATCHDOG_ARG); + Self::spawn_command(cmd) + } + + /// Start `cmd` as the watchdog, in a session of its own with its stdin + /// piped from here. + pub(super) fn spawn_command(mut cmd: Command) -> io::Result { + use std::os::unix::process::CommandExt; + + cmd.stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()); + // SAFETY: `setsid()` and `signal()` are async-signal-safe and touch + // nothing else. Ignored dispositions survive `exec`, so the watchdog + // cannot be taken down by these signals even before it gets to + // `run_watchdog`. + unsafe { + cmd.pre_exec(|| { + libc::setsid(); + for signal in IGNORED_SIGNALS { + libc::signal(signal, libc::SIG_IGN); + } + Ok(()) + }); + } + let mut child = cmd.spawn()?; + let stdin = child + .stdin + .take() + .ok_or_else(|| io::Error::other("the watchdog's stdin is not piped"))?; + Ok(Self { child, stdin }) + } + + /// Announce one change. + pub(super) fn send(&mut self, command: WatchCommand) -> io::Result<()> { + self.stdin.write_all(command.line().as_bytes()) + } + + /// Whether the watchdog is still running. + pub(super) fn is_running(&mut self) -> bool { + matches!(self.child.try_wait(), Ok(None)) + } + + #[cfg(test)] + pub(super) fn pid(&self) -> u32 { + self.child.id() + } + + /// Close the pipe, as Staged's exit would, and wait for the watchdog. + #[cfg(test)] + pub(super) fn close_and_wait(self) -> io::Result { + let Self { mut child, stdin } = self; + drop(stdin); + child.wait() + } +} + +/// One line of the watchdog protocol. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum WatchCommand { + /// Group `pgid` is Staged's: stop it if Staged dies. + Watch(i32, GroupKind), + /// Group `pgid` has been stopped by Staged itself. + Forget(i32), +} + +impl WatchCommand { + fn line(self) -> String { + match self { + Self::Watch(pgid, GroupKind::Local) => format!("L {pgid}\n"), + Self::Watch(pgid, GroupKind::Remote) => format!("R {pgid}\n"), + Self::Forget(pgid) => format!("U {pgid}\n"), + } + } + + fn parse(line: &str) -> Option { + let (tag, pgid) = line.trim().split_once(' ')?; + let pgid: i32 = pgid.parse().ok().filter(|&pgid| pgid > 1)?; + match tag { + "L" => Some(Self::Watch(pgid, GroupKind::Local)), + "R" => Some(Self::Watch(pgid, GroupKind::Remote)), + "U" => Some(Self::Forget(pgid)), + _ => None, + } + } +} + +/// Every group the watchdog stops if Staged dies, each with every process it +/// has been seen to have (see [`process_tree::closure`]). +type Watched = BTreeMap)>; + +/// How often the watched groups are walked while Staged runs. The walk at +/// Staged's death alone is not enough: an agent notices its stdin close at +/// the same moment the watchdog does and may exit first, and the children it +/// detached (`setsid()`) are re-parented to launchd, where nothing ties them +/// to the agent any more — except an earlier walk. A child detached and +/// orphaned within one interval of Staged's death can still be missed. +const TRACK_INTERVAL: Duration = Duration::from_millis(500); + +/// Apply one line of the protocol. +fn apply(groups: &mut Watched, line: &str) { + match WatchCommand::parse(line) { + Some(WatchCommand::Watch(pgid, kind)) => { + groups.insert(pgid, (kind, Vec::new())); + } + Some(WatchCommand::Forget(pgid)) => { + groups.remove(&pgid); + } + None => {} + } +} + +/// Remember what every watched group has now, dropping what has gone. +fn track(groups: &mut Watched) { + if groups.is_empty() { + return; + } + let table = process_tree::snapshot(); + for (pgid, (_, known)) in groups.iter_mut() { + *known = process_tree::closure(&table, *pgid, known); + } +} + +/// Apply every line of `input` until it ends, walking the groups every +/// [`TRACK_INTERVAL`] meanwhile. Returns what is watched when it ends. +fn watch_until_closed(input: impl BufRead + Send + 'static) -> Watched { + let groups = std::sync::Arc::new(std::sync::Mutex::new(Watched::new())); + let (closed_tx, closed_rx) = std::sync::mpsc::channel::<()>(); + let reader_groups = std::sync::Arc::clone(&groups); + std::thread::spawn(move || { + for line in input.lines() { + let Ok(line) = line else { break }; + apply(&mut lock(&reader_groups), &line); + } + let _ = closed_tx.send(()); + }); + while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) = + closed_rx.recv_timeout(TRACK_INTERVAL) + { + track(&mut lock(&groups)); + } + let watched = std::mem::take(&mut *lock(&groups)); + watched +} + +fn lock(groups: &std::sync::Mutex) -> std::sync::MutexGuard<'_, Watched> { + groups + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// The watchdog's `main`: never returns. Call it first thing when the process +/// was started with [`WATCHDOG_ARG`], before anything else runs. +pub fn run_watchdog() -> ! { + // SAFETY: changing signal dispositions and closing descriptors this + // process does not use, before any other thread exists. + unsafe { + for signal in IGNORED_SIGNALS { + libc::signal(signal, libc::SIG_IGN); + } + // Only stdio is meant to be inherited; anything else that leaked + // through (a descriptor some library opened without `O_CLOEXEC`) would + // be held open after Staged is gone. + let max_fd = libc::sysconf(libc::_SC_OPEN_MAX).clamp(256, 65536) as libc::c_int; + for fd in 3..max_fd { + libc::close(fd); + } + } + + let groups = watch_until_closed(io::BufReader::new(io::stdin())); + if !groups.is_empty() { + let groups: Vec<(i32, GroupKind, Vec)> = groups + .into_iter() + .map(|(pgid, (kind, known))| (pgid, kind, known)) + .collect(); + let signalled = process_tree::reap_blocking(&groups, WATCHDOG_GRACE); + eprintln!( + "staged agent reaper: Staged exited; stopped {} agent process group(s) \ + ({signalled} process(es))", + groups.len() + ); + } + std::process::exit(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_round_trip_through_their_lines() { + for command in [ + WatchCommand::Watch(4242, GroupKind::Local), + WatchCommand::Watch(77, GroupKind::Remote), + WatchCommand::Forget(4242), + ] { + assert_eq!(WatchCommand::parse(&command.line()), Some(command)); + } + // Never a group signal to everything (`kill(-1)`) or to launchd. + assert_eq!(WatchCommand::parse("L 1"), None); + assert_eq!(WatchCommand::parse("L 0"), None); + assert_eq!(WatchCommand::parse("L -5"), None); + assert_eq!(WatchCommand::parse("X 5"), None); + } + + #[test] + fn the_watched_set_is_what_was_announced_and_not_forgotten() { + let input = "L 100\nR 200\nL 300\nU 100\ngarbage\nL 400\n"; + let mut groups = Watched::new(); + for line in input.lines() { + apply(&mut groups, line); + } + assert_eq!( + groups + .into_iter() + .map(|(pgid, (kind, _))| (pgid, kind)) + .collect::>(), + vec![ + (200, GroupKind::Remote), + (300, GroupKind::Local), + (400, GroupKind::Local) + ] + ); + } +} diff --git a/crates/acp-client/src/driver.rs b/crates/acp-client/src/driver.rs index 6c7235852..7a802cab8 100644 --- a/crates/acp-client/src/driver.rs +++ b/crates/acp-client/src/driver.rs @@ -48,6 +48,7 @@ use nix::sys::signal::{self, Signal}; #[cfg(unix)] use nix::unistd::Pid; +use crate::agent_reaper::AgentGroup; use crate::types::blox_acp_command; mod attach; @@ -2997,15 +2998,36 @@ impl AcpDriver { // opaque "server shut down unexpectedly". .stderr(Stdio::piped()) .kill_on_drop(true); - // Put remote proxies in their own process group so we can send - // SIGINT to the entire group (sq + its child processes) for graceful - // shutdown. We must NOT do this for local interactive shells because - // process_group(0) detaches the child from the controlling terminal, - // which breaks zsh's job-control / precmd hooks — the shell either - // hangs or exits immediately without running `exec`. + // Remote proxies lead a process group of their own, so a graceful + // shutdown can send SIGINT to the whole group (`sq` and its children). + // + // Local agents lead a *session* of their own, with no controlling + // terminal. Left on Staged's terminal, an interactive login shell + // (the shell-spawn path's `$SHELL -i -l -s`, or one the agent starts + // itself) makes itself the terminal's foreground process group, and + // Staged's next log line or terminal read then gets it stopped with + // SIGTTOU/SIGTTIN — the terminal shows `suspended (tty output)`. + // `process_group(0)` alone is not enough: the shell is still on the + // terminal, sees itself in the background and stops itself until + // foregrounded. With no terminal at all it runs without job control, + // and its rc files and precmd hooks (Hermit) still run. + // + // That takes away what the terminal did for us — SIGHUP when it + // closes, SIGINT on Ctrl-C — so the agent's session is registered + // with the agent reaper once spawned (see `agent_reaper`), which + // stops it with everything it started however Staged exits. + #[cfg(unix)] if self.is_remote { - #[cfg(unix)] cmd.process_group(0); + } else { + // SAFETY: `setsid()` is async-signal-safe and touches nothing + // else between fork and exec. + unsafe { + cmd.pre_exec(|| { + libc::setsid(); + Ok(()) + }); + } } // extra_env is applied last so per-session overrides always win: over // the captured snapshot (local direct-spawn path) and over the @@ -3102,6 +3124,17 @@ impl AcpDriver { ) } else { let mut child = cmd.spawn().map_err(spawn_error)?; + // Registered before anything can fail, so an early return still + // takes the agent's whole session with it (see `AgentGroup`'s + // drop), not just its pid (`kill_on_drop`). + let group = AgentGroup::local(child.id()); + log::info!( + "Spawned {} for session {session_id}: pid {}{via_shell}", + self.agent_label, + child + .id() + .map_or_else(|| "unknown".to_string(), |pid| pid.to_string()) + ); let child_exited = CancellationToken::new(); if let (Some(observer), Some(pid)) = (&self.agent_process_observer, child.id()) { observe_agent_process(observer, pid, &child_exited); @@ -3146,7 +3179,7 @@ impl AcpDriver { .ok_or_else(|| "Failed to get stdout".to_string())?; let incoming = normalized_stdout(stdout, false, Arc::clone(&transport)); ( - AgentProcess::Local(child), + AgentProcess::Local(child, group), child_exited, Box::new(stdin), incoming, @@ -3475,8 +3508,9 @@ impl AgentDriver for AcpDriver { /// The agent process behind one session's connection. enum AgentProcess { - /// A local agent this session spawned and owns. - Local(tokio::process::Child), + /// A local agent this session spawned and owns, and the session it + /// leads. + Local(tokio::process::Child, AgentGroup), /// This session's lease on a remote agent proxy other sessions may share. Remote(remote_process::RemoteProcessLease), } @@ -3485,7 +3519,7 @@ impl AgentProcess { /// How the remote agent was lost under this session, if it was. fn loss(&self) -> Option { match self { - Self::Local(_) => None, + Self::Local(..) => None, Self::Remote(lease) => lease.loss(), } } @@ -3494,7 +3528,7 @@ impl AgentProcess { /// it was. fn cut_off(&self) -> Option { match self { - Self::Local(_) => None, + Self::Local(..) => None, Self::Remote(lease) => lease.cut_off(), } } @@ -3508,7 +3542,7 @@ impl AgentProcess { async fn release(self, transport: &TransportMonitor) { transport.begin_teardown(); match self { - Self::Local(mut child) => graceful_stop(&mut child, false).await, + Self::Local(mut child, mut group) => group.stop(&mut child, LOCAL_STOP_GRACE).await, Self::Remote(lease) => { if transport.spares_proxy() { lease.never_interrupt(); @@ -3556,6 +3590,11 @@ where /// its whole process group is SIGKILLed. const GRACEFUL_STOP_GRACE: Duration = Duration::from_secs(5); +/// How long a local agent and everything it started get to exit after +/// SIGTERM before they are SIGKILLed (see [`AgentGroup::stop`]). Short: the +/// session is over, and a quit waits on it inside its own small budget. +const LOCAL_STOP_GRACE: Duration = Duration::from_secs(1); + /// Gracefully stop the ACP child process. /// /// For remote proxies (spawned with `process_group(0)`), sends SIGINT to the @@ -3569,7 +3608,8 @@ const GRACEFUL_STOP_GRACE: Duration = Duration::from_secs(5); /// last running member — and could go on relaying whatever was queued for /// the workstation after Staged has finished with the session. /// -/// For local agents (no separate process group), kills immediately. +/// A local agent is stopped by its [`AgentGroup`] instead; given one here, +/// only its pid is killed. async fn graceful_stop(child: &mut tokio::process::Child, is_remote: bool) { graceful_stop_with_grace(child, is_remote, GRACEFUL_STOP_GRACE).await } diff --git a/crates/acp-client/src/driver/attach.rs b/crates/acp-client/src/driver/attach.rs index 6cbd41179..a20dc041a 100644 --- a/crates/acp-client/src/driver/attach.rs +++ b/crates/acp-client/src/driver/attach.rs @@ -148,6 +148,8 @@ type ProxyStreams = /// A spawned `sq blox acp` attached to the session's process. struct AttachProxy { child: tokio::process::Child, + /// Registered with the agent reaper while the proxy lives. + _group: AgentGroup, transport: Arc, streams: ProxyStreams, } @@ -213,6 +215,7 @@ impl AcpDriver { resolve_acp_working_dir(working_dir, true, self.remote_working_dir.as_deref())?; let AttachProxy { mut child, + _group, transport, streams, } = self.spawn_attach_proxy(session_id, command_id, working_dir)?; @@ -392,6 +395,7 @@ impl AcpDriver { let catch_up = std::cell::RefCell::new(catch_up); let AttachProxy { mut child, + _group, transport, streams, } = self.spawn_attach_proxy(session_id, command_id, working_dir)?; @@ -599,6 +603,7 @@ impl AcpDriver { ) })?; + let group = AgentGroup::remote(child.id()); let transport = TransportMonitor::new(); #[cfg(unix)] if let Some(pid) = child.id().and_then(|pid| i32::try_from(pid).ok()) { @@ -630,6 +635,7 @@ impl AcpDriver { ); Ok(AttachProxy { child, + _group: group, transport, streams, }) diff --git a/crates/acp-client/src/driver/remote_process.rs b/crates/acp-client/src/driver/remote_process.rs index d4dfc3d2d..be29598ab 100644 --- a/crates/acp-client/src/driver/remote_process.rs +++ b/crates/acp-client/src/driver/remote_process.rs @@ -52,6 +52,7 @@ use super::remote_liveness::{self, CommandStart, Liveness}; use super::remote_routing::{ RemoteClientId, RemoteLoss, RemoteTransport, RoutedClientStreams, CANCELLED_STOP_REASON, }; +use crate::agent_reaper::AgentGroup; static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1); @@ -855,6 +856,9 @@ async fn run_proxy( return; } }; + // Held to the end of this function, past the proxy's teardown below: + // should Staged die first, the agent reaper SIGKILLs the group. + let _group = AgentGroup::remote(child.id()); let (Some(stdin), Some(stdout), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take()) else { diff --git a/crates/acp-client/src/lib.rs b/crates/acp-client/src/lib.rs index 68d820623..d47a07206 100644 --- a/crates/acp-client/src/lib.rs +++ b/crates/acp-client/src/lib.rs @@ -17,6 +17,7 @@ //! 2. **Simple one-shot interface** (`run_acp_prompt`) - For simple prompting //! without session management +pub mod agent_reaper; mod driver; mod simple; mod types;