diff --git a/native/host/src/files/git.rs b/native/host/src/files/git.rs index add103e0db..368e35a900 100644 --- a/native/host/src/files/git.rs +++ b/native/host/src/files/git.rs @@ -32,7 +32,8 @@ async fn spawn(cmd: &str, args: &[&str], cwd: &str, env: &[(&str, &str)], kill: c.args(args).current_dir(cwd).stdin(std::process::Stdio::null()).envs(GIT_ENV.iter().copied()).envs(env.iter().copied()).kill_on_drop(kill); // a listed read on a copy must not refresh the real repository's index or take its lock while a live agent works there (git status would) if crate::copy::on() { c.env("GIT_OPTIONAL_LOCKS", "0"); } - match c.output().await { + // the exit through proc::output (proc::wait): tokio's own output() waits for SIGCHLD once the pipes close, and a macOS hub that misses it waits for ever (#1108, #1110) + match crate::proc::output(&mut c).await { Ok(o) => { let mut out = String::from_utf8_lossy(&o.stdout).into_owned(); out.push_str(&String::from_utf8_lossy(&o.stderr)); Ran { code: o.status.code().unwrap_or(1), out } } Err(e) => Ran { code: 127, out: e.to_string() }, } diff --git a/native/host/src/proc.rs b/native/host/src/proc.rs index 2a864257b2..868a367f1d 100644 --- a/native/host/src/proc.rs +++ b/native/host/src/proc.rs @@ -476,6 +476,50 @@ pub fn probe_output(c: std::process::Command, limit: std::time::Duration) -> Opt pub fn kicad_probe_tokio>(cli: S) -> (tokio::process::Command, ProbeHome) { let h = ProbeHome::new(); let mut c = tokio_cmd(Kind::Local, cli); c.envs(h.env()); (c, h) } +/// How often [`wait`] asks a child whether it has exited, at most. +const WAIT_POLL_MAX: std::time::Duration = std::time::Duration::from_millis(250); +/// A tokio child's exit, without depending on SIGCHLD alone (h04x3d, #1108/#1110). tokio's own `wait()` asks once and then waits for SIGCHLD; on Linux it has +/// a pidfd for each child, but on macOS that signal is all it has, and a hub there that missed it (a signal mask inherited from the desktop app's thread, +/// fixed in e16ae77c6) never saw a child exit that came after the first ask. So the exit is also asked for (`try_wait`, a `waitpid` on this child's pid +/// through tokio, which cannot take another child's status) every few ms at first, then every 250 ms; whichever comes first wins. tokio's `wait()` is +/// cancel-safe, so it is dropped and asked again on each round. +pub async fn wait(child: &mut tokio::process::Child) -> std::io::Result { + let mut gap = std::time::Duration::from_millis(5); + loop { + if let Some(s) = child.try_wait()? { return Ok(s) } + tokio::select! { + s = child.wait() => return s, + _ = tokio::time::sleep(gap) => {} + } + gap = (gap * 2).min(WAIT_POLL_MAX); + } +} +/// `Command::output`, with the exit taken by [`wait`]: stdout and stderr read to their ends (both at once, so neither pipe fills), then the exit. As tokio's +/// `output()`, the child's stdin is null: nothing is ever written to it here, so a piped one would hold a child that reads it until the wait. +pub async fn output(c: &mut tokio::process::Command) -> std::io::Result { + use tokio::io::AsyncReadExt; + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let mut child = c.spawn()?; + let (mut o, mut e) = (child.stdout.take(), child.stderr.take()); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let read_o = async { if let Some(p) = o.as_mut() { p.read_to_end(&mut stdout).await.map(|_| ()) } else { Ok(()) } }; + let read_e = async { if let Some(p) = e.as_mut() { p.read_to_end(&mut stderr).await.map(|_| ()) } else { Ok(()) } }; + let (ro, re) = tokio::join!(read_o, read_e); ro?; re?; + let status = wait(&mut child).await?; + Ok(std::process::Output { status, stdout, stderr }) +} +/// A child that was killed and is no longer needed: kill it, then reap it in the background with [`wait`] (for at most a minute), instead of dropping +/// it to tokio's orphan queue, which is only drained on a SIGCHLD. Needs a tokio runtime (every caller is async). +pub fn kill_and_reap(mut child: tokio::process::Child) { + let _ = child.start_kill(); + tokio::spawn(async move { let _ = tokio::time::timeout(std::time::Duration::from_secs(60), wait(&mut child)).await; }); +} +/// Kill a child and wait up to `limit` for its exit; one that is not seen to exit by then is reaped in the background ([`kill_and_reap`]), so the +/// caller is never held past `limit` and no zombie is left. +pub async fn kill_wait(mut child: tokio::process::Child, limit: std::time::Duration) { + let _ = child.start_kill(); + if tokio::time::timeout(limit, wait(&mut child)).await.is_err() { kill_and_reap(child) } +} /// `std::process::Command::new`, gated. pub fn std_cmd>(kind: Kind, program: S) -> std::process::Command { let p = program.as_ref().to_string_lossy().into_owned(); @@ -493,6 +537,29 @@ pub fn std_cmd>(kind: Kind, program: S) -> std::process::Command mod tests { use super::*; + #[cfg(unix)] #[tokio::test] async fn a_childs_exit_is_taken_without_sigchld_and_a_killed_child_is_reaped() { + let mut c = tokio::process::Command::new("sh"); c.args(["-c", "printf out; printf err >&2; exit 3"]); + let o = output(&mut c).await.unwrap(); + assert_eq!((o.status.code(), o.stdout.as_slice(), o.stderr.as_slice()), (Some(3), &b"out"[..], &b"err"[..])); + // a child that would read its stdin: output() gives it a null one, so it ends at once instead of waiting + let mut r = tokio::process::Command::new("sh"); r.args(["-c", "cat; echo done"]).stdin(std::process::Stdio::piped()); + let o = tokio::time::timeout(std::time::Duration::from_secs(5), output(&mut r)).await.expect("stdin is null").unwrap(); + assert_eq!(o.stdout, b"done\n"); + // a child still running when it is waited for: the exit comes by asking, as it must where SIGCHLD is missed + let mut ch = tokio::process::Command::new("sh").args(["-c", "sleep 0.3"]).spawn().unwrap(); + assert!(tokio::time::timeout(std::time::Duration::from_secs(5), wait(&mut ch)).await.unwrap().unwrap().success()); + // killed and handed over: reaped in the background, not left as a zombie + let ch = tokio::process::Command::new("sleep").arg("30").spawn().unwrap(); let pid = ch.id().unwrap() as i32; + kill_and_reap(ch); + let mut gone = false; + for _ in 0..100 { tokio::time::sleep(std::time::Duration::from_millis(20)).await; if unsafe { libc::kill(pid, 0) } != 0 { gone = true; break } } + assert!(gone, "the killed child was reaped"); + // kill_wait: back within its limit, the child gone + let ch = tokio::process::Command::new("sleep").arg("30").spawn().unwrap(); let pid = ch.id().unwrap() as i32; + let t = std::time::Instant::now(); kill_wait(ch, std::time::Duration::from_secs(2)).await; + assert!(t.elapsed() < std::time::Duration::from_secs(3) && unsafe { libc::kill(pid, 0) } != 0, "killed and reaped within the limit"); + } + #[test] fn a_test_never_runs_the_real_tailscale() { let tmp = std::path::Path::new(if cfg!(windows) { "C:\\Users\\x\\AppData\\Local\\Temp" } else { "/tmp" }); for p in ["tailscale", "tailscale.exe", "TailScale.EXE", "/usr/bin/tailscale", "C:\\Program Files\\Tailscale\\tailscale.exe", "C:/Program Files/Tailscale/tailscale.exe", "/tmp-evil/tailscale"] { diff --git a/native/host/src/settings/accounts_io.rs b/native/host/src/settings/accounts_io.rs index 3e88bd41b1..df87debd5f 100644 --- a/native/host/src/settings/accounts_io.rs +++ b/native/host/src/settings/accounts_io.rs @@ -344,7 +344,7 @@ impl Rpc { self.stdin.write_all(b"{\"method\":\"initialized\",\"params\":{}}\n").await.map_err(|_| ()) } /// Killed, and its exit waited for a moment only: a missed exit (#1108) must not hold the op that closes it. - async fn close(mut self) { let _ = self.child.start_kill(); let _ = tokio::time::timeout(Duration::from_secs(3), self.child.wait()).await; } + async fn close(self) { crate::proc::kill_wait(self.child, Duration::from_secs(3)).await } } /// The variables that point a CLI at one profile's store (`environment` sets them). The default login never inherits them: a hub started from a shell that /// ran under a profile (an agent's own Bash, after failover moved it) would otherwise run every default-login thread, and read its usage, under that profile. @@ -511,9 +511,9 @@ impl Accounts { let ran = tokio::time::timeout(limit, async { let mut chunk = [0u8; 8192]; loop { let n = out.read(&mut chunk).await.map_err(|_| ())?; if n == 0 { break } buf.extend_from_slice(&chunk[..n]); if buf.len() > 131072 { return Err(()) } } - Ok::(child.wait().await.map_err(|_| ())?.code().unwrap_or(-1)) + Ok::(crate::proc::wait(&mut child).await.map_err(|_| ())?.code().unwrap_or(-1)) }).await; - let code = match ran { Ok(Ok(code)) => code, _ => { let _ = child.start_kill(); let _ = tokio::time::timeout(Duration::from_secs(2), child.wait()).await; return Err(()) } }; + let code = match ran { Ok(Ok(code)) => code, _ => { crate::proc::kill_wait(child, Duration::from_secs(2)).await; return Err(()) } }; let data = if args.get(1) == Some(&"logout") { json!({}) } else { serde_json::from_slice(&buf).map_err(|_| ())? }; Ok((code, data)) } @@ -550,8 +550,7 @@ impl Accounts { Err("The Claude CLI closed before reporting usage.".to_string()) }).await.unwrap_or_else(|_| Err("The Claude CLI did not answer within 30 seconds.".to_string())) }.await; - let _ = child.start_kill(); - let _ = tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()).await; + crate::proc::kill_wait(child, Duration::from_secs(2)).await; // reaped, not dropped: one zombie per usage read on a hub that missed SIGCHLD r } /// A test's usage request and CLI store (the real hub's are set in `open`). @@ -1071,8 +1070,8 @@ impl Accounts { Some(b) => { output.push_str(&String::from_utf8_lossy(&b)); if output.len() > 131072 { break Err("failed") } if let Some(u) = scan(&output, &mut reason) { if self.current(&aid).is_some() { self.set_waiting(&aid, u, String::new()); } } } None => open = false, }, - cmd = cmds.recv() => match cmd { Some(Cmd::Respond(code)) => { let _ = stdin.write_all(format!("{code}\n").as_bytes()).await; } Some(Cmd::Cancel) | None => { let _ = child.start_kill(); let _ = child.wait().await; return } }, - st = child.wait() => { + cmd = cmds.recv() => match cmd { Some(Cmd::Respond(code)) => { let _ = stdin.write_all(format!("{code}\n").as_bytes()).await; } Some(Cmd::Cancel) | None => { let _ = child.start_kill(); let _ = crate::proc::wait(&mut child).await; return } }, + st = crate::proc::wait(&mut child) => { // whatever it printed last still counts (why a code was refused) while let Ok(Some(b)) = tokio::time::timeout(Duration::from_millis(200), orx.recv()).await { output.push_str(&String::from_utf8_lossy(&b)); let _ = scan(&output, &mut reason); } break Ok(st.map(|s| s.success()).unwrap_or(false)) @@ -1080,7 +1079,7 @@ impl Accounts { _ = tokio::time::sleep_until(deadline) => break Err("expired"), } }; - let _ = child.start_kill(); let _ = child.wait().await; + let _ = child.start_kill(); let _ = crate::proc::wait(&mut child).await; match outcome { Ok(ok) => self.finish(&aid, &cand, ok, &reason).await, Err("expired") => self.cancel(&aid, "expired", ""), Err(_) => self.cancel(&aid, "failed", "") } } }