diff --git a/native/guard/src/plan.rs b/native/guard/src/plan.rs index 564a1ebf35..0ef5b86802 100644 --- a/native/guard/src/plan.rs +++ b/native/guard/src/plan.rs @@ -148,6 +148,36 @@ pub fn holds_proof(health: &serde_json::Value) -> bool { health["folding"].as_u64().unwrap_or(0) > 0 || health["migrating"]["state"] == "running" || health["status"] == "migrating" } +/// Whether a probe proves this build started cleanly: requires a healthy (`well`) answer, not already stable, +/// no fold/migration holding proof, and `up_s >= need_s` awake seconds since ready. +pub fn proven(well: bool, body: &serde_json::Value, stable: bool, up_s: u64, need_s: u64) -> bool { + well && !stable && !holds_proof(body) && up_s >= need_s +} + +/// The machine slept since the last look: the wall clock moved this much more than the suspend-excluding awake clock. +/// 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, u64)>, woke: Option } +impl SleepClock { + pub fn new() -> SleepClock { SleepClock { last: None, woke: None } } + pub fn tick(&mut self, wall: std::time::SystemTime, awake_s: u64) -> bool { + let slept = self.last.map_or(false, |(w, a)| { + let dw = wall.duration_since(w).map_or(0, |d| d.as_secs()); + let da = awake_s.saturating_sub(a); + dw > da + SLEEP_JUMP_S + }); + self.last = Some((wall, awake_s)); + if slept { self.woke = Some(awake_s) } + slept + } + /// Whether `awake_s` is within the grace after the last wake. + pub fn waking(&self, awake_s: u64) -> bool { self.woke.map_or(false, |w| awake_s.saturating_sub(w) < WAKE_GRACE_S) } +} + #[cfg(test)] mod tests { use super::*; @@ -275,4 +305,52 @@ 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, SystemTime}; + + let mut clock = SleepClock::new(); + let mut wall = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000); + let mut awake = 100u64; + + assert!(!clock.tick(wall, awake)); + assert!(!clock.waking(awake)); + + // Normal awake advance (5s wall, 5s awake): not sleep. + wall += Duration::from_secs(5); + awake += 5; + assert!(!clock.tick(wall, awake)); + assert!(!clock.waking(awake)); + + // 17-minute lid-close sleep: wall jumps 1020s while awake clock ticks only 1s. + wall += Duration::from_secs(17 * 60); + awake += 1; + assert!(clock.tick(wall, awake)); + assert!(clock.waking(awake)); + assert!(clock.waking(awake + WAKE_GRACE_S - 1)); + assert!(!clock.waking(awake + WAKE_GRACE_S)); + + // Normal ticks right after waking stay false without clearing the grace window early. + wall += Duration::from_secs(SLEEP_JUMP_S - 5); + awake += SLEEP_JUMP_S - 5; + assert!(!clock.tick(wall, awake)); + assert!(clock.waking(awake)); + + // Backward wall-clock jump (e.g. NTP step) is not treated as sleep. + wall -= Duration::from_secs(60); + awake += 2; + assert!(!clock.tick(wall, awake)); + } + + #[test] + fn a_failed_probe_never_proves_a_build_even_past_stable() { + use serde_json::json; + assert!(!proven(false, &serde_json::Value::Null, false, 120, 60)); + assert!(!proven(false, &json!({"status": "starting"}), false, 120, 60)); + assert!(!proven(true, &json!({"status": "ok", "folding": 1}), false, 120, 60)); + assert!(!proven(true, &json!({"status": "ok", "folding": 0}), false, 59, 60)); + assert!(proven(true, &json!({"status": "ok", "folding": 0}), false, 60, 60)); + assert!(!proven(true, &json!({"status": "ok", "folding": 0}), true, 120, 60)); + } } diff --git a/native/guard/src/run.rs b/native/guard/src/run.rs index 165ad88d95..531adc06df 100644 --- a/native/guard/src/run.rs +++ b/native/guard/src/run.rs @@ -246,8 +246,14 @@ impl Guard { self.stable = false; self.hub_pid = 0; self.set("starting"); 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()); + let (t0, mut ready_at, mut misses, mut last_probe, mut last_said) = (Instant::now(), None::, 0u32, Instant::now(), String::new()); + let start_awake = sys::awake_s(); + // the start's progress on the suspend-excluding awake clock (`sys::awake_s`): both the phase file's age by the wall clock + // and Windows QPC/`Instant` count a night's sleep as a stall ("start stalled for 904 s" at the first wake after sleep, #1607 / #1497) + let (mut phase_seen, mut phase_at) = (None::, start_awake); + let mut clock = plan::SleepClock::new(); loop { + if clock.tick(std::time::SystemTime::now(), sys::awake_s()) { 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) } @@ -264,6 +270,7 @@ impl Guard { if last_probe.elapsed().as_secs() >= self.tm.probe { last_probe = Instant::now(); self.watch_space(); let (answered, well, said, control) = self.probe(); + if clock.tick(std::time::SystemTime::now(), sys::awake_s()) { misses = 0; say("the machine slept; health checks start counting again"); } if well { let down: Vec = serde_json::from_str::(&said).ok().and_then(|v| v["degraded"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())).unwrap_or_default(); // on probation, a part the build before had running and this one has not is the update failing: a start step panicked or ran out of time @@ -279,19 +286,24 @@ impl Guard { let why = self.wrong_build(&said).unwrap_or_default(); say(&format!("{} is not the build it was staged as: {why}; ending it", Self::short(&self.build))); sys::stop_child(&mut child, 10_000); self.hub_pid = 0; return End::Failed(why) } - 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 if well => { ready_at = Some(sys::awake_s()); 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()); - 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() })) } + let now_awake = sys::awake_s(); + 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 = now_awake; } + let quiet = now_awake.saturating_sub(phase_at); + if quiet >= self.tm.stall || now_awake.saturating_sub(start_awake) >= 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::())) } + let now_awake = sys::awake_s(); + if well || answered { misses = 0 } else if clock.waking(now_awake) { 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) - let busy = plan::holds_proof(&serde_json::from_str::(&said).unwrap_or(Value::Null)); - if busy { ready_at = Some(Instant::now()); } - if !busy && !self.stable && at.elapsed().as_secs() >= self.tm.stable { self.stable = true; self.d.add_good(&self.build); self.pin(); say(&format!("{} started cleanly", Self::short(&self.build))); if self.probation.take().is_some() { if let Some(b) = &self.b { b.publish(&self.build); } } self.publish(); } + let body = serde_json::from_str::(&said).unwrap_or(Value::Null); + let busy = plan::holds_proof(&body); + if busy { ready_at = Some(now_awake); } + if plan::proven(well, &body, self.stable, now_awake.saturating_sub(at), self.tm.stable) { self.stable = true; self.d.add_good(&self.build); self.pin(); say(&format!("{} started cleanly", Self::short(&self.build))); if self.probation.take().is_some() { if let Some(b) = &self.b { b.publish(&self.build); } } self.publish(); } } } } diff --git a/native/guard/src/sys.rs b/native/guard/src/sys.rs index cc8ce8e332..f1d111d8a6 100644 --- a/native/guard/src/sys.rs +++ b/native/guard/src/sys.rs @@ -33,6 +33,11 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; } pub fn detach(c: &mut std::process::Command) { use std::os::unix::process::CommandExt; unsafe { c.pre_exec(|| { libc::setsid(); Ok(()) }); } } pub fn signal_of(s: &std::process::ExitStatus) -> Option { use std::os::unix::process::ExitStatusExt; s.signal() } + /// Monotonic awake seconds since first call (pauses while macOS/Linux sleeps). + pub fn awake_s() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_secs() + } } #[cfg(windows)] mod os { pub fn watch_stop() {} @@ -41,7 +46,17 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; pub fn term(pid: u32) { let _ = quiet("taskkill").args(["/PID", &pid.to_string()]).output(); } pub fn abort(pid: u32) { let _ = quiet("taskkill").args(["/F", "/PID", &pid.to_string()]).output(); } pub fn alive(pid: u32) -> bool { quiet("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().map_or(false, |o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string())) } - #[link(name = "kernel32")] extern "system" { fn GetDiskFreeSpaceExW(dir: *const u16, free: *mut u64, total: *mut u64, all: *mut u64) -> i32; } + #[link(name = "kernel32")] extern "system" { + fn GetDiskFreeSpaceExW(dir: *const u16, free: *mut u64, total: *mut u64, all: *mut u64) -> i32; + fn QueryUnbiasedInterruptTime(unbiased_time: *mut u64) -> i32; + } + /// Monotonic awake seconds since first call (`QueryUnbiasedInterruptTime` excludes standby/hibernation). + pub fn awake_s() -> u64 { + static T0: std::sync::OnceLock<(Option, std::time::Instant)> = std::sync::OnceLock::new(); + let read = || { let mut t = 0u64; (unsafe { QueryUnbiasedInterruptTime(&mut t) } != 0).then_some(t / 10_000_000) }; + let (base, fallback) = *T0.get_or_init(|| (read(), std::time::Instant::now())); + match (base, read()) { (Some(b), Some(now)) => now.saturating_sub(b), _ => fallback.elapsed().as_secs() } + } pub fn space(p: &std::path::Path) -> Option<(u64, u64)> { use std::os::windows::ffi::OsStrExt; let w: Vec = p.as_os_str().encode_wide().chain(Some(0)).collect(); let (mut a, mut b, mut c) = (0u64, 0u64, 0u64); @@ -54,7 +69,7 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; fn quiet(name: &str) -> std::process::Command { use std::os::windows::process::CommandExt; let mut c = std::process::Command::new(name); c.creation_flags(NO_WINDOW); c } pub fn signal_of(_: &std::process::ExitStatus) -> Option { None } } -pub use os::{abort, alive, clean_signals, detach, signal_of, space, stop_asked, term, watch_stop}; +pub use os::{abort, alive, awake_s, clean_signals, detach, signal_of, space, stop_asked, term, watch_stop}; pub fn free_bytes(p: &Path) -> Option { space(p).map(|s| s.0) } /// The hub program in a build folder. diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index 0b2ea62694..490f369b76 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -632,9 +632,9 @@ async fn remake_folder(cwd: &str, root: &str) -> Result<(), String> { let p = std::path::Path::new(cwd); if cwd.is_empty() { return Err("the thread has no folder".into()) } if p.is_dir() { return Ok(()) } - if !root.is_empty() && std::path::Path::new(root).join(".git").exists() { + if !crate::copy::on() && !root.is_empty() && std::path::Path::new(root).join(".git").exists() { if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); } - let run = |args: Vec<&str>| { let mut c = tokio::process::Command::new("git"); c.arg("-C").arg(root).args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); c.status() }; + let run = |args: Vec<&str>| { let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.arg("-C").arg(root).args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); c.status() }; let _ = run(vec!["worktree", "prune"]).await; let _ = run(vec!["worktree", "add", "--detach", cwd, "HEAD"]).await; } diff --git a/native/host/src/agents/proc.rs b/native/host/src/agents/proc.rs index 11fa3e8e5d..fdcae9de36 100644 --- a/native/host/src/agents/proc.rs +++ b/native/host/src/agents/proc.rs @@ -375,7 +375,20 @@ mod reaper { #[cfg(test)] c.args(["agents::tests::reaper_child", "--exact", "--nocapture", "--test-threads=1"]).env("BP_REAPER_CHILD", "1"); // a test binary takes no such flag: its watcher is a test that only runs as that child c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); crate::plat::proc::own_group(&mut c); - match c.spawn() { Ok(mut ch) => { *g = ch.stdin.take(); std::thread::spawn(move || { let _ = ch.wait(); }); } Err(_) => return false } + struct Reap(Option); + impl Drop for Reap { fn drop(&mut self) { if let Some(mut c) = self.0.take() { let _ = c.kill(); let _ = c.wait(); } } } + match c.spawn() { + Ok(mut ch) => { + let stdin = ch.stdin.take(); + let mut guard = Reap(Some(ch)); + if std::thread::Builder::new().name("agent-reaper-wait".into()).spawn(move || { if let Some(mut c) = guard.0.take() { let _ = c.wait(); } }).is_ok() { + *g = stdin; + } else { + return false; + } + } + Err(_) => return false, + } } let ok = g.as_mut().map_or(false, |w| w.write_all(line.as_bytes()).and_then(|_| w.flush()).is_ok()); if !ok { *g = None } diff --git a/native/host/src/commands/clone/mod.rs b/native/host/src/commands/clone/mod.rs index 4ad25540b9..a745a7142b 100644 --- a/native/host/src/commands/clone/mod.rs +++ b/native/host/src/commands/clone/mod.rs @@ -510,7 +510,7 @@ fn uses_lfs(dest: &Path) -> bool { std::fs::read_to_string(dest.join(".gitattributes")).map_or(false, |t| t.contains("filter=lfs")) || dest.join(".lfsconfig").is_file() } async fn lfs_installed() -> bool { - let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.args(["lfs", "version"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.args(["lfs", "version"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true); matches!(tokio::time::timeout(std::time::Duration::from_secs(10), c.status()).await, Ok(Ok(s)) if s.success()) } diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index 377bd2b32b..d1c798c1f3 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -849,8 +849,8 @@ mod pick_tests { } #[test] fn browser_plan_path_is_confined_to_authorized_projects() { - let base = std::env::temp_dir().join(format!("bp-ext-plan-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); + let base_guard = crate::plat::tmp::dir("ext-plan"); + let base = base_guard.path(); let home = base.join("home"); let proj = base.join("proj"); let outside = base.join("outside"); @@ -891,6 +891,5 @@ mod pick_tests { std::os::unix::fs::symlink(&outside_plan, &sub_sidecar).unwrap(); assert!(check_browser_plan_path(&roots, &home, sub_pro.to_str().unwrap()).is_err()); } - let _ = std::fs::remove_dir_all(&base); } } diff --git a/native/host/src/guard.rs b/native/host/src/guard.rs index f81d63452b..f01bcc3275 100644 --- a/native/host/src/guard.rs +++ b/native/host/src/guard.rs @@ -37,6 +37,9 @@ 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 machine's suspend-excluding awake clock (pauses while macOS/Linux/Windows sleeps). +/// Wall time (and `Instant` on Windows) advances through sleep, so wall-clock timestamps marked `writer`/`model`/`agents` hung on wake (#1607, #1497). +fn mono_s() -> u64 { crate::plat::hub::awake_s() } /// 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 +116,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. @@ -319,6 +322,20 @@ mod tests { #[test] fn a_stale_check_names_what_stopped() { assert!(hung_at(&[("writer", 1000), ("model", 950)], 1000).is_empty()); assert_eq!(hung_at(&[("writer", 1000), ("agents", 800)], 1000), vec!["agents"]); + assert!(hung_at(&[("writer", 1000)], 1000 + WATCH_STALE_S).is_empty()); + assert_eq!(hung_at(&[("writer", 1000)], 1000 + WATCH_STALE_S + 1), vec!["writer"]); + } + #[tokio::test] async fn watch_timestamps_use_monotonic_clock_not_wall_epoch() { + assert!(mono_s() < 86_400, "mono_s must stay relative to awake runtime, not Unix epoch time"); + watch("test-mono-clock", || Box::pin(async {})); + tokio::task::yield_now().await; + let ts = WATCHED.lock().unwrap_or_else(|e| e.into_inner()).iter() + .find(|(n, _)| *n == "test-mono-clock") + .map(|(_, t)| t.load(Relaxed)) + .expect("watch registered entry"); + assert!(ts < 86_400 && ts <= mono_s(), "stored watch timestamp {ts} must use mono_s"); + assert!(!hung().iter().any(|n| n == "test-mono-clock")); + WATCHED.lock().unwrap_or_else(|e| e.into_inner()).retain(|(n, _)| *n != "test-mono-clock"); } #[tokio::test] async fn a_step_that_panics_or_hangs_costs_only_itself() { assert_eq!(step("ok", 5, async { 7 }).await, Some(7)); diff --git a/native/host/src/net/botnet.rs b/native/host/src/net/botnet.rs index 8b34e8ded6..5ff26a0683 100644 --- a/native/host/src/net/botnet.rs +++ b/native/host/src/net/botnet.rs @@ -3,7 +3,7 @@ //! argv or a log), and verifying signed requests in. Nothing here talks to the hub. use super::sign; use std::{path::{Path, PathBuf}, process::Stdio}; -use tokio::{io::AsyncWriteExt, process::Command}; +use tokio::io::AsyncWriteExt; /// A reply from a peer: curl printed the body, then a line with the status code. Code 0: no request was made. pub struct Resp { pub code: u16, pub body: String } @@ -127,21 +127,24 @@ pub fn choose_url(env: &str, tailnet: bool, dns: &str, serve: &str, host: &str, pub(crate) async fn served_url(port: u16) -> String { static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); if let Some((t, p, u)) = LAST.lock().unwrap().clone() { if p == port && t.elapsed() < std::time::Duration::from_secs(30) { return u } } - let out = tokio::time::timeout(std::time::Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["serve", "status", "--json"]).stderr(Stdio::null()).output()).await; + let out = tokio::time::timeout(std::time::Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["serve", "status", "--json"]).stderr(Stdio::null()).kill_on_drop(true).output()).await; let u = match out { Ok(Ok(o)) if o.status.success() => super::tailnet::serve(&String::from_utf8_lossy(&o.stdout), &port.to_string()), _ => String::new() }; *LAST.lock().unwrap() = Some((std::time::Instant::now(), port, u.clone())); u } /// Self.DNSName of `tailscale status --json`, without the trailing dot; "" when there is none. pub async fn tailscale_dns() -> String { - let Ok(o) = tokio::time::timeout(std::time::Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["status", "--json"]).stderr(Stdio::null()).output()).await else { return String::new() }; + let Ok(o) = tokio::time::timeout(std::time::Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["status", "--json"]).stderr(Stdio::null()).kill_on_drop(true).output()).await else { return String::new() }; let Ok(o) = o else { return String::new() }; serde_json::from_slice::(&o.stdout).ok().and_then(|j| j["Self"]["DNSName"].as_str().map(|s| s.trim_end_matches('.').to_string())).unwrap_or_default() } -/// This machine's name for others: BACKPLANE_NAME, else its host name. +fn name_with(env: Option<&str>, host: impl FnOnce() -> String) -> String { + if let Some(e) = env.map(str::trim).filter(|e| !e.is_empty()) { return clean(e) } + clean(&host()) +} +/// This machine's name for others: BACKPLANE_NAME, else its host name (read in-process, never spawning `hostname`: +/// `GET /` and `GET /pair` call this on every request, #1607). pub async fn name() -> String { - if let Ok(e) = std::env::var("BACKPLANE_NAME") { if !e.trim().is_empty() { return clean(e.trim()) } } - let h = crate::proc::tokio_cmd(crate::proc::Kind::Local, "hostname").stderr(Stdio::null()).output().await.ok().map(|o| String::from_utf8_lossy(&o.stdout).lines().next().unwrap_or("").trim().to_string()).unwrap_or_default(); - clean(&h) + name_with(std::env::var("BACKPLANE_NAME").ok().as_deref(), crate::plat::hub::hostname) } /// An unsigned POST with no body (tests: a route that must refuse it). @@ -206,4 +209,11 @@ mod tests { let r = parse_resp(b"line1\nline2\n403"); assert_eq!((r.code, r.body.as_str()), (403, "line1\nline2")); assert_eq!(parse_resp(b"").code, 0); } + #[tokio::test] async fn botnet_name_reads_hostname_in_process_and_honors_env_override() { + assert_eq!(name_with(Some(" Desk 1 "), || panic!("must not read hostname when BACKPLANE_NAME is set")), "Desk1"); + assert_eq!(name_with(Some(" "), || "my-host.local".into()), "my-host.local"); + let h = crate::plat::hub::hostname(); + assert!(!h.is_empty(), "in-process hostname is populated"); + assert_eq!(name().await, name_with(std::env::var("BACKPLANE_NAME").ok().as_deref(), crate::plat::hub::hostname)); + } } diff --git a/native/host/src/net/listener.rs b/native/host/src/net/listener.rs index 5b30ed7df8..dc77614988 100644 --- a/native/host/src/net/listener.rs +++ b/native/host/src/net/listener.rs @@ -38,12 +38,12 @@ pub trait Tailscale: Send + Sync { pub struct Cli; async fn run(args: Vec) -> String { if crate::copy::on() { return String::new() } - match tokio::time::timeout(Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stderr(std::process::Stdio::null()).output()).await { + match tokio::time::timeout(Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(), _ => String::new() } } async fn run_ok(args: Vec) -> bool { if crate::copy::on() { return false } - matches!(tokio::time::timeout(Duration::from_secs(15), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status()).await, Ok(Ok(s)) if s.success()) + matches!(tokio::time::timeout(Duration::from_secs(15), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true).status()).await, Ok(Ok(s)) if s.success()) } impl Tailscale for Cli { fn serve(&self, port: u16, https: u16) -> Fut { Box::pin(async move { run_ok(vec!["serve".into(), "--bg".into(), format!("--https={https}"), format!("http://127.0.0.1:{port}")]).await }) } diff --git a/native/host/src/net/tailnet.rs b/native/host/src/net/tailnet.rs index 8e8f730f11..6b358f4fed 100644 --- a/native/host/src/net/tailnet.rs +++ b/native/host/src/net/tailnet.rs @@ -119,9 +119,8 @@ pub async fn find(status: &str, port: u16, extra: &str) -> Value { machines_json(status, port, &found) } pub async fn status_json() -> String { - use tokio::process::Command; if crate::copy::on() { return String::new() } - match tokio::time::timeout(std::time::Duration::from_secs(10), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["status", "--json"]).stderr(std::process::Stdio::null()).output()).await { + match tokio::time::timeout(std::time::Duration::from_secs(10), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["status", "--json"]).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(), _ => String::new() } } diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index 28e3fb7396..75c211ecbd 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -972,9 +972,8 @@ mod tests { } #[test] fn saved_plan_update_checks_base_revision_and_unique_note_ids() { - let dir = std::env::temp_dir().join(format!("bp-plan-mod-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir_guard = crate::plat::tmp::dir("plan-mod"); + let dir = dir_guard.path(); let pcb = dir.join("demo.kicad_pcb"); let plan_f = dir.join("demo.kicad_plan"); std::fs::write(&pcb, "").unwrap(); @@ -1005,7 +1004,6 @@ mod tests { assert_eq!(disk_after["revision"], 6); assert_eq!(disk_after["notes"].as_array().unwrap().len(), 2); assert_eq!(disk_after["notes"][0]["target"], "c1"); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn live_merge_preserved_holes_keeps_authoritative_holes_and_allows_explicit_clear() { diff --git a/native/host/src/plat/unix.rs b/native/host/src/plat/unix.rs index d1d3224dd1..1970bd5f7b 100644 --- a/native/host/src/plat/unix.rs +++ b/native/host/src/plat/unix.rs @@ -212,6 +212,18 @@ pub mod hub { pub fn program(p: &std::ffi::OsStr) -> std::ffi::OsString { p.to_os_string() } /// What to start for `p` and the arguments before the caller's: the program itself (the kernel reads `#!`). pub fn launch(p: &std::ffi::OsStr) -> (std::ffi::OsString, Vec) { (p.to_os_string(), vec![]) } + /// This machine's host name via `gethostname(2)`: no child process, no PATH lookup, no SIGCHLD wait (#1607). + pub fn hostname() -> String { + let mut buf = [0u8; 256]; + if unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) } != 0 { return String::new() } + let n = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); + String::from_utf8_lossy(&buf[..n]).trim().to_string() + } + /// Monotonic awake seconds since first call (pauses while macOS/Linux sleeps, matching tokio timers). + pub fn awake_s() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_secs() + } } pub mod time { diff --git a/native/host/src/plat/windows.rs b/native/host/src/plat/windows.rs index 6a47c0a48c..9afc618612 100644 --- a/native/host/src/plat/windows.rs +++ b/native/host/src/plat/windows.rs @@ -323,6 +323,31 @@ pub mod hub { pub fn reset_inherited_signals() -> Option { None } /// Windows waits on process handles, never on a signal: nothing to watch. pub fn watch_reaping(_every: std::time::Duration) {} + /// This machine's host name via `GetComputerNameExW(ComputerNameDnsHostname)` (falling back to `COMPUTERNAME`): no child process (#1607). + pub fn hostname() -> String { + use windows_sys::Win32::System::SystemInformation::{ComputerNameDnsHostname, GetComputerNameExW}; + let mut n: u32 = 256; + let mut buf = vec![0u16; n as usize]; + let ok = unsafe { GetComputerNameExW(ComputerNameDnsHostname, buf.as_mut_ptr(), &mut n) } != 0; + if ok && n > 0 { + return String::from_utf16_lossy(&buf[..(n as usize).min(buf.len())]).trim().to_string() + } + if !ok && n > buf.len() as u32 { + let mut buf = vec![0u16; n as usize]; + if unsafe { GetComputerNameExW(ComputerNameDnsHostname, buf.as_mut_ptr(), &mut n) } != 0 && n > 0 { + return String::from_utf16_lossy(&buf[..(n as usize).min(buf.len())]).trim().to_string() + } + } + std::env::var("COMPUTERNAME").unwrap_or_default().trim().to_string() + } + /// Monotonic awake seconds since first call (`QueryUnbiasedInterruptTime` excludes standby/hibernation, unlike `Instant`/QPC). + pub fn awake_s() -> u64 { + #[link(name = "kernel32")] extern "system" { fn QueryUnbiasedInterruptTime(unbiased_time: *mut u64) -> i32; } + static T0: std::sync::OnceLock<(Option, std::time::Instant)> = std::sync::OnceLock::new(); + let read = || { let mut t = 0u64; (unsafe { QueryUnbiasedInterruptTime(&mut t) } != 0).then_some(t / 10_000_000) }; + let (base, fallback) = *T0.get_or_init(|| (read(), std::time::Instant::now())); + match (base, read()) { (Some(b), Some(now)) => now.saturating_sub(b), _ => fallback.elapsed().as_secs() } + } /// Ctrl+C or Ctrl+Break, the console closing, logoff or shutdown end the hub, said in hub.log, exit 130 (as SIGINT). pub fn exit_on_signals(on_exit: fn()) { tokio::spawn(async move { if tokio::signal::ctrl_c().await.is_ok() { on_exit(); eprintln!("backplane-hub: Ctrl+C received, exiting"); std::process::exit(130) } }); diff --git a/native/host/src/proc.rs b/native/host/src/proc.rs index 0237b75eca..9fc9fec8f1 100644 --- a/native/host/src/proc.rs +++ b/native/host/src/proc.rs @@ -441,6 +441,94 @@ mod tests { assert!(out.matches("chld=DFL").count() == 2 && out.matches("blocked=0 waited=true").count() == 2, "std and tokio children: {out}"); } + /// Non-test source lines up to the first inline `#[cfg(test)] mod {` module (forward declarations such as `#[cfg(test)] mod tests;` stay). + fn non_test_code(text: &str) -> String { + fn is_cfg_test(t: &str) -> bool { + let Some(rest) = t.strip_prefix("#[cfg(") else { return false }; + let Some((args, _)) = rest.split_once(")]") else { return false }; + // Strip balanced `not(...)` clauses so `#[cfg(not(test))]` and `#[cfg(all(not(test), unix))]` stay production code. + let mut filtered = String::with_capacity(args.len()); + let b = args.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i..].starts_with(b"not(") { + let mut depth = 1usize; + let mut j = i + 4; + while j < b.len() && depth > 0 { + if b[j] == b'(' { depth += 1; } else if b[j] == b')' { depth -= 1; } + j += 1; + } + i = j; + } else { + let ch = args[i..].chars().next().unwrap(); + filtered.push(ch); + i += ch.len_utf8(); + } + } + filtered.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').any(|w| w == "test") + } + fn starts_mod(rest: &str) -> Option<&str> { + let mut item = rest.trim_start(); + while item.starts_with("#[") { + let Some((_, after)) = item.split_once(']') else { return None }; + item = after.trim_start(); + } + let s = item.strip_prefix("pub").map(|r| { + let r = r.trim_start(); + if r.starts_with('(') { r.split_once(')').map_or(r, |x| x.1).trim_start() } else { r } + }).unwrap_or(item).trim_start(); + s.strip_prefix("mod ") + } + fn inline_mod_at(lines: &[&str], idx: usize, same_line: &str) -> bool { + let first = if same_line.is_empty() { + let mut k = idx + 1; + while k < lines.len() { + let s = lines[k].trim(); + if s.is_empty() || s.starts_with("//") || s.starts_with("#[") { k += 1; } else { break; } + } + if k >= lines.len() { return false } + (k, lines[k].trim()) + } else { + (idx, same_line) + }; + let Some(after) = starts_mod(first.1) else { return false }; + if let Some((name, _)) = after.split_once('{') { + return !name.contains(';') && !name.trim().is_empty(); + } + if after.contains(';') { return false } + let mut k = first.0 + 1; + while k < lines.len() { + let s = lines[k].trim(); + if s.is_empty() || s.starts_with("//") { k += 1; continue } + return s.starts_with('{'); + } + false + } + let lines: Vec<&str> = text.lines().collect(); + let mut out = String::new(); + for (i, &l) in lines.iter().enumerate() { + let t = l.trim(); + if is_cfg_test(t) { + if let Some((_, after)) = l.split_once(")]") { + if inline_mod_at(&lines, i, after.trim()) { break } + } + } + out.push_str(l); + out.push('\n'); + } + out + } + + #[test] fn non_test_code_keeps_code_after_forward_test_mod_declarations() { + let s = "fn a() {}\n#[cfg(test)] mod tests;\n#[cfg(test)] mod laws;\n#[cfg(not(test))] mod prod { Command::new(\"git\"); }\n#[cfg(all(not(test), unix))] mod prod2 { Command::new(\"sh\"); }\nfn b() { Command::new(\"git\"); }\n#[cfg(test)]\n#[allow(dead_code)]\nmod inline_tests\n{\n fn t() { Command::new(\"x\"); }\n}\n"; + let got = non_test_code(s); + assert!(got.contains("fn b()"), "must keep code after `#[cfg(test)] mod tests;`: {got}"); + assert!(got.contains("mod prod"), "must keep #[cfg(not(test))] production module: {got}"); + assert!(got.contains("mod prod2"), "must keep #[cfg(all(not(test), unix))] production module: {got}"); + assert!(!got.contains("inline_tests"), "must stop at inline test module with intervening attrs / next-line brace: {got}"); + assert!(non_test_code("#[cfg(test)] pub(crate) mod t { fn x() {} }\n").is_empty()); + } + /// The gate is the only way to make a process: no other non-test `Command::new` anywhere under src/ (src/bin has its own crates' helpers). #[test] fn every_child_process_is_made_through_proc() { fn walk(d: &std::path::Path, out: &mut Vec) { for e in std::fs::read_dir(d).unwrap().flatten() { let p = e.path(); if p.is_dir() { if p.file_name().map_or(false, |n| n == "bin") { continue } walk(&p, out) } else if p.extension().map_or(false, |x| x == "rs") { out.push(p) } } } @@ -450,9 +538,8 @@ mod tests { if f.ends_with("proc.rs") { continue } let text = std::fs::read_to_string(&f).unwrap(); let name = f.to_string_lossy().replace('\\', "/"); - if name.ends_with("tests.rs") || name.contains("/tests/") { continue } - // everything after the first #[cfg(test)] line is test code - let code = text.split("\n#[cfg(test)]").next().unwrap_or(&text); + if name.ends_with("tests.rs") || name.ends_with("copy_gate.rs") || name.ends_with("copy_outs.rs") || name.contains("/tests/") { continue } + let code = non_test_code(&text); for (i, l) in code.lines().enumerate() { if l.contains("Command::new(") && !l.trim_start().starts_with("//") { bad.push(format!("{}:{}", name, i + 1)) } } } assert!(bad.is_empty(), "build children with crate::proc::{{tokio_cmd, std_cmd}}: {bad:?}"); @@ -472,9 +559,9 @@ mod tests { let mut bad = vec![]; for f in files { let name = f.to_string_lossy().replace('\\', "/"); - if name.ends_with("tests.rs") || name.ends_with("e2e.rs") || name.contains("/tests/") || ALLOWED.iter().any(|a| name.ends_with(a)) { continue } + if name.ends_with("tests.rs") || name.ends_with("e2e.rs") || name.ends_with("copy_gate.rs") || name.ends_with("copy_outs.rs") || name.contains("/tests/") || ALLOWED.iter().any(|a| name.ends_with(a)) { continue } let text = std::fs::read_to_string(&f).unwrap(); - let code = text.split("\n#[cfg(test)]").next().unwrap_or(&text); + let code = non_test_code(&text); for (i, l) in code.lines().enumerate() { let l = l.trim_start(); if l.starts_with("//") { continue } if ["TcpStream::connect", "UdpSocket", "TcpSocket", "connect_async", "UnixStream::connect"].iter().any(|k| l.contains(k)) { bad.push(format!("{name}:{}", i + 1)) } diff --git a/native/host/src/push/apns.rs b/native/host/src/push/apns.rs index 8331bfdf83..9f4c4f2801 100644 --- a/native/host/src/push/apns.rs +++ b/native/host/src/push/apns.rs @@ -46,16 +46,22 @@ pub fn raw_sig(der: &[u8]) -> Option<[u8; 64]> { } Some(out) } +/// Write `input` to `c`'s stdin and wait for stdout; kill and reap on write failure so no `` child leaks (#1607). +fn pipe_and_wait(c: &mut std::process::Command, input: &[u8], missing: &str, fail: &str) -> Result, String> { + let mut ch = c.spawn().map_err(|_| missing.to_string())?; + let wrote = ch.stdin.take().ok_or_else(|| "no stdin".to_string()).and_then(|mut s| s.write_all(input).map_err(|e| e.to_string())); + if let Err(e) = wrote { let _ = ch.kill(); let _ = ch.wait(); return Err(e) } + let o = ch.wait_with_output().map_err(|e| e.to_string())?; + if !o.status.success() { return Err(fail.into()) } + Ok(o.stdout) +} /// The provider token. pub fn token(key: &Path, kid: &str, team: &str, now: u64) -> Result { let msg = format!("{}.{}", b64(json!({"alg":"ES256","kid":kid}).to_string().as_bytes()), b64(json!({"iss":team,"iat":now}).to_string().as_bytes())); let mut c = crate::proc::std_cmd(crate::proc::Kind::Local, "openssl"); c.args(["dgst", "-sha256", "-sign"]).arg(key).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()); - let mut ch = c.spawn().map_err(|_| "openssl is missing".to_string())?; - ch.stdin.take().ok_or("no stdin")?.write_all(msg.as_bytes()).map_err(|e| e.to_string())?; - let o = ch.wait_with_output().map_err(|e| e.to_string())?; - if !o.status.success() { return Err("could not sign with push.apns.key".into()) } - Ok(format!("{msg}.{}", b64(&raw_sig(&o.stdout).ok_or("the signature did not parse")?))) + let sig = pipe_and_wait(&mut c, msg.as_bytes(), "openssl is missing", "could not sign with push.apns.key")?; + Ok(format!("{msg}.{}", b64(&raw_sig(&sig).ok_or("the signature did not parse")?))) } pub fn curl_config(url: &str, jwt: &str, topic: &str, f: &Frame, body: &Path, out: &Path) -> String { let mut c = format!("url = \"{url}\"\nheader = \"authorization: bearer {jwt}\"\nheader = \"apns-topic: {topic}\"\nheader = \"apns-push-type: {}\"\nheader = \"apns-priority: {}\"\n", f.push_type, f.priority); @@ -167,3 +173,34 @@ pub fn undelivered_tell(why: &str) -> String { let fix = if why.starts_with("the APNs key file") { " Apple lets you download a key only once, so make a new APNs key at developer.apple.com (Certificates, IDs & Profiles, Keys), then ask me to point push.apns.key and push.apns.keyid at the new .p8. No restart needed." } else { "" }; format!("**Phone alerts aren't reaching your phone:** {why}. Replies still show here and in the app while it is open, but nothing pops up on the phone until this is fixed.{fix}") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn failed_pipe_reaps_child_and_missing_key_errors() { + assert!(token(Path::new("/nonexistent/key.p8"), "kid", "team", 1).is_err()); + + #[cfg(unix)] + { + let tmp = crate::plat::tmp::dir("apns-reap"); + let pid_file = tmp.path().join("pid"); + let mut cmd = crate::proc::std_cmd(crate::proc::Kind::Local, "/bin/sh"); + cmd.args([ + "-c", + "echo $$ > \"$1\" && exec 0<&- && exit 1", + "sh", + pid_file.to_str().unwrap(), + ]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + let big = vec![b'x'; 256 * 1024]; + let err = pipe_and_wait(&mut cmd, &big, "missing stdin", "failed").unwrap_err(); + assert_ne!(err, "failed", "expected stdin write error before exit status"); + let pid: u32 = std::fs::read_to_string(&pid_file).unwrap().trim().parse().unwrap(); + assert!(!crate::plat::proc::alive(pid), "failed write child {pid} stayed unreaped"); + } + } +} diff --git a/native/host/src/settings/accounts_io.rs b/native/host/src/settings/accounts_io.rs index d3ae6b3be0..3e88bd41b1 100644 --- a/native/host/src/settings/accounts_io.rs +++ b/native/host/src/settings/accounts_io.rs @@ -513,7 +513,7 @@ impl Accounts { 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)) }).await; - let code = match ran { Ok(Ok(code)) => code, _ => { let _ = child.start_kill(); return Err(()) } }; + 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 data = if args.get(1) == Some(&"logout") { json!({}) } else { serde_json::from_slice(&buf).map_err(|_| ())? }; Ok((code, data)) } @@ -528,27 +528,31 @@ impl Accounts { c.current_dir(&self.root); apply_env(&mut c, &self.environment(p).map_err(|_| "This account's private folder could not be verified.".to_string())?, p.is_some()); c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).kill_on_drop(true); let mut child = spawn(&mut c).await.map_err(|_| "The Claude CLI could not be started.".to_string())?; - let (mut stdin, stdout) = (child.stdin.take().ok_or("The Claude CLI could not be started.")?, child.stdout.take().ok_or("The Claude CLI could not be started.")?); - let first = json!({"type":"control_request","request_id":if want == "models" { "models" } else { "init" },"request":{"subtype":"initialize"}}).to_string(); - stdin.write_all(format!("{first}\n").as_bytes()).await.map_err(|_| "The Claude CLI closed before answering.".to_string())?; - let r = tokio::time::timeout(Duration::from_secs(30), async { - let mut lines = BufReader::new(stdout).lines(); let mut total = 0usize; - while let Ok(Some(l)) = lines.next_line().await { - total += l.len(); if total > 524288 { return Err("The Claude CLI's reply was too large.".to_string()) } - let Ok(r) = serde_json::from_str::(&l) else { continue }; - if r["type"] != "control_response" { continue } - let bad = r["response"]["subtype"] == "error"; - let why = || format!("Claude refused the request: {}", label(r["response"]["error"].as_str().unwrap_or("no reason given"))); - match (want, r["response"]["request_id"].as_str()) { - ("models", Some("models")) => return if bad { Err(why()) } else { Ok(r["response"]["response"].clone()) }, - ("usage", Some("init")) => { if bad { return Err(why()) } let q = json!({"type":"control_request","request_id":"usage","request":{"subtype":"get_usage","skip_behaviors":true}}).to_string(); stdin.write_all(format!("{q}\n").as_bytes()).await.map_err(|_| "The Claude CLI closed before answering.".to_string())?; } - ("usage", Some("usage")) => return if bad { Err(why()) } else { Ok(r["response"]["response"].clone()) }, - _ => {} + let r = async { + let (mut stdin, stdout) = (child.stdin.take().ok_or_else(|| "The Claude CLI could not be started.".to_string())?, child.stdout.take().ok_or_else(|| "The Claude CLI could not be started.".to_string())?); + let first = json!({"type":"control_request","request_id":if want == "models" { "models" } else { "init" },"request":{"subtype":"initialize"}}).to_string(); + stdin.write_all(format!("{first}\n").as_bytes()).await.map_err(|_| "The Claude CLI closed before answering.".to_string())?; + tokio::time::timeout(Duration::from_secs(30), async { + let mut lines = BufReader::new(stdout).lines(); let mut total = 0usize; + while let Ok(Some(l)) = lines.next_line().await { + total += l.len(); if total > 524288 { return Err("The Claude CLI's reply was too large.".to_string()) } + let Ok(r) = serde_json::from_str::(&l) else { continue }; + if r["type"] != "control_response" { continue } + let bad = r["response"]["subtype"] == "error"; + let why = || format!("Claude refused the request: {}", label(r["response"]["error"].as_str().unwrap_or("no reason given"))); + match (want, r["response"]["request_id"].as_str()) { + ("models", Some("models")) => return if bad { Err(why()) } else { Ok(r["response"]["response"].clone()) }, + ("usage", Some("init")) => { if bad { return Err(why()) } let q = json!({"type":"control_request","request_id":"usage","request":{"subtype":"get_usage","skip_behaviors":true}}).to_string(); stdin.write_all(format!("{q}\n").as_bytes()).await.map_err(|_| "The Claude CLI closed before answering.".to_string())?; } + ("usage", Some("usage")) => return if bad { Err(why()) } else { Ok(r["response"]["response"].clone()) }, + _ => {} + } } - } - 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())); - let _ = child.start_kill(); r + 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; + r } /// A test's usage request and CLI store (the real hub's are set in `open`). #[cfg(test)] diff --git a/native/host/src/settings/tools_install.rs b/native/host/src/settings/tools_install.rs index 19783c627a..d732af1341 100644 --- a/native/host/src/settings/tools_install.rs +++ b/native/host/src/settings/tools_install.rs @@ -117,7 +117,7 @@ async fn machine_git() -> Option { async fn elevated() -> bool { if !cfg!(windows) { return false } let Some(f) = std::env::var_os("SystemRoot").map(|r| Path::new(&r).join("System32").join("fltmc.exe")) else { return false }; - let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, f); c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, f); c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true); matches!(tokio::time::timeout(std::time::Duration::from_secs(20), c.status()).await, Ok(Ok(s)) if s.success()) } /// Git for Windows' command line from an elevated hub: its switches less `/CURRENTUSER` and no `/DIR`, so the all-users install it makes stays in Program Files. @@ -128,7 +128,7 @@ async fn registered_in(hive: &str, p: &WinInstaller) -> Option { if !cfg!(windows) { return None } let reg = std::env::var_os("SystemRoot").map(|r| Path::new(&r).join("System32").join("reg.exe"))?; let key = if hive.contains('\\') { format!("{hive}\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{}", uninstall_key(p)) } else { format!("{hive}\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{}", uninstall_key(p)) }; - let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, reg); c.args(["query", &key, "/v", "UninstallString"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, reg); c.args(["query", &key, "/v", "UninstallString"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true); let o = tokio::time::timeout(std::time::Duration::from_secs(20), c.output()).await.ok()?.ok()?; registered_dir(&String::from_utf8_lossy(&o.stdout)) } diff --git a/native/host/src/wire/tests.rs b/native/host/src/wire/tests.rs index f3f1b33a24..c2eb7b8783 100644 --- a/native/host/src/wire/tests.rs +++ b/native/host/src/wire/tests.rs @@ -231,3 +231,23 @@ fn sbs_wire_child(mode: &str, copy: Option<&str>, flag: Option<&str>) -> String assert!(!p.contains("token"), "no secret words on the page"); assert!(landing_page("", "1").contains("this machine")); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn landing_page_answers_burst_of_get_root_probes_fast() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (_hub, port) = test_hub("wire-landing", FIXTURE).await; + let probes = futures_util::future::join_all((0..20).map(|i| async move { + let path = if i % 2 == 0 { "/" } else { "/pair" }; + let resp = tokio::time::timeout(Duration::from_secs(2), async { + let mut s = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + s.write_all(format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap(); + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await.unwrap(); + String::from_utf8_lossy(&buf).into_owned() + }).await.expect("landing page answered within 2 s"); + (i, path, resp) + })).await; + for (i, path, resp) in probes { + assert!(resp.starts_with("HTTP/1.1 200 OK\r\n") && resp.contains("This is Backplane on"), "probe {i} ({path}): {resp}"); + } +} diff --git a/native/host/tests/inherited_signals.rs b/native/host/tests/inherited_signals.rs index ba81439fc6..b21ca72ba5 100644 --- a/native/host/tests/inherited_signals.rs +++ b/native/host/tests/inherited_signals.rs @@ -85,6 +85,22 @@ fn a_project_turn_reaches_its_agent(start: Start) { wait_for(40, "the agent gets the turn (the snapshot's git exits seen)", &log, || std::fs::read_to_string(&agent_log).unwrap_or_default().contains("TURN").then_some(())); assert!(proj.join(".git").exists(), "the project folder is a repository"); assert!(hub.try_wait().unwrap().is_none(), "the hub still runs"); + // #1607: landing-page probes and /healthz answer fast while a turn is running, without creating zombie children + let http_get = |path: String| { + let mut s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + use std::io::{Read, Write}; + s.write_all(format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + let mut out = String::new(); + s.read_to_string(&mut out).unwrap(); + out + }; + for i in 0..5 { + let resp = http_get("/".into()); + assert!(resp.starts_with("HTTP/1.1 200 OK\r\n") && resp.contains("This is Backplane on"), "GET / probe {i}: {resp}"); + } + let hz = http_get("/healthz".into()); + assert!(hz.starts_with("HTTP/1.1 200 OK\r\n"), "GET /healthz: {hz}"); // a child that exits is reaped at once, or by the hub's reaping watch within its 2 s look: none stays a zombie across 5 s let first = zombies(pid); std::thread::sleep(Duration::from_secs(5)); let left: Vec = zombies(pid).into_iter().filter(|z| first.contains(z)).collect();