diff --git a/native/host/src/agents/kicadsel.rs b/native/host/src/agents/kicadsel.rs index c06441e5f9..4ebdb00c93 100644 --- a/native/host/src/agents/kicadsel.rs +++ b/native/host/src/agents/kicadsel.rs @@ -65,16 +65,10 @@ pub fn kicad_of(env: &Env, version_of: impl FnOnce(&str) -> Option) -> K } } -/// `--version` of a CLI, remembered per path and modification time (a stock KiCad is asked once, not every turn). +/// `--version` of a CLI, resolved via the shared single-flight cache in `ipc::cli_version_output`. pub fn version_of(cli: &str) -> Option { - use std::{collections::HashMap, sync::{Mutex, OnceLock}}; - static SEEN: OnceLock, Option)>>> = OnceLock::new(); - let at = std::fs::metadata(cli).and_then(|m| m.modified()).ok(); - if let Some((t, v)) = SEEN.get_or_init(Default::default).lock().unwrap().get(cli).cloned() { if t == at { return v } } - let out = crate::files::kicad::ipc::cli_version_output(cli); - let v = out.filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()); - SEEN.get_or_init(Default::default).lock().unwrap().insert(cli.into(), (at, v.clone())); - v + let out = crate::files::kicad::ipc::cli_version_output(cli)?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()) } /// One shim's text: exec the selected program with the agent's arguments. diff --git a/native/host/src/kicad/checkrun.rs b/native/host/src/kicad/checkrun.rs index 11ff01366c..246fe8a648 100644 --- a/native/host/src/kicad/checkrun.rs +++ b/native/host/src/kicad/checkrun.rs @@ -723,22 +723,64 @@ fn low_priority(argv: &[String]) -> tokio::process::Command { /// never used for this: design files leave the person's machines only where they say so. #[derive(Clone, Debug, PartialEq)] pub struct Remote { pub host: String, pub cli: String } -/// (setting, local version) -> the probe's answer, so a host is asked once -static PROBED: Mutex)>> = Mutex::new(None); +fn remote_version_probe_script(cands: &str, timeout_secs: u64) -> String { + format!( + "t=$(mktemp -d) || exit 1; trap 'rm -rf \"$t\"' EXIT; trap 'rm -rf \"$t\"; exit 129' HUP; trap 'rm -rf \"$t\"; exit 130' INT; trap 'rm -rf \"$t\"; exit 143' TERM; \ + for s in 10.99:7 10.0:6 9.0:3 8.0:3; do d=${{s%:*}}; sv=${{s#*:}}; mkdir -p \"$t/$d\"; printf '{{\"api\":{{\"enable_server\":false,\"interpreter_path\":\"/nonexistent/bp-probe-python\"}},\"meta\":{{\"filename\":\"kicad_common.json\",\"version\":%s}}}}' \"$sv\" > \"$t/$d/kicad_common.json\"; done; \ + export KICAD_CONFIG_HOME=\"$t\" KICAD_CACHE_HOME=\"$t/cache\" KICAD_DOCUMENTS_HOME=\"$t/documents\" KICAD_INHIBIT_SETTINGS_WRITES=1; \ + if command -v python3 >/dev/null 2>&1 && python3 -c \"\" >/dev/null 2>&1; then \ + run_bounded() {{ python3 -c 'import os,signal,subprocess,sys,time +p=subprocess.Popen([sys.argv[1],\"--version\"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True) +try: + o,_=p.communicate(timeout={timeout_secs}) +except subprocess.TimeoutExpired: + try: os.killpg(p.pid,signal.SIGTERM) + except OSError: pass + time.sleep(0.2) + try: os.killpg(p.pid,signal.SIGKILL) + except OSError: pass + p.wait() + sys.exit(124) +sys.stdout.buffer.write(o) +sys.exit(p.returncode)' \"$1\"; }}; \ + else \ + exit 127; \ + fi; \ + for c in {cands}; do if [ -x \"$c\" ]; then \ + v=$(run_bounded \"$c\") || continue; \ + [ -n \"$v\" ] || continue; \ + printf '%s\\t%s\\n' \"$c\" \"$v\"; exit 0; \ + fi; done; exit 1" + ) +} + +fn remote_probe_ssh_secs(cands: &str, per_cand_secs: u64) -> u64 { + let count = cands.split_whitespace().count().max(1) as u64; + count.saturating_mul(per_cand_secs.saturating_add(2)).saturating_add(10) +} + +/// (host, remote cli, local cli, local version) -> the probe's answer, so a host is asked once per local build version +static PROBED: Mutex)>> = Mutex::new(None); async fn remote_ready(hub: &Arc) -> Option { + const REMOTE_PROBE_SECS: u64 = 15; let host = hub.setting("checks.remote").await.unwrap_or_default(); if host.is_empty() || crate::copy::on() { return None } let cli_set = hub.setting("checks.remote.cli").await.unwrap_or_default(); let rt = ipc::runtime(hub).await; if rt.cli.is_empty() { return None } - let key = (host.clone(), cli_set.clone(), rt.cli.clone()); + let cli = rt.cli.clone(); + let here = tokio::task::spawn_blocking(move || ipc::cli_version_output(&cli)).await.ok().flatten().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default(); + if here.is_empty() { + eprintln!("checks: local kicad-cli at {} did not report a version; checks stay on this machine", rt.cli); + return None; + } + let key = (host.clone(), cli_set.clone(), rt.cli.clone(), here.clone()); if let Some((k, v)) = PROBED.lock().unwrap().clone() { if k == key { return v } } let name = Path::new(&rt.cli).parent().and_then(Path::parent).and_then(|d| d.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let here = { let (mut c, _home) = crate::proc::kicad_probe_tokio(&rt.cli); c.arg("--version").stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true); /* bounded (#1160): killed on expiry */ tokio::time::timeout(crate::proc::PROBE_LIMIT, c.output()).await.ok().and_then(|r| r.ok()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default() }; let cands = if cli_set.is_empty() { format!("$HOME/.cache/bp-kembed-remote/kicad/{name}/bin/kicad-cli $HOME/.backplane-gpui-fresh/home/kicad/{name}/bin/kicad-cli") } else { cli_set.clone() }; - let script = format!("for c in {cands}; do if [ -x \"$c\" ]; then printf '%s\\t' \"$c\"; \"$c\" --version; exit 0; fi; done; exit 1"); - let out = ssh(&host, &script, 20).await; - let found = out.ok().and_then(|o| { let (c, v) = o.trim().split_once('\t')?; (v.trim() == here && !here.is_empty()).then(|| Remote { host: host.clone(), cli: c.to_string() }) }); + let script = remote_version_probe_script(&cands, REMOTE_PROBE_SECS); + let out = ssh(&host, &script, remote_probe_ssh_secs(&cands, REMOTE_PROBE_SECS)).await; + let found = out.ok().and_then(|o| { let (c, v) = o.trim().split_once('\t')?; (v.trim() == here).then(|| Remote { host: host.clone(), cli: c.to_string() }) }); if found.is_none() { eprintln!("checks: {host} has no kicad-cli of this build ({here}); checks stay on this machine"); } *PROBED.lock().unwrap() = Some((key, found.clone())); found @@ -1127,4 +1169,202 @@ mod tests { x.sched.running_since = 5; assert_eq!(state_word(&x), "running"); x.sched.running_since = 0; x.state = "failed".into(); assert_eq!(state_word(&x), "failed"); } + + #[cfg(unix)] + #[test] + fn remote_version_probe_script_isolates_and_bounds_probes() { + use std::os::unix::fs::{symlink, PermissionsExt}; + use std::process::Command; + + fn find_bin(name: &str) -> Option { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file()) + } + + let d = crate::plat::tmp::dir("remote-probe"); + let (bad, ok, cfg_rec) = (d.join("bad-cli"), d.join("ok-cli"), d.join("cfg.path")); + std::fs::write(&bad, "#!/bin/sh\nexit 1\n").unwrap(); + std::fs::write( + &ok, + format!( + "#!/bin/sh\n\ + [ \"$1\" = --version ] || exit 2\n\ + [ \"$KICAD_INHIBIT_SETTINGS_WRITES\" = 1 ] || exit 3\n\ + grep -q '/nonexistent/bp-probe-python' \"$KICAD_CONFIG_HOME/10.99/kicad_common.json\" || exit 4\n\ + printf '%s' \"$KICAD_CONFIG_HOME\" > '{}'\n\ + echo 10.99.0\n", + cfg_rec.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::set_permissions(&ok, std::fs::Permissions::from_mode(0o755)).unwrap(); + + // Case 1: skips failing candidate, seeds & isolates settings, removes temp folder on exit. + let cands = format!("{} {}", bad.display(), ok.display()); + let out = Command::new("/bin/sh").args(["-c", &remote_version_probe_script(&cands, 5)]).output().unwrap(); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), format!("{}\t10.99.0", ok.display())); + let cfg_home = std::fs::read_to_string(&cfg_rec).unwrap(); + assert!(!Path::new(&cfg_home).exists(), "remote probe temp folder leaked: {cfg_home}"); + + // Helper restricted bin without timeout/gtimeout (only core POSIX tools + sleep). + let no_watchdog_bin = d.join("bin-none"); + std::fs::create_dir_all(&no_watchdog_bin).unwrap(); + for tool in ["mktemp", "mkdir", "rm", "sleep"] { + if let Some(src) = find_bin(tool) { + symlink(src, no_watchdog_bin.join(tool)).unwrap(); + } + } + + // Case 2: when neither timeout nor gtimeout is on PATH, python3 watchdog bounds & kills sleeper. + if let Some(py3) = find_bin("python3") { + let py_bin = d.join("bin-py"); + std::fs::create_dir_all(&py_bin).unwrap(); + for tool in ["mktemp", "mkdir", "rm", "sleep", "grep"] { + if let Some(src) = find_bin(tool) { + symlink(src, py_bin.join(tool)).unwrap(); + } + } + symlink(py3, py_bin.join("python3")).unwrap(); + + let started_rec = d.join("hang.started"); + let hang = d.join("hang-cli"); + std::fs::write( + &hang, + format!("#!/bin/sh\n: > '{}'\nexec sleep 30\n", started_rec.display()), + ) + .unwrap(); + std::fs::set_permissions(&hang, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let t0 = std::time::Instant::now(); + let hang_out = Command::new("/bin/sh") + .args(["-c", &remote_version_probe_script(&hang.to_string_lossy(), 1)]) + .env("PATH", &py_bin) + .output() + .unwrap(); + let elapsed = t0.elapsed(); + assert!(!hang_out.status.success(), "hanging remote probe should fail"); + assert!(started_rec.is_file(), "hanging probe never started before timeout"); + assert!(elapsed < Duration::from_secs(5), "python3 watchdog took too long: {elapsed:?}"); + } + + // Case 3: without a working python3 process-group watchdog (empty PATH, timeout-only PATH, or failing python3 stub), + // script exits 127 without executing any candidate. + let ran_rec = d.join("unbounded.ran"); + let touch = d.join("touch-cli"); + std::fs::write(&touch, format!("#!/bin/sh\n: > '{}'\necho 10.99.0\n", ran_rec.display())).unwrap(); + std::fs::set_permissions(&touch, std::fs::Permissions::from_mode(0o755)).unwrap(); + let skipped = Command::new("/bin/sh") + .args(["-c", &remote_version_probe_script(&touch.to_string_lossy(), 1)]) + .env("PATH", &no_watchdog_bin) + .output() + .unwrap(); + assert_eq!(skipped.status.code(), Some(127)); + assert!(!ran_rec.exists(), "unbounded remote probe must not execute without a watchdog"); + + if let Some(to) = find_bin("timeout") { + let to_bin = d.join("bin-timeout"); + std::fs::create_dir_all(&to_bin).unwrap(); + for tool in ["mktemp", "mkdir", "rm", "sleep", "grep"] { + if let Some(src) = find_bin(tool) { + symlink(src, to_bin.join(tool)).unwrap(); + } + } + symlink(to, to_bin.join("timeout")).unwrap(); + let skipped_to = Command::new("/bin/sh") + .args(["-c", &remote_version_probe_script(&touch.to_string_lossy(), 1)]) + .env("PATH", &to_bin) + .output() + .unwrap(); + assert_eq!(skipped_to.status.code(), Some(127)); + assert!(!ran_rec.exists(), "non-process-group timeout watchdog must not run probe without python3"); + } + + let stub_bin = d.join("bin-py-stub"); + std::fs::create_dir_all(&stub_bin).unwrap(); + for tool in ["mktemp", "mkdir", "rm", "sleep", "grep"] { + if let Some(src) = find_bin(tool) { + symlink(src, stub_bin.join(tool)).unwrap(); + } + } + let py_stub = stub_bin.join("python3"); + std::fs::write(&py_stub, "#!/bin/sh\nexit 1\n").unwrap(); + std::fs::set_permissions(&py_stub, std::fs::Permissions::from_mode(0o755)).unwrap(); + let skipped_stub = Command::new("/bin/sh") + .args(["-c", &remote_version_probe_script(&touch.to_string_lossy(), 1)]) + .env("PATH", &stub_bin) + .output() + .unwrap(); + assert_eq!(skipped_stub.status.code(), Some(127)); + assert!(!ran_rec.exists(), "failing python3 stub must not run probe"); + + // Case 4: multi-candidate SSH budget gives every candidate its timeout window plus SSH overhead. + assert_eq!(remote_probe_ssh_secs("/a/kicad-cli", 15), 27); + assert_eq!(remote_probe_ssh_secs("/a/kicad-cli /b/kicad-cli", 15), 44); + + // Case 5: descendant holding stdout open while ignoring SIGTERM is killed on both restricted-python3 and + // default PATHs, allowing a healthy second candidate to be discovered cleanly with zero orphan processes. + let run_pipe_leak_case = |label: &str, path_env: Option<&Path>| { + let pid_rec = d.join(format!("{label}.pid")); + let fallback_cfg = d.join(format!("{label}.cfg")); + let leak = d.join(format!("{label}-leak-cli")); + let fallback = d.join(format!("{label}-ok-cli")); + std::fs::write( + &leak, + format!( + "#!/bin/sh\n\ + echo 10.99.0\n\ + (trap '' TERM; exec sleep 30) &\n\ + echo $! > '{}'\n\ + exit 0\n", + pid_rec.display() + ), + ) + .unwrap(); + std::fs::write( + &fallback, + format!( + "#!/bin/sh\n\ + printf '%s' \"$KICAD_CONFIG_HOME\" > '{}'\n\ + echo 10.99.0\n", + fallback_cfg.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&leak, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::set_permissions(&fallback, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let cands = format!("{} {}", leak.display(), fallback.display()); + let t0 = std::time::Instant::now(); + let mut cmd = Command::new("/bin/sh"); + cmd.args(["-c", &remote_version_probe_script(&cands, 1)]); + if let Some(p) = path_env { + cmd.env("PATH", p); + } + let out = cmd.output().unwrap(); + let elapsed = t0.elapsed(); + assert!(out.status.success(), "{label} failed: {}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), format!("{}\t10.99.0", fallback.display()), "{label}"); + assert!(elapsed < Duration::from_secs(6), "{label} took too long: {elapsed:?}"); + + let cfg_dir = std::fs::read_to_string(&fallback_cfg).unwrap(); + assert!(!Path::new(&cfg_dir).exists(), "{label} temp config dir leaked: {cfg_dir}"); + + let desc_pid = std::fs::read_to_string(&pid_rec).unwrap().trim().to_string(); + assert!(!desc_pid.is_empty() && desc_pid.bytes().all(|b| b.is_ascii_digit()), "{label} bad pid: {desc_pid:?}"); + let reap_deadline = std::time::Instant::now() + Duration::from_millis(800); + while crate::proc::is_live_non_zombie(&desc_pid) { + assert!(std::time::Instant::now() < reap_deadline, "{label} descendant pid {desc_pid} survived watchdog"); + std::thread::sleep(Duration::from_millis(20)); + } + }; + + if find_bin("python3").is_some() { + run_pipe_leak_case("py3", Some(&d.join("bin-py"))); + run_pipe_leak_case("default", None); + } + + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/native/host/src/kicad/ipc.rs b/native/host/src/kicad/ipc.rs index 13e59aa4fe..b805ba061f 100644 --- a/native/host/src/kicad/ipc.rs +++ b/native/host/src/kicad/ipc.rs @@ -646,11 +646,351 @@ fn newest_in(dirs: &[PathBuf]) -> Vec { v.sort_by(|a, b| match (ks::version_ge(&a.0, &b.0), ks::version_ge(&b.0, &a.0)) { (true, true) => std::cmp::Ordering::Equal, (true, false) => std::cmp::Ordering::Less, _ => std::cmp::Ordering::Greater }); v.into_iter().flat_map(|(n, d)| [d.join(&n).join("bin").join("kicad-cli"), d.join(n).join("bin").join("kicad-cli.exe")]).collect() } -/// ` --version`, its settings in a throwaway folder (proc::kicad_probe): the probe never writes the person's KiCad settings. -/// Bounded (proc::probe_output): a run that hangs (#1160, macOS) is killed and the probe asked once more, since only some runs hang. -pub fn cli_version_output(cli: &str) -> Option { cli_version_within(cli, crate::proc::PROBE_LIMIT) } -pub fn cli_version_within(cli: &str, limit: std::time::Duration) -> Option { - (0..2).find_map(|_| { let (mut c, _home) = crate::proc::kicad_probe(cli); c.arg("--version"); crate::proc::probe_output(c, limit) }) +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct ProbeKey { + path: PathBuf, + mtime: Option, + size: u64, +} + +/// Resolve `cli` without probing the working directory for bare command names, then canonicalize so fingerprinting and launching +/// target the exact same file. +pub(crate) fn resolve_probe_path(cli: &Path) -> Option { + if cli.as_os_str().is_empty() { return None } + let cand = if cli.components().count() > 1 { + cli.to_path_buf() + } else { + let path_env = std::env::var_os("PATH")?; + let exts: &[&str] = if cfg!(windows) && cli.extension().is_none() { &["", ".exe", ".cmd", ".bat"] } else { &[""] }; + let mut hit = None; + 'outer: for dir in std::env::split_paths(&path_env) { + if dir.as_os_str().is_empty() { continue } + for ext in exts { + let mut file = cli.as_os_str().to_os_string(); + if !ext.is_empty() { file.push(ext); } + let p = dir.join(file); + if std::fs::metadata(&p).is_ok_and(|m| crate::plat::fs::runnable(&m)) { + hit = Some(p); + break 'outer; + } + } + } + hit? + }; + Some(crate::plat::fs::canonicalize(&cand).unwrap_or(cand)) +} + +pub(crate) fn probe_key_for(resolved: &Path) -> Option { + let meta = std::fs::metadata(resolved).ok()?; + Some(ProbeKey { path: resolved.to_path_buf(), mtime: meta.modified().ok(), size: meta.len() }) +} + +#[derive(Clone, Debug)] +pub enum ProbeOutcome { + Output(std::process::Output), + Timeout { limit: Duration, attempts: usize }, + SpawnErr(String), +} + +impl ProbeOutcome { + pub fn is_ok_success(&self) -> bool { + matches!(self, Self::Output(o) if o.status.success()) + } + + pub fn into_output(self) -> Option { + match self { + Self::Output(o) => Some(o), + _ => None, + } + } +} + +struct Flight { + waiters: std::sync::atomic::AtomicUsize, + done: std::sync::Mutex>, + cv: std::sync::Condvar, +} + +#[derive(Default)] +struct CacheState { + entries: HashMap, + in_flight: HashMap>, +} + +pub(crate) struct VersionProbeCache { + state: std::sync::Mutex, + failure_ttl: Duration, +} + +struct FlightGuard<'a> { + cache: &'a VersionProbeCache, + key: ProbeKey, + flight: Arc, + finished: bool, +} + +impl Drop for FlightGuard<'_> { + fn drop(&mut self) { + if self.finished { return } + { + let mut st = self.cache.state.lock().unwrap_or_else(|e| e.into_inner()); + if st.in_flight.get(&self.key).is_some_and(|f| Arc::ptr_eq(f, &self.flight)) { + st.in_flight.remove(&self.key); + } + } + let mut done = self.flight.done.lock().unwrap_or_else(|e| e.into_inner()); + if done.is_none() { + *done = Some(ProbeOutcome::SpawnErr("probe panicked".into())); + self.flight.cv.notify_all(); + } + } +} + +const VERSION_CACHE_CAP: usize = 128; +const VERSION_FAILURE_TTL: Duration = Duration::from_secs(30); + +impl VersionProbeCache { + pub fn new(failure_ttl: Duration) -> Self { + Self { state: std::sync::Mutex::new(CacheState::default()), failure_ttl } + } + + pub fn get_or_probe( + &self, + cli: &Path, + limit: Duration, + attempts: usize, + run: impl FnMut(&Path, Duration, usize, Option) -> ProbeOutcome, + ) -> ProbeOutcome { + self.get_or_probe_at(cli, limit, attempts, std::time::Instant::now, run) + } + + pub(crate) fn get_or_probe_at( + &self, + cli: &Path, + limit: Duration, + attempts: usize, + now: impl Fn() -> std::time::Instant, + mut run: impl FnMut(&Path, Duration, usize, Option) -> ProbeOutcome, + ) -> ProbeOutcome { + let attempts = attempts.max(1); + let Some(resolved) = resolve_probe_path(cli) else { return run(cli, limit, attempts, None) }; + let Some(key) = probe_key_for(&resolved) else { return run(&resolved, limit, attempts, None) }; + let wait_deadline = std::time::Instant::now() + limit.saturating_mul(attempts as u32); + let mut rem_attempts = attempts; + let mut waited_attempts_at_limit = 0usize; + let mut waited = false; + + loop { + let (flight, waiter) = { + let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if waited && std::time::Instant::now() >= wait_deadline { + return ProbeOutcome::Timeout { limit, attempts }; + } + let check_now = now(); + if let Some((at, outcome)) = st.entries.get(&key) { + let expired = !outcome.is_ok_success() && check_now.saturating_duration_since(*at) >= self.failure_ttl; + if expired { + st.entries.remove(&key); + } else { + match outcome { + ProbeOutcome::Output(o) if o.status.success() => return ProbeOutcome::Output(o.clone()), + ProbeOutcome::Timeout { limit: fl, attempts: fa } if *fl < limit || *fa < attempts => {} + ProbeOutcome::Timeout { .. } => return ProbeOutcome::Timeout { limit, attempts }, + other => return other.clone(), + } + } + } + if std::time::Instant::now() >= wait_deadline { + return ProbeOutcome::Timeout { limit, attempts }; + } + if let Some(flight) = st.in_flight.get(&key).cloned() { + flight.waiters.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + (flight, true) + } else { + let flight = Arc::new(Flight { + waiters: std::sync::atomic::AtomicUsize::new(0), + done: std::sync::Mutex::new(None), + cv: std::sync::Condvar::new(), + }); + st.in_flight.insert(key.clone(), flight.clone()); + (flight, false) + } + }; + + if waiter { + waited = true; + let mut done = flight.done.lock().unwrap_or_else(|e| e.into_inner()); + while done.is_none() { + let Some(rem) = wait_deadline.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else { + return ProbeOutcome::Timeout { limit, attempts }; + }; + let (next, res) = flight.cv.wait_timeout(done, rem).unwrap_or_else(|e| e.into_inner()); + done = next; + if done.is_none() && res.timed_out() { + return ProbeOutcome::Timeout { limit, attempts }; + } + } + if std::time::Instant::now() >= wait_deadline { + return ProbeOutcome::Timeout { limit, attempts }; + } + match done.clone().expect("notified flight always holds an outcome") { + ProbeOutcome::Timeout { limit: fl, attempts: fa } => { + if fl >= limit && fa > 0 { + waited_attempts_at_limit += fa; + rem_attempts = rem_attempts.saturating_sub(fa); + if rem_attempts == 0 { + return ProbeOutcome::Timeout { limit, attempts }; + } + } + if std::time::Instant::now() >= wait_deadline { + return ProbeOutcome::Timeout { limit, attempts }; + } + continue; + } + other => return other, + } + } + + let mut guard = FlightGuard { cache: self, key: key.clone(), flight: flight.clone(), finished: false }; + let raw = run(&resolved, limit, rem_attempts, waited.then_some(wait_deadline)); + let finished_at = now(); + let (cached_outcome, notify_outcome, caller_outcome) = match raw { + ProbeOutcome::Timeout { limit: _, attempts: 0 } => { + let zero = ProbeOutcome::Timeout { limit: Duration::ZERO, attempts: 0 }; + (None, zero, ProbeOutcome::Timeout { limit, attempts }) + } + ProbeOutcome::Timeout { limit: l, attempts: a } => { + let total_at_limit = if l >= limit { a + waited_attempts_at_limit } else { a }; + let cached = ProbeOutcome::Timeout { limit: l, attempts: total_at_limit }; + let raw_done = ProbeOutcome::Timeout { limit: l, attempts: a }; + let ret = if l >= limit && total_at_limit >= attempts { + ProbeOutcome::Timeout { limit: l, attempts: total_at_limit.max(attempts) } + } else { + ProbeOutcome::Timeout { limit, attempts } + }; + (Some(cached), raw_done, ret) + } + other => (Some(other.clone()), other.clone(), other), + }; + { + let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if st.in_flight.get(&key).is_some_and(|f| Arc::ptr_eq(f, &flight)) { + st.in_flight.remove(&key); + } + if let Some(cached) = cached_outcome { + if st.entries.len() >= VERSION_CACHE_CAP { + let ttl = self.failure_ttl; + st.entries.retain(|_, (at, o)| o.is_ok_success() || finished_at.saturating_duration_since(*at) < ttl); + while st.entries.len() >= VERSION_CACHE_CAP { + if let Some(oldest) = st.entries.iter().min_by_key(|(_, (at, _))| *at).map(|(k, _)| k.clone()) { + st.entries.remove(&oldest); + } else { + break; + } + } + } + let keep_existing = st.entries.get(&key).is_some_and(|(at, cur)| { + let cur_fresh = cur.is_ok_success() || finished_at.saturating_duration_since(*at) < self.failure_ttl; + if !cur_fresh { return false } + if cur.is_ok_success() && !cached.is_ok_success() { return true } + match (cur, &cached) { + (ProbeOutcome::Timeout { limit: cl, attempts: ca }, ProbeOutcome::Timeout { limit: nl, attempts: na }) => *cl >= *nl && *ca >= *na, + _ => false, + } + }); + if !keep_existing { + st.entries.insert(key, (finished_at, cached)); + } + } + } + { + let mut done = flight.done.lock().unwrap_or_else(|e| e.into_inner()); + *done = Some(notify_outcome); + flight.cv.notify_all(); + } + guard.finished = true; + return caller_outcome; + } + } + + #[cfg(test)] + pub(crate) fn in_flight_waiters(&self, cli: &Path) -> usize { + let Some(resolved) = resolve_probe_path(cli) else { return 0 }; + let Some(key) = probe_key_for(&resolved) else { return 0 }; + let st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + st.in_flight.get(&key).map_or(0, |f| f.waiters.load(std::sync::atomic::Ordering::SeqCst)) + } +} + +static VERSION_CACHE: OnceLock = OnceLock::new(); +fn version_cache() -> &'static VersionProbeCache { + VERSION_CACHE.get_or_init(|| VersionProbeCache::new(VERSION_FAILURE_TTL)) +} + +fn probe_cli_version_uncached_until(cli: &Path, limit: Duration, attempts: usize, deadline: Option) -> ProbeOutcome { + let attempts = attempts.max(1); + let mut full_attempts = 0usize; + let mut tried = 0usize; + let mut max_limit_tried = Duration::ZERO; + for _ in 0..attempts { + if deadline.is_some_and(|dl| std::time::Instant::now() >= dl) { + break; + } + let (mut c, _home) = crate::proc::kicad_probe(cli); + c.arg("--version"); + let now_run = std::time::Instant::now(); + let (step_limit, step_end) = if let Some(dl) = deadline { + let Some(rem) = dl.checked_duration_since(now_run).filter(|d| !d.is_zero()) else { + break; + }; + let step = limit.min(rem); + (step, now_run + step) + } else { + (limit, now_run + limit) + }; + if step_limit >= limit { + full_attempts += 1; + } + tried += 1; + max_limit_tried = max_limit_tried.max(step_limit); + match crate::proc::probe_output_until(c, step_end, deadline, step_limit) { + Ok(out) => return ProbeOutcome::Output(out), + Err(crate::proc::ProbeError::Spawn(e)) => return ProbeOutcome::SpawnErr(e.to_string()), + Err(crate::proc::ProbeError::Timeout) => {} + } + } + if full_attempts > 0 { + ProbeOutcome::Timeout { limit, attempts: full_attempts } + } else { + ProbeOutcome::Timeout { limit: max_limit_tried, attempts: tried } + } +} + +/// ` --version`, single-flight deduplicated and cached by `(canonical_path, mtime, size)` with budget-aware sharing. +pub fn cli_version_cached_path(cli: &Path, limit: Duration, attempts: usize) -> ProbeOutcome { + version_cache().get_or_probe(cli, limit, attempts, |p, l, a, deadline| { + probe_cli_version_uncached_until(p, l, a, deadline) + }) +} + +pub fn cli_version_cached(cli: &str, limit: Duration, attempts: usize) -> ProbeOutcome { + cli_version_cached_path(Path::new(cli), limit, attempts) +} + +/// ` --version`, its settings in a throwaway pre-seeded folder (proc::kicad_probe): the probe never writes the person's KiCad +/// settings or triggers `FindPythonInterpreter`. Bounded (proc::probe_output_result): a run that hangs (#1160, macOS) has its process +/// group killed and reaped, and is asked once more; concurrent callers share one probe and results are cached by `(path, mtime, size)`. +pub fn cli_version_output_path(cli: &Path) -> Option { + cli_version_cached_path(cli, crate::proc::PROBE_LIMIT, 2).into_output() +} + +pub fn cli_version_output(cli: &str) -> Option { + cli_version_output_path(Path::new(cli)) +} + +/// Uncached bounded ` --version` probe (up to 2 attempts, killing and reaping the process group on timeout). +pub fn cli_version_within(cli: &str, limit: Duration) -> Option { + probe_cli_version_uncached_until(Path::new(cli), limit, 2, None).into_output() } /// Publish what this machine has for Settings > CAD: info `kicad.cli`, `kicad.version`, `kicad.status`, `kicad.source` and `freecad` (empty when absent). pub async fn publish_cad(hub: &Arc) { @@ -1987,6 +2327,879 @@ mod tests { tx.send(Msg::Clear).unwrap(); assert!(info_on(&ipc).await.contains("|stopped|")); } + + fn ok_test_out(s: &str) -> ProbeOutcome { + #[cfg(unix)] + let status = { use std::os::unix::process::ExitStatusExt; std::process::ExitStatus::from_raw(0) }; + #[cfg(windows)] + let status = { use std::os::windows::process::ExitStatusExt; std::process::ExitStatus::from_raw(0) }; + ProbeOutcome::Output(std::process::Output { status, stdout: s.as_bytes().to_vec(), stderr: vec![] }) + } + + fn stdout_trimmed(o: ProbeOutcome) -> String { + String::from_utf8_lossy(&o.into_output().expect("output").stdout).trim().to_string() + } + + fn wait_for_waiters(cache: &VersionProbeCache, cli: &Path, want: usize) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while cache.in_flight_waiters(cli) < want { + assert!(std::time::Instant::now() < deadline, "timed out waiting for {want} single-flight waiters"); + std::thread::sleep(Duration::from_millis(2)); + } + } + + #[test] + fn version_probe_cache_single_flight_and_mtime_size_invalidation() { + use std::sync::{atomic::{AtomicUsize, Ordering}, Condvar, Mutex}; + + let d = crate::plat::tmp::dir("vprobe-cache"); + let cli = d.join("kicad-cli"); + std::fs::write(&cli, "v1-payload").unwrap(); + let orig_mtime = std::fs::metadata(&cli).unwrap().modified().unwrap(); + let t0 = std::time::Instant::now(); + + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let calls = Arc::new(AtomicUsize::new(0)); + let active = Arc::new(AtomicUsize::new(0)); + let max_active = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + + let leader = { + let (cache, cli, calls, active, max_active, gate) = (cache.clone(), cli.clone(), calls.clone(), active.clone(), max_active.clone(), gate.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + let cur = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(cur, Ordering::SeqCst); + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + drop(st); + active.fetch_sub(1, Ordering::SeqCst); + ok_test_out("10.0.9\n") + }) + }) + }; + + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + + let mut waiters = vec![]; + for _ in 0..7 { + let (cache, cli, calls) = (cache.clone(), cli.clone(), calls.clone()); + waiters.push(std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }) + })); + } + wait_for_waiters(&cache, &cli, 7); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert_eq!(stdout_trimmed(leader.join().unwrap()), "10.0.9"); + for w in waiters { + assert_eq!(stdout_trimmed(w.join().unwrap()), "10.0.9"); + } + assert_eq!(calls.load(Ordering::SeqCst), 1, "single-flight deduplicated 8 concurrent probes"); + assert_eq!(max_active.load(Ordering::SeqCst), 1); + + let hit = cache.get_or_probe_at(&cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }); + assert_eq!(stdout_trimmed(hit), "10.0.9"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "subsequent call hits cache"); + + // Size change with identical mtime -> cache miss + std::fs::write(&cli, "v1-payload-longer").unwrap(); + std::fs::File::options().write(true).open(&cli).unwrap().set_modified(orig_mtime).unwrap(); + let resolved_cli = resolve_probe_path(&cli).unwrap(); + assert_eq!(probe_key_for(&resolved_cli).unwrap().mtime, Some(orig_mtime)); + let hit2 = cache.get_or_probe_at(&cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.0.10\n") + }); + assert_eq!(stdout_trimmed(hit2), "10.0.10"); + assert_eq!(calls.load(Ordering::SeqCst), 2, "size change invalidates cache even with identical mtime"); + + // mtime change with identical size -> cache miss + std::fs::write(&cli, "v2-payload-longer").unwrap(); + std::fs::File::options().write(true).open(&cli).unwrap().set_modified(orig_mtime + Duration::from_secs(10)).unwrap(); + let hit3 = cache.get_or_probe_at(&cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.0.11\n") + }); + assert_eq!(stdout_trimmed(hit3), "10.0.11"); + assert_eq!(calls.load(Ordering::SeqCst), 3, "mtime change invalidates cache even with identical size"); + + // Negative cache TTL (deterministic virtual clock) and larger-limit bypass + let fail_cli = d.join("fail-cli"); + std::fs::write(&fail_cli, "fail").unwrap(); + let fail_calls = AtomicUsize::new(0); + let r1 = cache.get_or_probe_at(&fail_cli, Duration::from_secs(2), 1, || t0, |_, l, a, _| { + fail_calls.fetch_add(1, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l, attempts: a } + }); + assert!(matches!(r1, ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_secs(2))); + let r2 = cache.get_or_probe_at(&fail_cli, Duration::from_secs(2), 1, || t0 + Duration::from_secs(10), |_, l, a, _| { + fail_calls.fetch_add(1, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l, attempts: a } + }); + assert!(matches!(r2, ProbeOutcome::Timeout { .. })); + assert_eq!(fail_calls.load(Ordering::SeqCst), 1, "failure cached within TTL for equal/smaller limit"); + + let r3 = cache.get_or_probe_at(&fail_cli, Duration::from_secs(5), 1, || t0 + Duration::from_secs(10), |_, l, a, _| { + fail_calls.fetch_add(1, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l, attempts: a } + }); + assert!(matches!(r3, ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_secs(5))); + assert_eq!(fail_calls.load(Ordering::SeqCst), 2, "larger timeout limit bypasses smaller timeout cache"); + + let r4 = cache.get_or_probe_at(&fail_cli, Duration::from_secs(5), 1, || t0 + Duration::from_secs(41), |_, _, _, _| { + fail_calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.0.12\n") + }); + assert_eq!(stdout_trimmed(r4), "10.0.12"); + assert_eq!(fail_calls.load(Ordering::SeqCst), 3, "expired failure is retried"); + + // Failure TTL starts at completion, not probe start: a full 30s timeout stays cached for 30s after completion. + let slow_fail_cli = d.join("slow-fail-cli"); + std::fs::write(&slow_fail_cli, "slow-fail").unwrap(); + let clock = Arc::new(Mutex::new(t0)); + let slow_calls = AtomicUsize::new(0); + let f1 = cache.get_or_probe_at( + &slow_fail_cli, + Duration::from_secs(15), + 2, + || *clock.lock().unwrap(), + |_, l, a, _| { + slow_calls.fetch_add(1, Ordering::SeqCst); + *clock.lock().unwrap() += Duration::from_secs(30); + ProbeOutcome::Timeout { limit: l, attempts: a } + }, + ); + assert!(matches!(f1, ProbeOutcome::Timeout { limit, attempts: 2 } if limit == Duration::from_secs(15))); + + *clock.lock().unwrap() = t0 + Duration::from_secs(40); + let f2 = cache.get_or_probe_at( + &slow_fail_cli, + Duration::from_secs(15), + 2, + || *clock.lock().unwrap(), + |_, l, a, _| { + slow_calls.fetch_add(1, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l, attempts: a } + }, + ); + assert!(matches!(f2, ProbeOutcome::Timeout { limit, attempts: 2 } if limit == Duration::from_secs(15))); + assert_eq!(slow_calls.load(Ordering::SeqCst), 1, "full-budget failure stays cached relative to completion"); + + *clock.lock().unwrap() = t0 + Duration::from_secs(61); + let f3 = cache.get_or_probe_at( + &slow_fail_cli, + Duration::from_secs(15), + 2, + || *clock.lock().unwrap(), + |_, _, _, _| { + slow_calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.0.14\n") + }, + ); + assert_eq!(stdout_trimmed(f3), "10.0.14"); + assert_eq!(slow_calls.load(Ordering::SeqCst), 2, "failure expires 30s after completion"); + + // Panic safety: panicking leader wakes registered waiters and clears in-flight entry deterministically + let p_cli = d.join("panic-cli"); + std::fs::write(&p_cli, "p").unwrap(); + let p_gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let p_leader = { + let (cache, p_cli, p_gate) = (cache.clone(), p_cli.clone(), p_gate.clone()); + std::thread::spawn(move || { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + cache.get_or_probe_at(&p_cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| { + let (lk, cv) = &*p_gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + panic!("simulated panic in probe leader"); + }) + })); + }) + }; + { + let (lk, cv) = &*p_gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let p_waiter = { + let (cache, p_cli) = (cache.clone(), p_cli.clone()); + std::thread::spawn(move || cache.get_or_probe_at(&p_cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| ok_test_out("unused\n"))) + }; + wait_for_waiters(&cache, &p_cli, 1); + { + let (lk, cv) = &*p_gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + p_leader.join().unwrap(); + assert!(matches!(p_waiter.join().unwrap(), ProbeOutcome::SpawnErr(ref m) if m.contains("panicked"))); + let recovered = cache.get_or_probe_at(&p_cli, Duration::from_secs(5), 1, || t0, |_, _, _, _| ok_test_out("10.0.13\n")); + assert_eq!(stdout_trimmed(recovered), "10.0.13"); + } + + #[test] + fn version_probe_cache_mixed_budget_arrival_orders() { + use std::sync::{atomic::{AtomicUsize, Ordering}, Condvar, Mutex}; + + let d = crate::plat::tmp::dir("vprobe-budget"); + let t0 = std::time::Instant::now(); + + // Case A: weak (2s, 1 attempt) arrives first and times out; strong (2s, 2 attempts) joins in-flight. + // Weak must return Timeout { 2s, 1 }; strong must continue with ONLY the remaining 1 attempt and succeed. + { + let cli = d.join("case-a"); + std::fs::write(&cli, "a").unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let calls = Arc::new(AtomicUsize::new(0)); + let strong_observed_attempts = Arc::new(AtomicUsize::new(0)); + + let weak = { + let (cache, cli, gate, calls) = (cache.clone(), cli.clone(), gate.clone(), calls.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(2), 1, || t0, |_, l, a, _| { + calls.fetch_add(1, Ordering::SeqCst); + assert_eq!(a, 1); + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + ProbeOutcome::Timeout { limit: l, attempts: a } + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let strong = { + let (cache, cli, calls, obs) = (cache.clone(), cli.clone(), calls.clone(), strong_observed_attempts.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(2), 2, || t0, |_, _, a, _| { + calls.fetch_add(1, Ordering::SeqCst); + obs.store(a, Ordering::SeqCst); + ok_test_out("10.99.0\n") + }) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert!(matches!(weak.join().unwrap(), ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_secs(2))); + assert_eq!(stdout_trimmed(strong.join().unwrap()), "10.99.0"); + assert_eq!(strong_observed_attempts.load(Ordering::SeqCst), 1, "strong runs only remaining 1 attempt after joining weak"); + assert_eq!(calls.load(Ordering::SeqCst), 2); + let cached = cache.get_or_probe_at(&cli, Duration::from_secs(2), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }); + assert_eq!(stdout_trimmed(cached), "10.99.0"); + assert_eq!(calls.load(Ordering::SeqCst), 2, "weak success from strong is cached"); + } + + // Case B: strong (2s, 2 attempts) arrives first and runs past weak's 150ms budget; weak joins in-flight. + // Weak must return Timeout { 150ms, 1 } promptly BEFORE strong finishes, while strong caches success for follow-up callers. + { + let cli = d.join("case-b"); + std::fs::write(&cli, "b").unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let calls = Arc::new(AtomicUsize::new(0)); + + let strong = { + let (cache, cli, gate, calls) = (cache.clone(), cli.clone(), gate.clone(), calls.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(2), 2, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + ok_test_out("10.99.0\n") + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let weak = { + let (cache, cli, calls) = (cache.clone(), cli.clone(), calls.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(150), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }) + }) + }; + wait_for_waiters(&cache, &cli, 1); + let weak_res = weak.join().unwrap(); + assert!(matches!(weak_res, ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_millis(150))); + // Only now unblock strong: weak returned strictly before strong finished! + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert_eq!(stdout_trimmed(strong.join().unwrap()), "10.99.0"); + let cached = cache.get_or_probe_at(&cli, Duration::from_millis(150), 1, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }); + assert_eq!(stdout_trimmed(cached), "10.99.0"); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + // Case C: both arrival orders when leader succeeds quickly -> 1 probe serves both. + for (weak_first, name) in [(true, "case-c-weak"), (false, "case-c-strong")] { + let cli = d.join(name); + std::fs::write(&cli, "c").unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let calls = Arc::new(AtomicUsize::new(0)); + let (la, wa) = if weak_first { (1, 2) } else { (2, 1) }; + + let leader = { + let (cache, cli, gate, calls) = (cache.clone(), cli.clone(), gate.clone(), calls.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(2), la, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + ok_test_out("10.99.0\n") + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let waiter = { + let (cache, cli, calls) = (cache.clone(), cli.clone(), calls.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_secs(2), wa, || t0, |_, _, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert_eq!(stdout_trimmed(leader.join().unwrap()), "10.99.0"); + assert_eq!(stdout_trimmed(waiter.join().unwrap()), "10.99.0"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "{name}"); + } + + // Case D: waiter taking over from a weaker probe inherits only its remaining wall-clock budget. + { + let cli = d.join("case-d-mock"); + std::fs::write(&cli, "d").unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let rem_seen_ms = Arc::new(AtomicUsize::new(usize::MAX)); + + let weak = { + let (cache, cli, gate) = (cache.clone(), cli.clone(), gate.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(140), 1, std::time::Instant::now, |_, l, a, _| { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + drop(st); + std::thread::sleep(Duration::from_millis(110)); + ProbeOutcome::Timeout { limit: l, attempts: a } + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let strong = { + let (cache, cli, rem_seen_ms) = (cache.clone(), cli.clone(), rem_seen_ms.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(200), 1, std::time::Instant::now, |_, l, a, dl| { + let dl = dl.expect("expected continuation deadline after weaker probe"); + let rem = dl.saturating_duration_since(std::time::Instant::now()).as_millis() as usize; + rem_seen_ms.store(rem, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l.min(Duration::from_millis(rem as u64)), attempts: a } + }) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert!(matches!(weak.join().unwrap(), ProbeOutcome::Timeout { .. })); + assert!(matches!(strong.join().unwrap(), ProbeOutcome::Timeout { .. })); + let rem = rem_seen_ms.load(Ordering::SeqCst); + assert!(rem < 115, "expected remaining continuation deadline < 115ms, got {rem}ms"); + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let cli = d.join("case-d-real"); + std::fs::write(&cli, "#!/bin/sh\nsleep 10\n").unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + + let weak = { + let (cache, cli, gate) = (cache.clone(), cli.clone(), gate.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(200), 1, std::time::Instant::now, |_, l, a, _| { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + drop(st); + std::thread::sleep(Duration::from_millis(180)); + ProbeOutcome::Timeout { limit: l, attempts: a } + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let strong = { + let (cache, cli) = (cache.clone(), cli.clone()); + std::thread::spawn(move || { + let started = std::time::Instant::now(); + let res = cache.get_or_probe_at(&cli, Duration::from_millis(300), 1, std::time::Instant::now, probe_cli_version_uncached_until); + (started.elapsed(), res) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert!(matches!(weak.join().unwrap(), ProbeOutcome::Timeout { .. })); + let (elapsed, strong_res) = strong.join().unwrap(); + assert!(matches!(strong_res, ProbeOutcome::Timeout { .. })); + assert!(elapsed < Duration::from_millis(420), "continuation exceeded caller budget: {elapsed:?}"); + + let followup_calls = AtomicUsize::new(0); + let retry = cache.get_or_probe_at(&cli, Duration::from_millis(300), 1, std::time::Instant::now, |_, _, _, _| { + followup_calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.99.2\n") + }); + assert_eq!(stdout_trimmed(retry), "10.99.2"); + assert_eq!(followup_calls.load(Ordering::SeqCst), 1, "capped continuation timeout must not cache as a full 300ms timeout"); + } + + // Case E: waiter joining a LARGER-limit flight (400ms, 1) with (220ms, 2) must carry its remaining wall-clock + // deadline into its second attempt and must not cache a truncated continuation as a full (220ms, 2) timeout. + { + let cli = d.join("case-e-mock"); + std::fs::write(&cli, "e").unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + let rem_seen_ms = Arc::new(AtomicUsize::new(usize::MAX)); + let attempts_seen = Arc::new(AtomicUsize::new(0)); + + let leader = { + let (cache, cli, gate) = (cache.clone(), cli.clone(), gate.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(400), 1, std::time::Instant::now, |_, l, a, _| { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + drop(st); + std::thread::sleep(Duration::from_millis(300)); + ProbeOutcome::Timeout { limit: l, attempts: a } + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let waiter = { + let (cache, cli, rem_seen_ms, attempts_seen) = (cache.clone(), cli.clone(), rem_seen_ms.clone(), attempts_seen.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(220), 2, std::time::Instant::now, |_, l, a, dl| { + attempts_seen.store(a, Ordering::SeqCst); + let dl = dl.expect("expected continuation deadline after larger-limit flight"); + let rem = dl.saturating_duration_since(std::time::Instant::now()).as_millis() as usize; + rem_seen_ms.store(rem, Ordering::SeqCst); + ProbeOutcome::Timeout { limit: l.min(Duration::from_millis(rem as u64)), attempts: a } + }) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert!(matches!(leader.join().unwrap(), ProbeOutcome::Timeout { .. })); + assert!(matches!(waiter.join().unwrap(), ProbeOutcome::Timeout { .. })); + assert_eq!(attempts_seen.load(Ordering::SeqCst), 1); + let rem = rem_seen_ms.load(Ordering::SeqCst); + assert!(rem < 170, "expected remaining continuation deadline < 170ms (total 440ms - 300ms wait), got {rem}ms"); + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let cli = d.join("case-e-real"); + std::fs::write(&cli, "#!/bin/sh\ntrap '' TERM\nexec sleep 10\n").unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let gate = Arc::new((Mutex::new((false, false)), Condvar::new())); + + let leader = { + let (cache, cli, gate) = (cache.clone(), cli.clone(), gate.clone()); + std::thread::spawn(move || { + cache.get_or_probe_at(&cli, Duration::from_millis(450), 1, std::time::Instant::now, |_, l, a, _| { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.0 = true; + cv.notify_all(); + while !st.1 { + st = cv.wait(st).unwrap(); + } + drop(st); + std::thread::sleep(Duration::from_millis(360)); + ProbeOutcome::Timeout { limit: l, attempts: a } + }) + }) + }; + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + while !st.0 { + st = cv.wait(st).unwrap(); + } + } + let waiter = { + let (cache, cli) = (cache.clone(), cli.clone()); + std::thread::spawn(move || { + let started = std::time::Instant::now(); + let res = cache.get_or_probe_at(&cli, Duration::from_millis(250), 2, std::time::Instant::now, probe_cli_version_uncached_until); + (started.elapsed(), res) + }) + }; + wait_for_waiters(&cache, &cli, 1); + { + let (lk, cv) = &*gate; + let mut st = lk.lock().unwrap(); + st.1 = true; + cv.notify_all(); + } + assert!(matches!(leader.join().unwrap(), ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_millis(450))); + let (elapsed, waiter_res) = waiter.join().unwrap(); + assert!(matches!(waiter_res, ProbeOutcome::Timeout { .. })); + assert!(elapsed < Duration::from_millis(560), "waiter continuation exceeded 500ms budget (incl. SIGTERM cleanup): {elapsed:?}"); + + let leader_followup = AtomicUsize::new(0); + let cached_leader = cache.get_or_probe_at(&cli, Duration::from_millis(450), 1, std::time::Instant::now, |_, _, _, _| { + leader_followup.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }); + assert!(matches!(cached_leader, ProbeOutcome::Timeout { .. })); + assert_eq!(leader_followup.load(Ordering::SeqCst), 0, "leader's 450ms x1 timeout must remain cached"); + + let followup_calls = AtomicUsize::new(0); + let retry = cache.get_or_probe_at(&cli, Duration::from_millis(250), 2, std::time::Instant::now, |_, _, _, _| { + followup_calls.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.99.3\n") + }); + assert_eq!(stdout_trimmed(retry), "10.99.3"); + assert_eq!(followup_calls.load(Ordering::SeqCst), 1, "truncated continuation must not cache as a full (250ms, 2) timeout"); + } + + // Case F: equal-limit waiter (250ms, 2) joining a SIGTERM-ignoring (250ms, 1) flight obeys its 500ms + // wall-clock deadline end-to-end and does not cache a truncated continuation as (250ms, 2). + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let cli = d.join("case-f-real"); + let log = d.join("case-f-real.log"); + std::fs::write(&cli, format!("#!/bin/sh\necho $$ >> '{}'\ntrap '' TERM\nexec sleep 10\n", log.display())).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + + let weak = { + let (cache, cli) = (cache.clone(), cli.clone()); + std::thread::spawn(move || cache.get_or_probe_at(&cli, Duration::from_millis(250), 1, std::time::Instant::now, probe_cli_version_uncached_until)) + }; + let wait_start = std::time::Instant::now() + Duration::from_secs(5); + while !log.is_file() { + assert!(std::time::Instant::now() < wait_start, "weak equal-limit probe did not start"); + std::thread::sleep(Duration::from_millis(2)); + } + let strong = { + let (cache, cli) = (cache.clone(), cli.clone()); + std::thread::spawn(move || { + let started = std::time::Instant::now(); + let res = cache.get_or_probe_at(&cli, Duration::from_millis(250), 2, std::time::Instant::now, probe_cli_version_uncached_until); + (started.elapsed(), res) + }) + }; + wait_for_waiters(&cache, &cli, 1); + assert!(matches!(weak.join().unwrap(), ProbeOutcome::Timeout { limit, attempts: 1 } if limit == Duration::from_millis(250))); + let (elapsed, strong_res) = strong.join().unwrap(); + assert!(matches!(strong_res, ProbeOutcome::Timeout { .. })); + assert!(elapsed < Duration::from_millis(570), "equal-limit continuation exceeded 500ms budget: {elapsed:?}"); + + let followup_1 = AtomicUsize::new(0); + let cached_1 = cache.get_or_probe_at(&cli, Duration::from_millis(250), 1, std::time::Instant::now, |_, _, _, _| { + followup_1.fetch_add(1, Ordering::SeqCst); + ok_test_out("unexpected\n") + }); + assert!(matches!(cached_1, ProbeOutcome::Timeout { .. })); + assert_eq!(followup_1.load(Ordering::SeqCst), 0, "weak (250ms, 1) timeout stays cached"); + + let followup_2 = AtomicUsize::new(0); + let retry_2 = cache.get_or_probe_at(&cli, Duration::from_millis(250), 2, std::time::Instant::now, |_, _, _, _| { + followup_2.fetch_add(1, Ordering::SeqCst); + ok_test_out("10.99.4\n") + }); + assert_eq!(stdout_trimmed(retry_2), "10.99.4"); + assert_eq!(followup_2.load(Ordering::SeqCst), 1, "truncated equal-limit continuation must not cache as (250ms, 2)"); + } + } + + #[cfg(unix)] + #[test] + fn version_probe_cache_real_timeouts_populate_cache_for_same_budget() { + use std::os::unix::fs::PermissionsExt; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let d = crate::plat::tmp::dir("vprobe-real-to"); + let make_hang = |name: &str| { + let cli = d.join(name); + let log = d.join(format!("{name}.log")); + std::fs::write(&cli, format!("#!/bin/sh\necho $$ >> '{}'\nexec sleep 10\n", log.display())).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + (cli, log) + }; + let cache = Arc::new(VersionProbeCache::new(Duration::from_secs(30))); + let limit = Duration::from_millis(200); + + // 1. Solo 1-attempt real timeout populates cache for (limit, 1) and serves repeat call from cache. + let (c1, l1) = make_hang("solo-1"); + let r1 = cache.get_or_probe(&c1, limit, 1, probe_cli_version_uncached_until); + assert!(matches!(r1, ProbeOutcome::Timeout { limit: l, attempts: 1 } if l == limit), "got {r1:?}"); + assert_eq!(std::fs::read_to_string(&l1).unwrap().lines().count(), 1); + let r1_again = cache.get_or_probe(&c1, limit, 1, probe_cli_version_uncached_until); + assert!(matches!(r1_again, ProbeOutcome::Timeout { limit: l, attempts: 1 } if l == limit)); + assert_eq!(std::fs::read_to_string(&l1).unwrap().lines().count(), 1, "solo 1-attempt timeout cached"); + + // 2. Solo 2-attempt real timeout populates cache for (limit, 2) and serves repeat call from cache. + let (c2, l2) = make_hang("solo-2"); + let r2 = cache.get_or_probe(&c2, limit, 2, probe_cli_version_uncached_until); + assert!(matches!(r2, ProbeOutcome::Timeout { limit: l, attempts: 2 } if l == limit), "got {r2:?}"); + assert_eq!(std::fs::read_to_string(&l2).unwrap().lines().count(), 2); + let r2_again = cache.get_or_probe(&c2, limit, 2, probe_cli_version_uncached_until); + assert!(matches!(r2_again, ProbeOutcome::Timeout { limit: l, attempts: 2 } if l == limit)); + assert_eq!(std::fs::read_to_string(&l2).unwrap().lines().count(), 2, "solo 2-attempt timeout cached"); + + // 3. Same-limit 1-attempt followed mid-flight by 2-attempt continuation populates cache for (limit, 2). + let (c3, l3) = make_hang("weak-then-2"); + let weak_limit = Duration::from_millis(400); + let weak = { + let (cache, cli) = (cache.clone(), c3.clone()); + std::thread::spawn(move || cache.get_or_probe(&cli, weak_limit, 1, probe_cli_version_uncached_until)) + }; + let wait_start = std::time::Instant::now() + Duration::from_secs(5); + while !l3.is_file() { + assert!(std::time::Instant::now() < wait_start, "weak probe did not start"); + std::thread::sleep(Duration::from_millis(2)); + } + std::thread::sleep(Duration::from_millis(80)); + let strong = { + let (cache, cli) = (cache.clone(), c3.clone()); + std::thread::spawn(move || cache.get_or_probe(&cli, weak_limit, 2, probe_cli_version_uncached_until)) + }; + wait_for_waiters(&cache, &c3, 1); + assert!(matches!(weak.join().unwrap(), ProbeOutcome::Timeout { limit: l, attempts: 1 } if l == weak_limit)); + assert!(matches!(strong.join().unwrap(), ProbeOutcome::Timeout { limit: l, attempts: 2 } if l == weak_limit)); + assert_eq!(std::fs::read_to_string(&l3).unwrap().lines().count(), 2, "1 weak + 1 continuation = 2 total spawns"); + + let followup_calls = AtomicUsize::new(0); + let hit = cache.get_or_probe(&c3, weak_limit, 2, |p, l, a, dl| { + followup_calls.fetch_add(1, Ordering::SeqCst); + probe_cli_version_uncached_until(p, l, a, dl) + }); + assert!(matches!(hit, ProbeOutcome::Timeout { limit: l, attempts: 2 } if l == weak_limit)); + assert_eq!(followup_calls.load(Ordering::SeqCst), 0, "repeat 2-attempt call hits cache"); + } + + #[test] + fn resolve_probe_path_ignores_cwd_file_for_bare_command_name() { + // A bare command name must never resolve to a file in the current working directory. + if Path::new("Cargo.toml").is_file() { + assert_eq!(resolve_probe_path(Path::new("Cargo.toml")), None); + } + assert_eq!(resolve_probe_path(Path::new("bp-nonexistent-kicad-cli-test-only")), None); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("resolve-symlink"); + let (t1, t2, link) = (d.join("t1"), d.join("t2"), d.join("kicad-cli")); + std::fs::write(&t1, "a").unwrap(); + std::fs::write(&t2, "longer-target").unwrap(); + std::fs::set_permissions(&t1, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::set_permissions(&t2, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::os::unix::fs::symlink(&t1, &link).unwrap(); + + let r1 = resolve_probe_path(&link).unwrap(); + assert_eq!(r1, crate::plat::fs::canonicalize(&t1).unwrap()); + assert_eq!(probe_key_for(&r1).unwrap().size, 1); + + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&t2, &link).unwrap(); + let r2 = resolve_probe_path(&link).unwrap(); + assert_eq!(r2, crate::plat::fs::canonicalize(&t2).unwrap()); + assert_eq!(probe_key_for(&r2).unwrap().size, 13); + } + } + + #[cfg(unix)] + #[test] + fn cli_version_output_deduplicates_concurrent_probes_and_invalidates_on_change() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("cli-cache"); + let (cli, log) = (d.join("kicad-cli"), d.join("invocations.log")); + std::fs::write( + &cli, + format!( + "#!/bin/sh\n[ \"$1\" = {NOOP} ] && exit 0\necho $$ >> '{}'\nsleep 0.15\necho 10.0.9\n", + log.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + started(&cli); + + let cli_s = cli.to_string_lossy().into_owned(); + let handles: Vec<_> = (0..6) + .map(|_| { + let s = cli_s.clone(); + std::thread::spawn(move || { + let o = cli_version_output(&s).expect("probe succeeded"); + String::from_utf8_lossy(&o.stdout).trim().to_string() + }) + }) + .collect(); + for h in handles { + assert_eq!(h.join().unwrap(), "10.0.9"); + } + assert_eq!(std::fs::read_to_string(&log).unwrap().lines().count(), 1, "6 concurrent probes spawned kicad-cli only once"); + + let seq = cli_version_output(&cli_s).expect("cached hit"); + assert_eq!(String::from_utf8_lossy(&seq.stdout).trim(), "10.0.9"); + assert_eq!(std::fs::read_to_string(&log).unwrap().lines().count(), 1); + + let prev_mtime = std::fs::metadata(&cli).unwrap().modified().unwrap(); + std::fs::write( + &cli, + format!( + "#!/bin/sh\n[ \"$1\" = {NOOP} ] && exit 0\necho $$ >> '{}'\necho 10.0.10-updated\n", + log.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + let _ = std::fs::File::options().write(true).open(&cli).and_then(|f| f.set_modified(prev_mtime + Duration::from_secs(2))); + started(&cli); + + let updated = cli_version_output(&cli_s).expect("re-probed after file update"); + assert_eq!(String::from_utf8_lossy(&updated.stdout).trim(), "10.0.10-updated"); + assert_eq!(std::fs::read_to_string(&log).unwrap().lines().count(), 2); + } } /// Whether `path`'s project is open in a co-editing KiCad (bp.11 `coedit`): agents write its live documents through IPC at once, diff --git a/native/host/src/plat/unix.rs b/native/host/src/plat/unix.rs index 1970bd5f7b..dd553a0e4f 100644 --- a/native/host/src/plat/unix.rs +++ b/native/host/src/plat/unix.rs @@ -111,6 +111,30 @@ pub mod proc { } /// Whether a process is there (kill 0). pub fn alive(pid: u32) -> bool { pid > 0 && unsafe { libc::kill(pid as i32, 0) } == 0 } + /// State of a direct child PID polled with `WNOWAIT` (leaving the zombie in place so `pid` / its pgid cannot be recycled). + #[allow(dead_code)] // bp-plot includes plat/unix.rs + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum ChildWait { + Running, + Exited, + NotChild, + } + + /// Non-reaping status poll of child `pid`. `ECHILD` returns `NotChild` (distinct from `Exited`, so callers never signal an unowned PID). + #[allow(dead_code)] // bp-plot includes plat/unix.rs + pub fn poll_child_nowait(pid: u32) -> ChildWait { + if pid == 0 || pid > i32::MAX as u32 { return ChildWait::NotChild } + unsafe { + let mut si: libc::siginfo_t = std::mem::zeroed(); + if libc::waitid(libc::P_PID, pid as libc::id_t, &mut si, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT) != 0 { + return match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECHILD) => ChildWait::NotChild, + _ => ChildWait::Running, + }; + } + if si.si_pid() == pid as libc::pid_t { ChildWait::Exited } else { ChildWait::Running } + } + } /// Whether anything is left in the process group a leader made (kill(-pid, 0)), or the leader itself. pub fn group_alive(pid: u32) -> bool { pid > 0 && (unsafe { libc::kill(-(pid as i32), 0) } == 0 || alive(pid)) } /// Whether a process is there, including another user's (kill 0 answering EPERM). diff --git a/native/host/src/proc.rs b/native/host/src/proc.rs index 9fc9fec8f1..2a864257b2 100644 --- a/native/host/src/proc.rs +++ b/native/host/src/proc.rs @@ -178,24 +178,50 @@ pub fn tokio_cmd_in>(kind: Kind, program: S, wrap: Option/kicad_common.json` with a non-empty `api.interpreter_path` and `api.enable_server: false`, +/// and `env()` sets `KICAD_INHIBIT_SETTINGS_WRITES=1`: Backplane `bp.6`-`bp.13.2` and stock KiCad skip `PYTHON_MANAGER::FindPythonInterpreter()` +/// (which runs `wxExecute("which -a python3", wxEXEC_SYNC)` and hung probes on macOS, #1160) and `ReloadPlugins()`, and builds honoring +/// `KICAD_INHIBIT_SETTINGS_WRITES` skip settings writeback too. pub struct ProbeHome(std::path::PathBuf); impl ProbeHome { pub fn new() -> Self { static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let d = std::env::temp_dir().join(format!("bp-kicad-probe-{}-{n}", std::process::id())); - let _ = std::fs::create_dir_all(&d); + if let Err(e) = std::fs::create_dir_all(&d) { + eprintln!("kicad: could not create probe home {}: {e}", d.display()); + return ProbeHome(d); + } + for (ver, schema) in [("10.99", 7u32), ("10.0", 6), ("9.0", 3), ("8.0", 3)] { + let sub = d.join(ver); + if let Err(e) = std::fs::create_dir_all(&sub) { + eprintln!("kicad: could not create probe settings folder {}: {e}", sub.display()); + continue; + } + let file = sub.join("kicad_common.json"); + let body = format!(r#"{{"api":{{"enable_server":false,"interpreter_path":"/nonexistent/bp-probe-python"}},"meta":{{"filename":"kicad_common.json","version":{schema}}}}}"#); + if let Err(e) = std::fs::write(&file, body) { + eprintln!("kicad: could not seed probe settings {}: {e}", file.display()); + } + } ProbeHome(d) } pub fn path(&self) -> &std::path::Path { &self.0 } /// What a probed KiCad is given: its settings (`KICAD_CONFIG_HOME`), and the cache and documents folders KiCad makes at every start /// (PATHS::EnsureUserPathsExist: `~/.cache/kicad/`, `~/.local/share/kicad/`, macOS and Windows `Documents/KiCad/`), - /// all in this throwaway folder: a probe leaves nothing in the person's home (#1204). - pub fn env(&self) -> [(&'static str, std::path::PathBuf); 3] { - [("KICAD_CONFIG_HOME", self.0.clone()), ("KICAD_CACHE_HOME", self.0.join("cache")), ("KICAD_DOCUMENTS_HOME", self.0.join("documents"))] + /// all in this throwaway folder, plus `KICAD_INHIBIT_SETTINGS_WRITES=1`: a probe leaves nothing in the person's home (#1204). + pub fn env(&self) -> [(&'static str, std::ffi::OsString); 4] { + [ + ("KICAD_CONFIG_HOME", self.0.as_os_str().to_os_string()), + ("KICAD_CACHE_HOME", self.0.join("cache").into_os_string()), + ("KICAD_DOCUMENTS_HOME", self.0.join("documents").into_os_string()), + ("KICAD_INHIBIT_SETTINGS_WRITES", std::ffi::OsString::from("1")), + ] } } impl Drop for ProbeHome { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } @@ -205,30 +231,246 @@ pub fn kicad_probe>(cli: S) -> (std::process::Command, ProbeHome } /// How long a KiCad probe may run. A `--version` takes a few seconds; on macOS (#1160) some never exit: KiCad's start-up runs Python to /// find its interpreter (PYTHON_MANAGER::FindPythonInterpreter → wxExecute) and misses that child's exit, so the probe waits forever, -/// ignoring SIGTERM, and they piled up under the hub (42 in two hours). Past this it is killed (SIGKILL) and reaped. +/// ignoring SIGTERM, and they piled up under the hub (42 in two hours). Past this its process group is killed (SIGKILL) and reaped. #[allow(dead_code)] // bp-plot includes this file -pub const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(20); -/// Run a probe `c` (stdin and stderr on /dev/null, stdout captured) for at most `limit`: its output when it exited in time; None when it -/// could not start or ran over (then it is killed and reaped, and the hub's log says so). Its stdout is read on a thread of its own, so a -/// grandchild still holding the pipe after the kill never holds the caller. +pub const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(15); + #[allow(dead_code)] // bp-plot includes this file -pub fn probe_output(mut c: std::process::Command, limit: std::time::Duration) -> Option { - use std::io::Read; - let mut child = c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).spawn().ok()?; - let mut out = child.stdout.take()?; +#[derive(Debug)] +pub enum ProbeError { + Spawn(std::io::Error), + Timeout, +} + +#[allow(dead_code)] // bp-plot includes this file +fn drain_pipe(pipe: Option) -> std::sync::mpsc::Receiver> { let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { let mut b = vec![]; let _ = out.read_to_end(&mut b); let _ = tx.send(b); }); - let end = std::time::Instant::now() + limit; - loop { - match child.try_wait() { - Ok(Some(status)) => { let stdout = rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default(); return Some(std::process::Output { status, stdout, stderr: vec![] }) } - Ok(None) if std::time::Instant::now() < end => std::thread::sleep(std::time::Duration::from_millis(25)), - _ => { let pid = child.id(); let _ = child.kill(); let _ = child.wait(); - eprintln!("kicad: a probe ({:?} {:?}, pid {pid}) ran over {} s and was killed", c.get_program(), c.get_args().collect::>(), limit.as_secs()); - return None } + std::thread::spawn(move || { + let mut b = vec![]; + if let Some(mut r) = pipe { let _ = r.read_to_end(&mut b); } + let _ = tx.send(b); + }); + rx +} + +#[allow(dead_code)] // bp-plot includes this file +fn poll_pipe(slot: &mut Option>, rx: &std::sync::mpsc::Receiver>) { + if slot.is_none() { + match rx.try_recv() { + Ok(b) => *slot = Some(b), + Err(std::sync::mpsc::TryRecvError::Disconnected) => *slot = Some(vec![]), + Err(std::sync::mpsc::TryRecvError::Empty) => {} } } } + +#[allow(dead_code)] // bp-plot includes this file +#[cfg(unix)] +fn kill_and_reap_group( + child: &mut std::process::Child, + pid: u32, + stdout_done: &mut Option>, + stderr_done: &mut Option>, + rx_out: &std::sync::mpsc::Receiver>, + rx_err: &std::sync::mpsc::Receiver>, + cleanup_deadline: Option, +) { + use crate::plat::proc::ChildWait; + if crate::plat::proc::poll_child_nowait(pid) == ChildWait::NotChild { + let _ = child.wait(); + return; + } + crate::plat::proc::kill_group(pid, crate::plat::proc::TERM); + crate::plat::proc::kill(pid, crate::plat::proc::TERM); + let mut grace = std::time::Instant::now() + std::time::Duration::from_millis(200); + if let Some(dl) = cleanup_deadline { + grace = grace.min(dl); + } + while std::time::Instant::now() < grace { + poll_pipe(stdout_done, rx_out); + poll_pipe(stderr_done, rx_err); + match crate::plat::proc::poll_child_nowait(pid) { + ChildWait::Exited if stdout_done.is_some() && stderr_done.is_some() => break, + ChildWait::NotChild => break, + _ => { + let step = std::time::Duration::from_millis(20).min(grace.saturating_duration_since(std::time::Instant::now())); + if !step.is_zero() { + std::thread::sleep(step); + } + } + } + } + if crate::plat::proc::poll_child_nowait(pid) != ChildWait::NotChild { + crate::plat::proc::kill_group(pid, crate::plat::proc::KILL); + let _ = child.kill(); + } + let _ = child.wait(); +} + +#[allow(dead_code)] // bp-plot includes this file +#[cfg(not(unix))] +fn kill_and_reap_group( + child: &mut std::process::Child, + pid: u32, + _stdout_done: &mut Option>, + _stderr_done: &mut Option>, + _rx_out: &std::sync::mpsc::Receiver>, + _rx_err: &std::sync::mpsc::Receiver>, + _cleanup_deadline: Option, +) { + crate::plat::proc::kill_group(pid, crate::plat::proc::KILL); + let _ = child.kill(); + let _ = child.wait(); +} + +/// Run a probe `c` in its own process group/job (stdin on /dev/null, stdout and stderr captured) until `end`, capping any post-timeout +/// `SIGTERM` grace to `cleanup_deadline` when provided: returns `Ok(Output)` when BOTH the child exited and stdout/stderr reached EOF by +/// `end`, `Err(ProbeError::Spawn(_))` when it could not start or poll failed, or `Err(ProbeError::Timeout)` when it or a descendant ran past +/// `end` (then the entire process group/job is killed and the child is reaped before returning). On Unix, the child is polled non-reapingly +/// via `WNOWAIT` until both pipes close or cleanup finishes, keeping its PID/PGID reserved so `kill_group` never signals a recycled PID. +#[allow(dead_code)] // bp-plot includes this file +pub fn probe_output_until( + mut c: std::process::Command, + end: std::time::Instant, + cleanup_deadline: Option, + log_limit: std::time::Duration, +) -> Result { + if std::time::Instant::now() >= end { + return Err(ProbeError::Timeout); + } + crate::plat::proc::own_group(&mut c); + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let mut tries = 0u32; + let mut child = loop { + if std::time::Instant::now() >= end { + return Err(ProbeError::Timeout); + } + match c.spawn() { + Err(e) if e.raw_os_error() == Some(crate::plat::errno::ETXTBSY) && tries < 40 => { + let Some(rem) = end.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else { + return Err(ProbeError::Timeout); + }; + tries += 1; + std::thread::sleep(std::time::Duration::from_millis(25).min(rem)); + } + Err(e) => return Err(ProbeError::Spawn(e)), + Ok(ch) => break ch, + } + }; + let pid = child.id(); + // Best-effort Job Object assignment on Windows (std::process::Command does not expose the primary thread handle for CREATE_SUSPENDED, + // matching the rest of plat/windows.rs); timeout cleanup also falls back to child.kill(). + crate::plat::proc::adopt(pid, false); + let rx_out = drain_pipe(child.stdout.take()); + let rx_err = drain_pipe(child.stderr.take()); + let mut stdout_done: Option> = None; + let mut stderr_done: Option> = None; + let timeout_err = |child: &mut std::process::Child, stdout_done: &mut Option>, stderr_done: &mut Option>| -> Result { + kill_and_reap_group(child, pid, stdout_done, stderr_done, &rx_out, &rx_err, cleanup_deadline); + eprintln!("kicad: a probe ({:?} {:?}, pid {pid}) ran over {} s and was killed", c.get_program(), c.get_args().collect::>(), log_limit.as_secs()); + Err(ProbeError::Timeout) + }; + + #[cfg(unix)] + { + use crate::plat::proc::ChildWait; + loop { + if std::time::Instant::now() >= end { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + poll_pipe(&mut stdout_done, &rx_out); + poll_pipe(&mut stderr_done, &rx_err); + match crate::plat::proc::poll_child_nowait(pid) { + ChildWait::Exited if stdout_done.is_some() && stderr_done.is_some() => { + if std::time::Instant::now() >= end { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + return match child.wait() { + Ok(status) => Ok(std::process::Output { + status, + stdout: stdout_done.unwrap_or_default(), + stderr: stderr_done.unwrap_or_default(), + }), + Err(e) => Err(ProbeError::Spawn(e)), + }; + } + ChildWait::NotChild => { + if std::time::Instant::now() >= end { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + return match child.wait() { + Ok(status) => Ok(std::process::Output { + status, + stdout: stdout_done.unwrap_or_default(), + stderr: stderr_done.unwrap_or_default(), + }), + Err(e) => Err(ProbeError::Spawn(e)), + }; + } + ChildWait::Running | ChildWait::Exited => { + if let Some(rem) = end.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) { + std::thread::sleep(std::time::Duration::from_millis(10).min(rem)); + } else { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + } + } + } + } + + #[cfg(not(unix))] + { + let mut exited: Option = None; + loop { + if std::time::Instant::now() >= end { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + poll_pipe(&mut stdout_done, &rx_out); + poll_pipe(&mut stderr_done, &rx_err); + if exited.is_none() { + match child.try_wait() { + Ok(Some(st)) => exited = Some(st), + Ok(None) => {} + Err(e) => { + kill_and_reap_group(&mut child, pid, &mut stdout_done, &mut stderr_done, &rx_out, &rx_err, cleanup_deadline); + return Err(ProbeError::Spawn(e)); + } + } + } + if let (Some(status), Some(stdout), Some(stderr)) = (exited, stdout_done.as_ref(), stderr_done.as_ref()) { + if std::time::Instant::now() >= end { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + return Ok(std::process::Output { status, stdout: stdout.clone(), stderr: stderr.clone() }); + } + if let Some(rem) = end.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) { + std::thread::sleep(std::time::Duration::from_millis(10).min(rem)); + } else { + return timeout_err(&mut child, &mut stdout_done, &mut stderr_done); + } + } + } +} + +/// Run a probe `c` in its own process group/job (stdin on /dev/null, stdout and stderr captured) for at most `limit`: +/// returns `Ok(Output)` when BOTH the child exited and stdout/stderr reached EOF within `limit`, `Err(ProbeError::Spawn(_))` when it +/// could not start or poll failed, or `Err(ProbeError::Timeout)` when either the child or any pipe-holding descendant ran past `limit` +/// (then the entire process group/job is killed, the child is always reaped before returning, and the hub's log says so). +#[allow(dead_code)] // bp-plot includes this file +pub fn probe_output_result(c: std::process::Command, limit: std::time::Duration) -> Result { + probe_output_until(c, std::time::Instant::now() + limit, None, limit) +} + +#[cfg(all(test, unix))] +#[allow(dead_code)] // bp-plot includes this file +pub(crate) fn is_live_non_zombie(pid: &str) -> bool { tests::is_live_non_zombie(pid) } + +/// Run a probe `c` (stdin on /dev/null, stdout/stderr captured) for at most `limit`: `Some(output)` when it exited in time, None when +/// it could not start or ran over (then its process group is killed and the child is reaped). +#[allow(dead_code)] // bp-plot includes this file +pub fn probe_output(c: std::process::Command, limit: std::time::Duration) -> Option { + probe_output_result(c, limit).ok() +} /// `kicad_probe` as a tokio command. #[allow(dead_code)] // bp-plot includes this file pub fn kicad_probe_tokio>(cli: S) -> (tokio::process::Command, ProbeHome) { @@ -569,4 +811,217 @@ mod tests { } assert!(bad.is_empty(), "an outbound socket outside the allowlist (add it to proc.rs's list with a copy-guard): {bad:?}"); } + + #[test] + fn probe_home_seeds_python_interpreter_and_inhibits_writes() { + let h = ProbeHome::new(); + let root = h.path().to_path_buf(); + for (ver, schema) in [("10.99", 7u64), ("10.0", 6), ("9.0", 3), ("8.0", 3)] { + let raw = std::fs::read_to_string(root.join(ver).join("kicad_common.json")).unwrap(); + let v: serde_json::Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(v["api"]["enable_server"], serde_json::json!(false), "{ver}"); + assert!(v["api"]["interpreter_path"].as_str().is_some_and(|s| !s.is_empty()), "{ver}"); + assert_eq!(v["meta"]["filename"], "kicad_common.json", "{ver}"); + assert_eq!(v["meta"]["version"], serde_json::json!(schema), "{ver}"); + } + let env = h.env(); + assert!(env.iter().any(|(k, v)| *k == "KICAD_CONFIG_HOME" && *v == root.as_os_str())); + assert!(env.iter().any(|(k, v)| *k == "KICAD_CACHE_HOME" && *v == root.join("cache").as_os_str())); + assert!(env.iter().any(|(k, v)| *k == "KICAD_DOCUMENTS_HOME" && *v == root.join("documents").as_os_str())); + assert!(env.iter().any(|(k, v)| *k == "KICAD_INHIBIT_SETTINGS_WRITES" && v == "1")); + drop(h); + assert!(!root.exists(), "ProbeHome drop removes throwaway folder"); + } + + #[cfg(unix)] + fn warm_script(cli: &std::path::Path) { + let t = std::time::Instant::now(); + loop { + match std::process::Command::new(cli).arg("--bp-test-noop").status() { + Err(e) if e.raw_os_error() == Some(crate::plat::errno::ETXTBSY) && t.elapsed() < std::time::Duration::from_secs(30) => { + std::thread::sleep(std::time::Duration::from_millis(25)); + } + _ => break, + } + } + } + + #[cfg(unix)] + fn pid_signal_ok(pid: &str) -> bool { + std::process::Command::new("kill") + .args(["-0", pid]) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + } + + #[cfg(unix)] + pub(super) fn is_live_non_zombie(pid: &str) -> bool { + if !pid_signal_ok(pid) { return false; } + #[cfg(target_os = "linux")] + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + if let Some((_, rest)) = stat.rsplit_once(')') { + if rest.trim_start().starts_with('Z') { return false; } + } + } + #[cfg(target_os = "macos")] + if let Ok(o) = std::process::Command::new("ps").args(["-o", "state=", "-p", pid]).output() { + if String::from_utf8_lossy(&o.stdout).trim().starts_with('Z') { return false; } + } + true + } + + #[cfg(unix)] + #[test] + fn probe_output_result_captures_stdout_and_stderr() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("probe-out"); + let cli = d.join("kicad-cli"); + std::fs::write(&cli, "#!/bin/sh\necho out-line\necho err-line >&2\n").unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + // Do not pre-warm here so probe_output_result's built-in ETXTBSY retry is exercised directly. + let mut c = std_cmd(Kind::Local, &cli); + c.arg("--version"); + let out = probe_output_result(c, std::time::Duration::from_secs(5)).expect("ok"); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "out-line"); + assert_eq!(String::from_utf8_lossy(&out.stderr).trim(), "err-line"); + + let missing = std_cmd(Kind::Local, d.join("missing-kicad-cli")); + assert!(matches!(probe_output_result(missing, std::time::Duration::from_secs(2)), Err(ProbeError::Spawn(_)))); + } + + #[cfg(unix)] + #[test] + fn probe_output_kills_sigterm_ignoring_process_group_and_reaps_child() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("probe-kill-grp"); + let (cli, parent_pid_file, gc_pid_file) = (d.join("kicad-cli"), d.join("parent.pid"), d.join("gc.pid")); + std::fs::write( + &cli, + format!( + "#!/bin/sh\n[ \"$1\" = \"--bp-test-noop\" ] && exit 0\ntrap '' TERM\nsh -c \"trap '' TERM; echo \\$\\$ > '{}'; exec sleep 60\" &\nwhile [ ! -s '{}' ]; do sleep 0.01; done\necho $$ > '{}'\nexec sleep 60\n", + gc_pid_file.display(), + gc_pid_file.display(), + parent_pid_file.display(), + ), + ) + .unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + warm_script(&cli); + + let mut c = std_cmd(Kind::Local, &cli); + c.arg("--version"); + let at = std::time::Instant::now(); + let res = probe_output_result(c, std::time::Duration::from_secs(2)); + assert!(matches!(res, Err(ProbeError::Timeout)), "{res:?}"); + assert!(at.elapsed() < std::time::Duration::from_secs(10), "bounded: {:?}", at.elapsed()); + + let ppid = std::fs::read_to_string(&parent_pid_file).unwrap().trim().to_string(); + let gpid = std::fs::read_to_string(&gc_pid_file).unwrap().trim().to_string(); + assert!(!ppid.is_empty() && !gpid.is_empty(), "ppid={ppid:?} gpid={gpid:?}"); + assert!(!pid_signal_ok(&ppid), "direct child pid {ppid} was synchronously killed and reaped"); + let gc_deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while is_live_non_zombie(&gpid) && std::time::Instant::now() < gc_deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(!is_live_non_zombie(&gpid), "grandchild pid {gpid} in the probe's process group was terminated"); + } + + #[cfg(unix)] + #[test] + fn probe_output_kills_descendant_holding_pipes_after_leader_exits() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("probe-pipe-hold"); + let (cli, parent_pid_file, gc_pid_file) = (d.join("kicad-cli"), d.join("parent.pid"), d.join("gc.pid")); + std::fs::write( + &cli, + format!( + "#!/bin/sh\n[ \"$1\" = \"--bp-test-noop\" ] && exit 0\nsh -c \"trap '' TERM; echo \\$\\$ > '{}'; exec sleep 60\" &\nwhile [ ! -s '{}' ]; do sleep 0.01; done\necho $$ > '{}'\necho 10.99.0\nexit 0\n", + gc_pid_file.display(), + gc_pid_file.display(), + parent_pid_file.display(), + ), + ) + .unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + warm_script(&cli); + + let mut c = std_cmd(Kind::Local, &cli); + c.arg("--version"); + let at = std::time::Instant::now(); + let res = probe_output_result(c, std::time::Duration::from_secs(2)); + assert!(matches!(res, Err(ProbeError::Timeout)), "descendant holding stdout pipe must time out cleanly: {res:?}"); + assert!(at.elapsed() < std::time::Duration::from_secs(10), "bounded: {:?}", at.elapsed()); + + let ppid = std::fs::read_to_string(&parent_pid_file).unwrap().trim().to_string(); + let gpid = std::fs::read_to_string(&gc_pid_file).unwrap().trim().to_string(); + assert!(!ppid.is_empty() && !gpid.is_empty(), "ppid={ppid:?} gpid={gpid:?}"); + assert!(!pid_signal_ok(&ppid), "direct leader pid {ppid} was reaped after cleanup"); + let gc_deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while is_live_non_zombie(&gpid) && std::time::Instant::now() < gc_deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(!is_live_non_zombie(&gpid), "pipe-holding descendant pid {gpid} was killed"); + } + + #[cfg(unix)] + #[test] + fn probe_output_kills_stubborn_grandchild_when_leader_exits_on_sigterm() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("probe-leader-term"); + let (cli, parent_pid_file, gc_pid_file) = (d.join("kicad-cli"), d.join("parent.pid"), d.join("gc.pid")); + std::fs::write( + &cli, + format!( + "#!/bin/sh\n[ \"$1\" = \"--bp-test-noop\" ] && exit 0\nsh -c \"trap '' TERM; echo \\$\\$ > '{}'; exec sleep 60\" &\nwhile [ ! -s '{}' ]; do sleep 0.01; done\necho $$ > '{}'\nexec sleep 60\n", + gc_pid_file.display(), + gc_pid_file.display(), + parent_pid_file.display(), + ), + ) + .unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + warm_script(&cli); + + let mut c = std_cmd(Kind::Local, &cli); + c.arg("--version"); + let res = probe_output_result(c, std::time::Duration::from_secs(2)); + assert!(matches!(res, Err(ProbeError::Timeout)), "{res:?}"); + + let ppid = std::fs::read_to_string(&parent_pid_file).unwrap().trim().to_string(); + let gpid = std::fs::read_to_string(&gc_pid_file).unwrap().trim().to_string(); + assert!(!ppid.is_empty() && !gpid.is_empty(), "ppid={ppid:?} gpid={gpid:?}"); + assert!(!pid_signal_ok(&ppid), "direct leader pid {ppid} was reaped"); + let gc_deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while is_live_non_zombie(&gpid) && std::time::Instant::now() < gc_deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(!is_live_non_zombie(&gpid), "SIGKILL still swept grandchild pid {gpid} after leader exited on SIGTERM"); + } + + #[cfg(unix)] + #[test] + fn probe_output_until_enforces_deadline_before_spawn_and_completion() { + use std::os::unix::fs::PermissionsExt; + let d = crate::plat::tmp::dir("probe-dl"); + let (early_cli, marker, late_cli) = (d.join("early"), d.join("ran"), d.join("late")); + std::fs::write(&early_cli, format!("#!/bin/sh\n: > '{}'\necho ok\n", marker.display())).unwrap(); + std::fs::set_permissions(&early_cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let expired = std::time::Instant::now(); + let res_expired = probe_output_until(std_cmd(Kind::Local, &early_cli), expired, Some(expired), std::time::Duration::from_secs(1)); + assert!(matches!(res_expired, Err(ProbeError::Timeout)), "{res_expired:?}"); + assert!(!marker.exists(), "probe must not execute after deadline"); + + std::fs::write(&late_cli, "#!/bin/sh\n[ \"$1\" = \"--bp-test-noop\" ] && exit 0\nsleep 0.12\necho late\n").unwrap(); + std::fs::set_permissions(&late_cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + warm_script(&late_cli); + + let mut c = std_cmd(Kind::Local, &late_cli); + c.arg("--version"); + let end = std::time::Instant::now() + std::time::Duration::from_millis(25); + let res_late = probe_output_until(c, end, Some(end), std::time::Duration::from_millis(25)); + assert!(matches!(res_late, Err(ProbeError::Timeout)), "late completion must time out: {res_late:?}"); + } } diff --git a/native/host/src/review/stockdrc.rs b/native/host/src/review/stockdrc.rs index 41a890a03e..89a72b9dd4 100644 --- a/native/host/src/review/stockdrc.rs +++ b/native/host/src/review/stockdrc.rs @@ -54,10 +54,9 @@ pub async fn find(runtime_cli: &str) -> Option<(PathBuf, String)> { let mut seen = std::collections::HashSet::new(); for c in candidates() { if !c.is_file() || ours(&c, runtime_cli) || !seen.insert(std::fs::canonicalize(&c).unwrap_or(c.clone())) { continue } - // a probe: the stock KiCad's settings, cache and documents go to a throwaway folder, never the person's (#1204) - let (mut p, _home) = crate::proc::kicad_probe_tokio(&c); - let o = tokio::time::timeout(Duration::from_secs(20), p.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true).output()).await; - if let Ok(Ok(o)) = o { if let Some(v) = stock_version(&String::from_utf8_lossy(&o.stdout)) { return Some((c, v)) } } + let cli = c.clone(); + let o = tokio::task::spawn_blocking(move || crate::files::kicad::ipc::cli_version_output_path(&cli)).await.ok().flatten(); + if let Some(o) = o.filter(|o| o.status.success()) { if let Some(v) = stock_version(&String::from_utf8_lossy(&o.stdout)) { return Some((c, v)) } } } None } diff --git a/native/host/src/settings/onboard.rs b/native/host/src/settings/onboard.rs index e5c0c8cb52..af9ddbd6e3 100644 --- a/native/host/src/settings/onboard.rs +++ b/native/host/src/settings/onboard.rs @@ -79,17 +79,19 @@ async fn kicad(hub: &Arc, typed: &str) -> Value { let Some(cli) = first_of(typed, &set, "BACKPLANE_KICAD_CLI", pf.kicad_names, places) else { return json!({"path": "", "runs": false}) }; kicad_version(&cli, TIMEOUT).await } -/// The KiCad at `cli` asked its version, as a probe (#1204): KiCad loads, migrates and saves its settings even for `--version`, and one -/// killed at the limit mid-save left `kicad_common.json.kicad-save--0` in the person's settings; its settings, cache and documents -/// folders are a throwaway one (proc::kicad_probe_tokio), removed once it has answered or been killed. +/// The KiCad at `cli` asked its version, via the shared single-flight probe cache (`ipc::cli_version_cached`) with pre-seeded +/// settings (`proc::ProbeHome`, #1204 / #1160) so it never writes the person's KiCad folders or triggers `FindPythonInterpreter`, +/// and any hung process group is killed and reaped on timeout. async fn kicad_version(cli: &Path, limit: Duration) -> Value { + use crate::files::kicad::ipc::{cli_version_cached_path, ProbeOutcome}; let path = cli.to_string_lossy().into_owned(); - let (mut c, _home) = proc::kicad_probe_tokio(cli); - c.arg("--version"); - match output_or_why(c, limit).await { - Ok((0, out, _)) => json!({"path": path, "version": version_of(&out), "runs": true}), - Ok((code, _, err)) => json!({"path": path, "runs": false, "why": why(code, &err)}), - Err(w) => json!({"path": path, "runs": false, "why": w}), + let probe_path = cli.to_path_buf(); + match tokio::task::spawn_blocking(move || cli_version_cached_path(&probe_path, limit, 1)).await { + Ok(ProbeOutcome::Output(o)) if o.status.success() => json!({"path": path, "version": version_of(&String::from_utf8_lossy(&o.stdout)), "runs": true}), + Ok(ProbeOutcome::Output(o)) => json!({"path": path, "runs": false, "why": why(o.status.code().unwrap_or(-1), &String::from_utf8_lossy(&o.stderr))}), + Ok(ProbeOutcome::Timeout { limit: d, .. }) => json!({"path": path, "runs": false, "why": format!("it did not answer within {} s", d.as_secs())}), + Ok(ProbeOutcome::SpawnErr(e)) => json!({"path": path, "runs": false, "why": format!("it did not start: {e}")}), + Err(e) => json!({"path": path, "runs": false, "why": format!("it did not start: {e}")}), } } fn why(code: i32, err: &str) -> String { let l = err.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("").chars().take(120).collect::(); if l.is_empty() { format!("exit code {code}") } else { format!("exit code {code}, {l}") } }