From 0069623cf40310bedb8e7191b58b66d8e92bc2e8 Mon Sep 17 00:00:00 2001 From: jlcjak <206324213+jlcjak@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:05:14 +0200 Subject: [PATCH 1/2] guard: a sleeping Mac is no longer taken for a hung hub A Mac user saw the hub restart overnight ("stopped answering", "start stalled for 1054 s") and builds marked bad after the laptop slept. The hub stored each part's last good check by the wall clock while its checks run on tokio's timers, which stop while the machine sleeps. At a Power Nap DarkWake (about 2 s, every 15 minutes) every part looked hours old, the wake was too short for the next check, and six wakes in a row ended a well hub. The guard measured a start's stall by the phase file's wall-clock age, so a sleep counted as a stall. - hub guard.rs: the last good checks are kept on the monotonic clock, as the timers are. - guard run.rs: a start's stall is measured on Instant from the last change of the phase file. - guard plan.rs SleepClock: the wall clock running >10 s past the monotonic one is a sleep; it resets the miss count, and a failed check within 30 s of a wake is logged, not counted. Found and first fixed by h04x3d (fix/macos-sleep on their fork); taken as is, without that branch's child-reaping part, which main covers since e16ae77c6 (#1456). Tested: guard crate tests (45, incl. plan::a_sleep_is_told_from_a_hang_by_the_two_clocks), hub guard:: tests (25). Not run on a Mac. Co-authored-by: h04x3d <33473989+h04x3d@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- native/guard/src/plan.rs | 40 ++++++++++++++++++++++++++++++++++++++++ native/guard/src/run.rs | 11 +++++++++-- native/host/src/guard.rs | 10 +++++++--- 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/native/guard/src/plan.rs b/native/guard/src/plan.rs index 564a1ebf35..114be6b223 100644 --- a/native/guard/src/plan.rs +++ b/native/guard/src/plan.rs @@ -148,6 +148,30 @@ pub fn holds_proof(health: &serde_json::Value) -> bool { health["folding"].as_u64().unwrap_or(0) > 0 || health["migrating"]["state"] == "running" || health["status"] == "migrating" } +/// The machine slept since the last look: the wall clock moved this much more than the monotonic one (`Instant`, which stops in sleep on macOS +/// and Linux). A clock set by hand or by NTP can look the same; that only costs a short grace. +pub const SLEEP_JUMP_S: u64 = 10; +/// How long after a wake a failed health check is not counted: a Mac's DarkWake lasts about 2 s, too short for the hub's 10 s checks to run, and +/// a full wake gives the hub one round of them to catch up. +pub const WAKE_GRACE_S: u64 = 30; +/// Tells a sleep from a hang. `tick` each turn of the guard's loop: true when the machine slept since the last tick. +pub struct SleepClock { last: Option<(std::time::SystemTime, std::time::Instant)>, woke: Option } +impl SleepClock { + pub fn new() -> SleepClock { SleepClock { last: None, woke: None } } + pub fn tick(&mut self, wall: std::time::SystemTime, mono: std::time::Instant) -> bool { + let slept = self.last.map_or(false, |(w, m)| { + let dw = wall.duration_since(w).map_or(0, |d| d.as_secs()); + let dm = mono.saturating_duration_since(m).as_secs(); + dw > dm + SLEEP_JUMP_S + }); + self.last = Some((wall, mono)); + if slept { self.woke = Some(mono) } + slept + } + /// Whether `mono` is within the grace after the last wake. + pub fn waking(&self, mono: std::time::Instant) -> bool { self.woke.map_or(false, |w| mono.saturating_duration_since(w).as_secs() < WAKE_GRACE_S) } +} + #[cfg(test)] mod tests { use super::*; @@ -275,4 +299,20 @@ mod tests { assert!(!holds_proof(&json!({"status": "ok", "folding": 0, "migrating": null}))); assert!(!holds_proof(&serde_json::Value::Null), "an old build's /hello says neither"); } + + #[test] fn a_sleep_is_told_from_a_hang_by_the_two_clocks() { + use std::time::{Duration, Instant, SystemTime}; + let (w0, m0) = (SystemTime::now(), Instant::now()); + let mut c = SleepClock::new(); + assert!(!c.tick(w0, m0), "the first look has nothing to compare"); + assert!(!c.tick(w0 + Duration::from_secs(5), m0 + Duration::from_secs(5)), "awake: both clocks moved together"); + assert!(!c.waking(m0 + Duration::from_secs(5))); + // 17 minutes asleep: the wall clock jumps, the monotonic one barely moves + let (w, m) = (w0 + Duration::from_secs(1057), m0 + Duration::from_secs(6)); + assert!(c.tick(w, m), "a sleep"); + assert!(c.waking(m + Duration::from_secs(2)), "a DarkWake's probe is not counted"); + assert!(!c.waking(m + Duration::from_secs(WAKE_GRACE_S)), "the grace ends"); + assert!(!c.tick(w + Duration::from_secs(3), m + Duration::from_secs(3)), "awake again"); + assert!(!c.tick(w, m + Duration::from_secs(4)), "a wall clock set back is no sleep"); + } } diff --git a/native/guard/src/run.rs b/native/guard/src/run.rs index 3d3095ca1e..6e8e373a8c 100644 --- a/native/guard/src/run.rs +++ b/native/guard/src/run.rs @@ -247,7 +247,12 @@ impl Guard { let mut child = match self.spawn() { Ok(c) => c, Err(e) => return e }; self.hub_pid = child.id(); self.pin(); self.publish(); let (t0, mut ready_at, mut misses, mut last_probe, mut last_said) = (Instant::now(), None::, 0u32, Instant::now(), String::new()); + // the start's progress on the clock the hub's own timers run on (`Instant`, stopped while the machine sleeps): the phase file's age by the wall + // clock counts a night's sleep as a stall ("start stalled for 1054 s" at the first wake after 17 minutes asleep) + let (mut phase_seen, mut phase_at) = (None::, t0); + let mut clock = plan::SleepClock::new(); loop { + if clock.tick(std::time::SystemTime::now(), Instant::now()) { misses = 0; say("the machine slept; health checks start counting again"); } if sys::stop_asked() { self.quit(Some(&mut child)) } match child.try_wait() { Ok(Some(s)) => { self.hub_pid = 0; return self.classify(s) } @@ -281,11 +286,13 @@ impl Guard { } None if well => { ready_at = Some(Instant::now()); say(&format!("{} answers, {} ms after its start", Self::short(&self.build), t0.elapsed().as_millis())); self.set(if self.mode == Mode::Safe { "safe" } else { "running" }); if control && !self.has_control(&self.build) { let mut c = self.d.lines("control"); c.push(self.build.clone()); let from = c.len().saturating_sub(32); let _ = self.d.put("control", &(c[from..].join("\n") + "\n")); } } None => { - let quiet = fs::metadata(self.d.path("phase")).ok().and_then(|m| m.modified().ok()).and_then(|m| m.elapsed().ok()).map_or(t0.elapsed().as_secs(), |e| e.as_secs()); + let m = fs::metadata(self.d.path("phase")).ok().and_then(|m| m.modified().ok()); + if m.is_some() && m != phase_seen { phase_seen = m; phase_at = Instant::now(); } + let quiet = phase_at.elapsed().as_secs(); if quiet >= self.tm.stall || t0.elapsed().as_secs() >= self.tm.boot { let ph = self.d.text("phase"); return self.kill_hung(&mut child, &format!("start stalled for {quiet} s at {}", if ph.trim().is_empty() { "its first step" } else { ph.trim() })) } } Some(at) => { - if well || answered { misses = 0 } else { misses += 1; last_said = said.clone(); say(&format!("health check {misses} of {} failed: {}", self.tm.misses, said.chars().take(160).collect::())) } + if well || answered { misses = 0 } else if clock.waking(Instant::now()) { say(&format!("health check failed just after a wake, not counted: {}", said.chars().take(160).collect::())) } else { misses += 1; last_said = said.clone(); say(&format!("health check {misses} of {} failed: {}", self.tm.misses, said.chars().take(160).collect::())) } if misses >= self.tm.misses { let why = format!("stopped answering: {}", last_said.chars().take(160).collect::()); return self.kill_hung(&mut child, &why) } // the clock that proves a build starts when its folds and any migration are over: a crash at the end of a long fold or import is the // start failing, while a long import itself is not (plan::holds_proof) diff --git a/native/host/src/guard.rs b/native/host/src/guard.rs index 207be0fb22..d79b13d631 100644 --- a/native/host/src/guard.rs +++ b/native/host/src/guard.rs @@ -37,6 +37,10 @@ pub fn carry_wait() -> u64 { std::env::var("BACKPLANE_CARRY_WAIT").ok().and_then fn dir() -> Option { HOME.get().map(|h| h.join("guard")) } fn now_s() -> u64 { crate::hub::now_ms() / 1000 } +/// Seconds on the clock the watch's timers run on (tokio's, `Instant`): it stops while the machine sleeps, as they do. The wall clock does not, so a +/// last good check stored as wall time looked minutes or hours old the moment a Mac woke (a DarkWake every 15 minutes or so, for 2 s, is enough for +/// the guard to ask and too short for the next check to run): every part "hung" at once, and six such wakes in a row ended a well hub. +fn mono_s() -> u64 { static T0: OnceLock = OnceLock::new(); T0.get_or_init(std::time::Instant::now).elapsed().as_secs() } /// Small files beside and renamed: the guard never reads half. A full disk loses the note, nothing else. fn put(name: &str, text: &str) { if let Some(d) = dir() { let _ = crate::ckpt::write_atomic(&d.join(name), &[text.as_bytes()]); } } @@ -113,16 +117,16 @@ pub fn step_now(name: &'static str, f: impl FnOnce() -> T) -> Option { /// Keep asking `check`, from outside what it checks. `check` should do what a real request does: take the lock, go through the task. pub fn watch(name: &'static str, check: impl Fn() -> Fut<'static, ()> + Send + Sync + 'static) { - let last = Arc::new(AtomicU64::new(now_s())); + let last = Arc::new(AtomicU64::new(mono_s())); WATCHED.lock().unwrap_or_else(|e| e.into_inner()).push((name, last.clone())); tokio::spawn(async move { loop { - if tokio::time::timeout(Duration::from_secs(WATCH_TIMEOUT_S), check()).await.is_ok() { last.store(now_s(), Relaxed); } else { eprintln!("backplane-hub: {name} did not answer in {WATCH_TIMEOUT_S} s"); } + if tokio::time::timeout(Duration::from_secs(WATCH_TIMEOUT_S), check()).await.is_ok() { last.store(mono_s(), Relaxed); } else { eprintln!("backplane-hub: {name} did not answer in {WATCH_TIMEOUT_S} s"); } tokio::time::sleep(Duration::from_secs(WATCH_EVERY_S)).await; } }); } /// What stopped answering (none: the hub is well). pub fn hung_at(rows: &[(&str, u64)], now: u64) -> Vec { rows.iter().filter(|(_, at)| now.saturating_sub(*at) > WATCH_STALE_S).map(|(n, _)| n.to_string()).collect() } -fn hung() -> Vec { let w = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); hung_at(&w.iter().map(|(n, t)| (*n, t.load(Relaxed))).collect::>(), now_s()) } +fn hung() -> Vec { let w = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); hung_at(&w.iter().map(|(n, t)| (*n, t.load(Relaxed))).collect::>(), mono_s()) } static FOLDING: AtomicU64 = AtomicU64::new(0); /// A fold of history is still running after the hub began to serve. `/healthz` says so, and the guard does not begin counting a build as proven until it is over: a crash at the end of a long fold is the start failing. From 9a4c303e166454d2840f2bf22646063903b5abf0 Mon Sep 17 00:00:00 2001 From: jlcjak <206324213+jlcjak@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:19:36 +0200 Subject: [PATCH 2/2] proc: take a child's exit by asking too, not by SIGCHLD alone (from h04x3d) h04x3d's Mac hub missed SIGCHLD: git calls never returned (design-history captures over 120 s, #1110), account checks got stuck (#1108), and the Claude usage read left a zombie every five minutes. The root cause (a signal mask inherited from the desktop app) was fixed in e16ae77c6, and their sleep fix landed in main as 47c492c98. This takes the rest of their branch as a backstop, so a missed signal can no longer hang the hub. - proc::wait: try_wait every 5 ms, backing off to 250 ms, raced with tokio's wait() (cancel-safe); whichever comes first wins. - proc::output: output() with the exit taken by proc::wait. It sets stdin to null as tokio's output() does, so a child that reads stdin cannot hold it. Every git and sh call in files/git.rs goes through it. - proc::kill_and_reap / kill_wait: a killed child is reaped in the background, never dropped to tokio's orphan queue. The account checks' closes, CLI calls, usage read and sign-in flow use them. On Linux (pidfd) and Windows the poll only adds a few cheap timer wakes while a child runs; wait() still answers first. Tested: hub tests for proc::, files::git, settings::accounts and guard:: (188 pass), including the new a_childs_exit_is_taken_without_sigchld_and_a_killed_child_is_reaped (stdin null, a running child's exit, a killed child reaped, kill_wait within its limit). Not run on a Mac. Co-Authored-By: h04x3d <33473989+h04x3d@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- native/host/src/files/git.rs | 3 +- native/host/src/proc.rs | 67 +++++++++++++++++++++++++ native/host/src/settings/accounts_io.rs | 15 +++--- 3 files changed, 76 insertions(+), 9 deletions(-) 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", "") } } }