Skip to main content

agentmux_launcher/
upgrade.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! [`quiesce_srv`]: the launcher's one way of stopping srv, used on every
5//! quit by both supervisors and on "Upgrade & restart". It returns only once
6//! the OS has genuinely reaped the process (`Child::wait()`'s own contract),
7//! never after a fixed sleep: data must never change while a srv may still
8//! hold it (`341faa981`'s data-loss incident).
9//!
10//! This module began as phase 1 of
11//! `docs/specs/SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md`,
12//! with a "quiesce srv, migrate, come back" path for an upgrade action. That
13//! path became the launcher's prepare step instead (§10): srv refuses data
14//! that needs preparing and exits, and `srv_spawner::spawn_srv` runs
15//! `agentmux-srv migrate --prepare` before starting it again.
16
17use std::time::Duration;
18
19use tokio::process::Child;
20
21/// How long [`quiesce_srv`] waits for srv to exit on its own before
22/// escalating to a hard kill: long enough for srv to close every agent
23/// (`agent_teardown::app_exit`, capped at `SRV_APP_EXIT_CAP`).
24pub const GRACEFUL_QUIESCE_TIMEOUT: Duration = agentmux_common::process::SRV_EXIT_WAIT;
25
26/// How [`quiesce_srv`] actually stopped the process — logged, and useful in
27/// tests, but callers don't need to branch on it: either variant means the
28/// same thing (the process is genuinely gone).
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum QuiesceOutcome {
31    /// The child had already exited before this call (e.g. a crash that
32    /// raced the upgrade request).
33    AlreadyExited,
34    /// Exited on its own within the graceful window, after being told to.
35    ExitedGracefully,
36    /// Didn't exit in time and was force-killed.
37    ExitedAfterForceKill,
38}
39
40/// Stop srv and return only once it has genuinely exited — never a fixed
41/// sleep. The launcher's one way of stopping srv: on every quit (both
42/// supervisors) and on "Upgrade & restart".
43///
44/// Telling srv to stop is dropping `stdin`, its keepalive pipe: srv reads
45/// EOF as "shut down" on every platform (`bootstrap::install_shutdown_handlers`)
46/// and closes every agent gracefully on the way out
47/// (`agent_teardown::app_exit`). Unix also gets SIGTERM, which does the same.
48/// Only if srv hasn't exited after `graceful_timeout` is it force-killed —
49/// on Windows, whatever it still runs then goes with J0.
50pub async fn quiesce_srv(
51    child: &mut Child,
52    stdin: Option<tokio::process::ChildStdin>,
53    graceful_timeout: Duration,
54) -> std::io::Result<(std::process::ExitStatus, QuiesceOutcome)> {
55    if let Ok(Some(status)) = child.try_wait() {
56        return Ok((status, QuiesceOutcome::AlreadyExited));
57    }
58    drop(stdin);
59    #[cfg(not(target_os = "windows"))]
60    crate::host_spawn::terminate_child_gracefully(child);
61    match tokio::time::timeout(graceful_timeout, child.wait()).await {
62        Ok(status) => Ok((status?, QuiesceOutcome::ExitedGracefully)),
63        Err(_elapsed) => {
64            // With srv's process group, while srv is still unreaped (so its
65            // pid is still its own): whatever else srv started in that group
66            // (its helpers, anything not in a group of its own) goes with it.
67            // Its agent CLIs lead groups of their own and are ended by the
68            // caller (`agent_roots::kill_orphans`).
69            agentmux_common::process::start_kill_child_and_group(child)?;
70            let status = child.wait().await?;
71            Ok((status, QuiesceOutcome::ExitedAfterForceKill))
72        }
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    #[cfg(not(target_os = "windows"))]
80    use tokio::io::{AsyncBufReadExt, BufReader};
81
82    /// Portable "runs for a while, does nothing" child: `sleep` on Unix,
83    /// `ping` on Windows (`timeout.exe` refuses to run with no console —
84    /// "Input redirection is not supported" — the standard Windows-
85    /// automation workaround for a long-lived, headless-safe dummy process
86    /// is a ping loop against loopback, which never needs a console).
87    fn spawn_long_lived() -> Child {
88        #[cfg(not(target_os = "windows"))]
89        {
90            tokio::process::Command::new("sleep")
91                .arg("30")
92                .kill_on_drop(true)
93                .spawn()
94                .expect("spawn sleep")
95        }
96        #[cfg(target_os = "windows")]
97        {
98            tokio::process::Command::new("cmd")
99                .args(["/C", "ping", "-n", "30", "127.0.0.1"])
100                .kill_on_drop(true)
101                .spawn()
102                .expect("spawn ping")
103        }
104    }
105
106    /// A child that ignores SIGTERM, forcing `quiesce_srv`'s escalation
107    /// path (it has no stdin to close). Unix only: Windows sends no signal
108    /// to ignore, so its escalation path is covered by the live-child test.
109    ///
110    /// Blocks until the child confirms its trap is actually installed
111    /// before returning — sending SIGTERM immediately after `spawn()` races
112    /// the shell's own startup (parse `-c`, run `trap`, THEN start `sleep`),
113    /// and on a loaded CI runner that race is real: a signal arriving
114    /// before `trap ''` executes finds SIGTERM at its default disposition
115    /// and the shell dies immediately, which is exactly the CI-only flake
116    /// this fixes (`ExitedGracefully` instead of `ExitedAfterForceKill`,
117    /// ubuntu-latest, PR #3352). Piping stdout and reading one line back is
118    /// a real synchronization point, not a fixed delay that would just
119    /// narrow the window instead of closing it.
120    #[cfg(not(target_os = "windows"))]
121    async fn spawn_sigterm_immune() -> Child {
122        let mut child = tokio::process::Command::new("sh")
123            .args(["-c", "trap '' TERM; echo ready; sleep 30"])
124            .stdout(std::process::Stdio::piped())
125            .kill_on_drop(true)
126            .spawn()
127            .expect("spawn sigterm-immune shell");
128
129        let stdout = child.stdout.take().expect("piped stdout");
130        let mut lines = BufReader::new(stdout).lines();
131        let line = lines
132            .next_line()
133            .await
134            .expect("read readiness line")
135            .expect("readiness line present");
136        assert_eq!(line.trim(), "ready", "trap must be installed before the test signals this child");
137
138        child
139    }
140
141    /// The force-kill takes srv's process group too: a helper srv started in
142    /// its own group (not a group of its own) must not outlive it.
143    #[cfg(not(target_os = "windows"))]
144    #[tokio::test]
145    async fn the_force_kill_takes_the_childs_process_group() {
146        use std::os::unix::process::CommandExt as _;
147        let mut child = tokio::process::Command::new("sh")
148            .args(["-c", "trap '' TERM; sleep 30 & echo $!; wait"])
149            .stdout(std::process::Stdio::piped())
150            .process_group(0)
151            .kill_on_drop(true)
152            .spawn()
153            .expect("spawn a group leader that ignores SIGTERM");
154        let mut lines = BufReader::new(child.stdout.take().expect("piped stdout")).lines();
155        let helper: u32 = lines.next_line().await.unwrap().unwrap().trim().parse().unwrap();
156        assert!(agentmux_common::process::process_start_time(helper).is_some());
157
158        let (_, outcome) = quiesce_srv(&mut child, None, Duration::from_millis(300)).await.unwrap();
159        assert_eq!(outcome, QuiesceOutcome::ExitedAfterForceKill);
160        let mut gone = false;
161        for _ in 0..100 {
162            let zombie = std::fs::read_to_string(format!("/proc/{helper}/stat"))
163                .ok()
164                .and_then(|t| t.rfind(')').map(|i| t[i + 1..].trim_start().starts_with('Z')))
165                .unwrap_or(false);
166            if agentmux_common::process::process_start_time(helper).is_none() || zombie {
167                gone = true;
168                break;
169            }
170            tokio::time::sleep(Duration::from_millis(20)).await;
171        }
172        assert!(gone, "helper {helper} outlived the force-kill of its group leader");
173    }
174
175    #[tokio::test]
176    async fn already_exited_child_is_reported_without_signaling_anything() {
177        let mut child = tokio::process::Command::new(if cfg!(windows) { "cmd" } else { "true" })
178            .args(if cfg!(windows) { vec!["/C", "exit 0"] } else { vec![] })
179            .kill_on_drop(true)
180            .spawn()
181            .expect("spawn a trivially-exiting child");
182        // Let it actually exit and get reaped before quiescing.
183        let _ = tokio::time::timeout(Duration::from_secs(5), child.wait())
184            .await
185            .expect("child did not exit");
186
187        let (status, outcome) = quiesce_srv(&mut child, None, Duration::from_secs(1))
188            .await
189            .expect("quiesce_srv must not error on an already-exited child");
190
191        assert_eq!(outcome, QuiesceOutcome::AlreadyExited);
192        assert!(status.success());
193    }
194
195    #[tokio::test]
196    async fn a_live_child_is_actually_stopped_and_reaped() {
197        // The core guarantee this function exists for: not a sleep, a real
198        // wait for a real exit. A long-lived process that were merely
199        // signaled-and-assumed-dead (the bug this replaces) would still be
200        // running here; this asserts the OS has actually reaped it.
201        let mut child = spawn_long_lived();
202        let pid = child.id().expect("live child has a pid");
203
204        // A short graceful window: on Windows nothing here tells the dummy
205        // to stop, so it is force-killed when the window ends.
206        let (_status, _outcome) = tokio::time::timeout(
207            Duration::from_secs(15),
208            quiesce_srv(&mut child, None, Duration::from_secs(1)),
209        )
210        .await
211        .expect("quiesce_srv hung instead of returning once the child exited")
212        .expect("quiesce_srv errored");
213
214        // A second wait on the same handle must not hang or find a live
215        // process — the child is genuinely gone, not merely signaled.
216        assert!(
217            tokio::time::timeout(Duration::from_millis(500), child.wait())
218                .await
219                .is_ok(),
220            "pid {pid} should already be reaped after quiesce_srv returned"
221        );
222    }
223
224    #[cfg(not(target_os = "windows"))]
225    #[tokio::test]
226    async fn a_sigterm_ignoring_child_is_force_killed_after_the_timeout() {
227        use std::os::unix::process::ExitStatusExt;
228
229        let mut child = spawn_sigterm_immune().await;
230
231        let (status, outcome) = tokio::time::timeout(
232            Duration::from_secs(10),
233            // Short graceful window so the test doesn't wait the full
234            // production 10s to prove the escalation path.
235            quiesce_srv(&mut child, None, Duration::from_millis(300)),
236        )
237        .await
238        .expect("quiesce_srv hung past its own escalation timeout")
239        .expect("quiesce_srv errored");
240
241        assert_eq!(outcome, QuiesceOutcome::ExitedAfterForceKill);
242        assert_eq!(status.signal(), Some(libc::SIGKILL));
243    }
244
245    /// Closing stdin is the stop signal on every platform (it is the only
246    /// one on Windows): a child that ignores SIGTERM but exits on stdin EOF,
247    /// as srv does, exits gracefully.
248    #[cfg(not(target_os = "windows"))]
249    #[tokio::test]
250    async fn closing_stdin_stops_a_child_that_ignores_sigterm() {
251        let mut child = tokio::process::Command::new("sh")
252            .args(["-c", "trap '' TERM; echo ready; cat >/dev/null"])
253            .stdin(std::process::Stdio::piped())
254            .stdout(std::process::Stdio::piped())
255            .kill_on_drop(true)
256            .spawn()
257            .expect("spawn stdin-reading shell");
258        let stdin = child.stdin.take();
259        let stdout = child.stdout.take().expect("piped stdout");
260        let line = BufReader::new(stdout).lines().next_line().await.expect("read").expect("line");
261        assert_eq!(line.trim(), "ready");
262
263        let (status, outcome) = tokio::time::timeout(
264            Duration::from_secs(10),
265            quiesce_srv(&mut child, stdin, Duration::from_secs(5)),
266        )
267        .await
268        .expect("quiesce_srv hung")
269        .expect("quiesce_srv errored");
270
271        assert_eq!(outcome, QuiesceOutcome::ExitedGracefully);
272        assert!(status.success());
273    }
274
275    #[cfg(not(target_os = "windows"))]
276    #[tokio::test]
277    async fn a_child_that_honors_sigterm_exits_gracefully_not_via_force_kill() {
278        // Plain `sleep` has no signal handler — the default SIGTERM action
279        // is immediate termination, so this should resolve almost
280        // instantly, well inside the graceful window, and never reach the
281        // force-kill branch.
282        let mut child = spawn_long_lived();
283
284        let (_status, outcome) = tokio::time::timeout(
285            Duration::from_secs(5),
286            quiesce_srv(&mut child, None, GRACEFUL_QUIESCE_TIMEOUT),
287        )
288        .await
289        .expect("quiesce_srv hung")
290        .expect("quiesce_srv errored");
291
292        assert_eq!(outcome, QuiesceOutcome::ExitedGracefully);
293    }
294}