From 541b33a4fbba1e3af5927b468d71b6913a08904d Mon Sep 17 00:00:00 2001 From: Martin Kuntz Jacobsen Date: Tue, 24 Nov 2026 09:14:58 +0100 Subject: [PATCH 1/3] tests: wait on events instead of fixed sleeps in the test harness dx_test_scratch::wait adds bounded waits on real conditions: a path appearing (notify), a lock coming free, a pid exiting (pidfd, kqueue, WaitForSingleObject via dx_os_sys::exit) and a child exiting under a deadline. dx_testing, the process and nested probes, the nested harness and reaper, the lsp session and the maven pin use them in place of sleep-and-poll loops. Long-lived stand-in children block on stdin instead of sleeping. dx_testing::rlocation opens the runfiles manifest once instead of on every call, which made module_extension_srcs_test time out on Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xut2hyBydsMejdwk6QdKus --- cli/os_sys/BUILD.bazel | 3 + cli/os_sys/src/exit.rs | 90 ++++++ cli/os_sys/src/exit_tests.rs | 34 +++ cli/os_sys/src/lib.rs | 4 + cli/os_sys/src/process.rs | 13 + cli/os_sys/src/win32_tests.rs | 9 +- cli/test_scratch/BUILD.bazel | 19 +- cli/test_scratch/src/lib.rs | 82 +++++ cli/test_scratch/src/wait.rs | 102 +++++++ tools/ide/lsp_headless_rust_analyzer_test.rs | 4 +- tools/testing/hermetic/BUILD.bazel | 1 + tools/testing/hermetic/maven_pin.rs | 19 +- tools/testing/lsp/BUILD.bazel | 4 +- tools/testing/lsp/src/lib.rs | 117 ++++--- tools/testing/nested/probe/main.rs | 28 +- tools/testing/nested/src/lib.rs | 303 +++++++++++-------- tools/testing/nested_bazel_harness_test.rs | 11 +- tools/testing/process_probe/BUILD.bazel | 1 + tools/testing/process_probe/probe_test.rs | 46 +-- tools/testing/process_probe/src/main.rs | 18 +- tools/testing/src/lib.rs | 90 +++--- 21 files changed, 670 insertions(+), 328 deletions(-) create mode 100644 cli/os_sys/src/exit.rs create mode 100644 cli/os_sys/src/exit_tests.rs create mode 100644 cli/test_scratch/src/wait.rs diff --git a/cli/os_sys/BUILD.bazel b/cli/os_sys/BUILD.bazel index 7893d863b1..27d654400e 100644 --- a/cli/os_sys/BUILD.bazel +++ b/cli/os_sys/BUILD.bazel @@ -12,6 +12,7 @@ rust_library( srcs = [ "src/console.rs", "src/errno.rs", + "src/exit.rs", "src/fd.rs", "src/fs.rs", "src/job.rs", @@ -44,6 +45,8 @@ rust_test( "src/console.rs", "src/console_tests.rs", "src/errno.rs", + "src/exit.rs", + "src/exit_tests.rs", "src/fd.rs", "src/fs.rs", "src/job.rs", diff --git a/cli/os_sys/src/exit.rs b/cli/os_sys/src/exit.rs new file mode 100644 index 0000000000..1c2227de06 --- /dev/null +++ b/cli/os_sys/src/exit.rs @@ -0,0 +1,90 @@ +#![cfg_attr( + target_os = "macos", + expect(unsafe_code, reason = "rustix exposes kevent only as an unsafe fn") +)] + +use std::io; +use std::time::{Duration, Instant}; + +pub fn wait_gone(pid: u32, limit: Duration) -> io::Result { + let deadline = Instant::now() + limit; + wait_gone_until(pid, deadline) +} + +#[cfg(target_os = "linux")] +fn wait_gone_until(pid: u32, deadline: Instant) -> io::Result { + use rustix::event::{PollFd, PollFlags, Timespec, poll}; + use rustix::io::Errno; + use rustix::process::{Pid, PidfdFlags, pidfd_open}; + let raw = i32::try_from(pid).map_err(io::Error::other)?; + let target = Pid::from_raw(raw).ok_or(io::Error::from(io::ErrorKind::InvalidInput))?; + let fd = match pidfd_open(target, PidfdFlags::empty()) { + Err(Errno::SRCH) => return Ok(true), + opened => opened?, + }; + loop { + let left = Timespec::try_from(deadline.saturating_duration_since(Instant::now())) + .map_err(io::Error::other)?; + let mut fds = [PollFd::new(&fd, PollFlags::IN)]; + match poll(&mut fds, Some(&left)) { + Err(Errno::INTR) => {} + Ok(ready) => return Ok(ready > 0), + Err(error) => return Err(error.into()), + } + } +} + +#[cfg(target_os = "macos")] +fn wait_gone_until(pid: u32, deadline: Instant) -> io::Result { + use rustix::buffer::spare_capacity; + use rustix::event::kqueue::{Event, EventFilter, EventFlags, ProcessEvents, kevent, kqueue}; + use rustix::io::Errno; + use rustix::process::Pid; + let raw = i32::try_from(pid).map_err(io::Error::other)?; + let target = Pid::from_raw(raw).ok_or(io::Error::from(io::ErrorKind::InvalidInput))?; + let queue = kqueue()?; + let exit = Event::new( + EventFilter::Proc { + pid: target, + flags: ProcessEvents::EXIT, + }, + EventFlags::ADD | EventFlags::ONESHOT, + std::ptr::null_mut(), + ); + let mut none: Vec = Vec::new(); + // SAFETY: the change list holds one process filter whose udata is null and never read. + match unsafe { kevent(&queue, &[exit], &mut none, Some(Duration::ZERO)) } { + Err(Errno::SRCH) => return Ok(true), + Err(error) => return Err(error.into()), + Ok(_) => {} + } + loop { + let left = deadline.saturating_duration_since(Instant::now()); + let mut fired: Vec = Vec::with_capacity(1); + // SAFETY: the event list has room for one event and the queue holds only the exit filter. + match unsafe { kevent(&queue, &[], spare_capacity(&mut fired), Some(left)) } { + Err(Errno::INTR) => {} + Ok(count) => return Ok(count > 0), + Err(error) => return Err(error.into()), + } + } +} + +#[cfg(windows)] +fn wait_gone_until(pid: u32, deadline: Instant) -> io::Result { + use std::os::windows::io::AsHandle; + const ERROR_INVALID_PARAMETER: i32 = 87; + let process = match crate::win32::open(pid, crate::win32::Access::Wait) { + Err(error) if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER) => return Ok(true), + opened => opened?, + }; + crate::win32::wait( + process.as_handle(), + Some(deadline.saturating_duration_since(Instant::now())), + ) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +fn wait_gone_until(_pid: u32, _deadline: Instant) -> io::Result { + Err(io::Error::from(io::ErrorKind::Unsupported)) +} diff --git a/cli/os_sys/src/exit_tests.rs b/cli/os_sys/src/exit_tests.rs new file mode 100644 index 0000000000..41b226d273 --- /dev/null +++ b/cli/os_sys/src/exit_tests.rs @@ -0,0 +1,34 @@ +use crate::exit::wait_gone; +use std::io::Read as _; +use std::process::{Command, Stdio}; +use std::time::Duration; + +const CHILD: &str = "DX_OS_SYS_EXIT_CHILD"; + +#[test] +fn holds_until_stdin_closes() { + if std::env::var_os(CHILD).is_some() { + drop(std::io::stdin().read_to_end(&mut Vec::new())); + } +} + +#[test] +fn returns_once_the_process_exits() { + let mut child = Command::new(std::env::current_exe().expect("exe")) + .args(["--exact", "exit_tests::holds_until_stdin_closes"]) + .env(CHILD, "1") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .expect("spawn"); + let pid = child.id(); + assert!(!wait_gone(pid, Duration::ZERO).expect("wait while running")); + drop(child.stdin.take()); + assert!(wait_gone(pid, Duration::from_secs(60)).expect("wait for exit")); + assert!(child.wait().expect("reap").success()); +} + +#[test] +fn a_missing_pid_is_already_gone() { + assert!(wait_gone(0x7fff_fff0, Duration::ZERO).expect("wait")); +} diff --git a/cli/os_sys/src/lib.rs b/cli/os_sys/src/lib.rs index 8121d23ae9..3f31be4abb 100644 --- a/cli/os_sys/src/lib.rs +++ b/cli/os_sys/src/lib.rs @@ -12,6 +12,7 @@ pub const STOP_SIGNALS: [i32; 3] = [2, 15, 1]; pub mod console; #[cfg(unix)] pub mod errno; +pub mod exit; #[cfg(unix)] pub mod fd; #[cfg(any(unix, windows))] @@ -38,6 +39,9 @@ pub mod win32; #[cfg(test)] #[path = "console_tests.rs"] mod console_tests; +#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))] +#[path = "exit_tests.rs"] +mod exit_tests; #[cfg(test)] #[path = "job_object_tests.rs"] mod job_object_tests; diff --git a/cli/os_sys/src/process.rs b/cli/os_sys/src/process.rs index 5824c98b6c..c3be840358 100644 --- a/cli/os_sys/src/process.rs +++ b/cli/os_sys/src/process.rs @@ -99,6 +99,19 @@ pub fn stopped_by(child: i32) -> io::Result> { Ok(status.and_then(|status| status.stopping_signal())) } +pub fn await_stop(child: i32) -> io::Result> { + let status = rustix::process::waitid(WaitId::Pid(pid(child)?), WaitIdOptions::STOPPED)?; + Ok(status.and_then(|status| status.stopping_signal())) +} + +pub fn await_exit_unreaped(child: i32) -> io::Result<()> { + rustix::process::waitid( + WaitId::Pid(pid(child)?), + WaitIdOptions::EXITED | WaitIdOptions::NOWAIT, + )?; + Ok(()) +} + pub fn reap(child: i32) -> io::Result<()> { rustix::process::waitpid(Some(pid(child)?), WaitOptions::empty())?; Ok(()) diff --git a/cli/os_sys/src/win32_tests.rs b/cli/os_sys/src/win32_tests.rs index cd978182f3..11c0337df7 100644 --- a/cli/os_sys/src/win32_tests.rs +++ b/cli/os_sys/src/win32_tests.rs @@ -17,16 +17,19 @@ pub(crate) fn child(code: Option) -> Command { .args(["--exact", "win32_tests::child_main"]) .env( CHILD, - code.map_or_else(|| "sleep".to_owned(), |code| code.to_string()), + code.map_or_else(|| "block".to_owned(), |code| code.to_string()), ) - .stdin(Stdio::null()); + .stdin(code.map_or_else(Stdio::piped, |_| Stdio::null())); command } #[test] fn child_main() { match std::env::var(CHILD).as_deref() { - Ok("sleep") => std::thread::sleep(Duration::from_secs(30)), + Ok("block") => drop(std::io::Read::read_to_end( + &mut std::io::stdin(), + &mut Vec::new(), + )), Ok(code) => std::process::exit(code.parse().expect("exit code")), Err(_) => {} } diff --git a/cli/test_scratch/BUILD.bazel b/cli/test_scratch/BUILD.bazel index 6ddc29fc38..3dbd9b1b9a 100644 --- a/cli/test_scratch/BUILD.bazel +++ b/cli/test_scratch/BUILD.bazel @@ -8,7 +8,10 @@ package(default_visibility = VIS_CLI) rust_library( name = "dx_test_scratch", testonly = True, - srcs = ["src/lib.rs"], + srcs = [ + "src/lib.rs", + "src/wait.rs", + ], aliases = aliases( package_name = "cli/dx_test_scratch", normal = True, @@ -20,11 +23,10 @@ rust_library( package_name = "cli/dx_test_scratch", normal = True, ) + [ + "//cli/os_sys:dx_os_sys", "//cli/process:dx_process", - ] + select({ - "@platforms//os:windows": [], - "//conditions:default": ["//cli/os_sys:dx_os_sys"], - }), + "@crates//:notify", + ], ) rust_test( @@ -43,11 +45,10 @@ rust_test( normal = True, normal_dev = True, ) + [ + "//cli/os_sys:dx_os_sys", "//cli/process:dx_process", - ] + select({ - "@platforms//os:windows": [], - "//conditions:default": ["//cli/os_sys:dx_os_sys"], - }), + "@crates//:notify", + ], ) real_source_target( diff --git a/cli/test_scratch/src/lib.rs b/cli/test_scratch/src/lib.rs index dcdc82b2c1..5beb7514b1 100644 --- a/cli/test_scratch/src/lib.rs +++ b/cli/test_scratch/src/lib.rs @@ -11,6 +11,8 @@ use std::path::{Component, Path}; use std::process::Command; pub use tempfile::TempDir; +pub mod wait; + const PREFIX_KEEP: usize = 24; fn fnv1a(bytes: &[u8]) -> u64 { @@ -479,4 +481,84 @@ mod tests { let relative = scratch_in(Path::new("."), "dx-rel-").unwrap(); assert!(relative.path().is_absolute(), "{:?}", relative.path()); } + + const HOLD: &str = "DX_TEST_SCRATCH_HOLD"; + + #[test] + fn holds_until_stdin_closes() { + if std::env::var_os(HOLD).is_some() { + drop(std::io::Read::read_to_end( + &mut std::io::stdin(), + &mut Vec::new(), + )); + } + } + + fn holder() -> std::process::Child { + Command::new(std::env::current_exe().expect("exe")) + .args(["--exact", "tests::holds_until_stdin_closes"]) + .env(HOLD, "1") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .expect("spawn") + } + + const LONG: std::time::Duration = std::time::Duration::from_secs(60); + + #[test] + fn within_returns_the_work_or_names_what_never_finished() { + assert_eq!(wait::within("one", LONG, || 1), Ok(1)); + let (_keep, never) = std::sync::mpsc::channel::<()>(); + let error = wait::within("the never", std::time::Duration::ZERO, move || never.recv()) + .expect_err("never finishes"); + assert!(error.contains("the never did not happen"), "{error}"); + } + + #[test] + fn path_appears_sees_a_file_created_below_a_missing_directory() { + let dir = scratch("dx-wait-path-").unwrap(); + let path = dir.path().join("later/deeper/file"); + let error = wait::path_appears(&path, std::time::Duration::ZERO).expect_err("absent"); + assert!(error.contains("appearing did not happen"), "{error}"); + let root = dir.path().to_path_buf(); + let writer = std::thread::spawn(move || write(&root, "later/deeper/file", "x")); + wait::path_appears(&path, LONG).unwrap(); + writer.join().expect("writer").unwrap(); + } + + #[test] + fn lock_free_waits_for_the_holder_to_let_go() { + let dir = scratch("dx-wait-lock-").unwrap(); + let path = dir.path().join("alive.lock"); + let held = std::fs::File::create(&path).unwrap(); + held.lock().unwrap(); + let error = wait::lock_free(&path, std::time::Duration::ZERO).expect_err("held"); + assert!(error.contains("coming free did not happen"), "{error}"); + drop(held); + wait::lock_free(&path, LONG).unwrap(); + } + + #[test] + fn pid_gone_and_exit_within_follow_a_child_to_its_end() { + let mut child = holder(); + let pid = child.id(); + assert!(wait::pid_gone(pid, std::time::Duration::ZERO).is_err()); + drop(child.stdin.take()); + wait::pid_gone(pid, LONG).unwrap(); + assert!(matches!( + wait::exit_within(child, LONG).unwrap(), + wait::Exit::Exited(status) if status.success() + )); + } + + #[test] + fn exit_within_kills_a_child_that_outlives_the_limit() { + let mut child = holder(); + let _stdin = child.stdin.take(); + assert!(matches!( + wait::exit_within(child, std::time::Duration::ZERO).unwrap(), + wait::Exit::Killed(status) if !status.success() + )); + } } diff --git a/cli/test_scratch/src/wait.rs b/cli/test_scratch/src/wait.rs new file mode 100644 index 0000000000..ee3dd3eb53 --- /dev/null +++ b/cli/test_scratch/src/wait.rs @@ -0,0 +1,102 @@ +use std::path::Path; +use std::process::{Child, ExitStatus}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::time::{Duration, Instant}; + +pub fn within( + what: &str, + limit: Duration, + work: impl FnOnce() -> T + Send + 'static, +) -> Result { + let (sender, receiver) = mpsc::sync_channel(1); + std::thread::spawn(move || drop(sender.send(work()))); + receiver.recv_timeout(limit).map_err(|error| match error { + RecvTimeoutError::Timeout => format!("{what} did not happen within {limit:?}"), + RecvTimeoutError::Disconnected => format!("{what}: the waiting thread panicked"), + }) +} + +pub fn path_appears(path: &Path, limit: Duration) -> Result<(), String> { + let what = format!("{} appearing", path.display()); + watch_until(path, &what, limit, || path.exists()) +} + +pub fn watch_until( + path: &Path, + what: &str, + limit: Duration, + mut done: impl FnMut() -> bool, +) -> Result<(), String> { + use notify::{RecursiveMode, Watcher as _}; + let deadline = Instant::now() + limit; + let parent = path + .parent() + .ok_or_else(|| format!("{} has no parent to watch", path.display()))?; + let watched = parent + .ancestors() + .find(|dir| dir.is_dir()) + .ok_or_else(|| format!("no ancestor of {} exists", path.display()))?; + let mode = if watched == parent { + RecursiveMode::NonRecursive + } else { + RecursiveMode::Recursive + }; + let (sender, events) = mpsc::channel(); + let mut watcher = notify::recommended_watcher(sender) + .map_err(|error| format!("watch {}: {error}", watched.display()))?; + watcher + .watch(watched, mode) + .map_err(|error| format!("watch {}: {error}", watched.display()))?; + while !done() { + match events.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(_) => {} + Err(RecvTimeoutError::Timeout) => { + return Err(format!("{what} did not happen within {limit:?}")); + } + Err(RecvTimeoutError::Disconnected) => { + return Err(format!("the watcher on {} stopped", watched.display())); + } + } + } + Ok(()) +} + +pub fn lock_free(path: &Path, limit: Duration) -> Result<(), String> { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(path) + .map_err(|error| format!("open {}: {error}", path.display()))?; + let what = format!("the lock on {} coming free", path.display()); + within(&what, limit, move || file.lock())? + .map_err(|error| format!("lock {}: {error}", path.display())) +} + +pub fn pid_gone(pid: u32, limit: Duration) -> Result<(), String> { + match dx_os_sys::exit::wait_gone(pid, limit) { + Ok(true) => Ok(()), + Ok(false) => Err(format!("process {pid} still runs after {limit:?}")), + Err(error) => Err(format!("wait for process {pid}: {error}")), + } +} + +pub fn child_exits(child: &mut Child, limit: Duration) -> Result { + pid_gone(child.id(), limit)?; + child + .wait() + .map_err(|error| format!("reap process {}: {error}", child.id())) +} + +#[derive(Debug)] +pub enum Exit { + Exited(ExitStatus), + Killed(ExitStatus), +} + +pub fn exit_within(mut child: Child, limit: Duration) -> std::io::Result { + if dx_os_sys::exit::wait_gone(child.id(), limit)? { + return child.wait().map(Exit::Exited); + } + child.kill()?; + child.wait().map(Exit::Killed) +} diff --git a/tools/ide/lsp_headless_rust_analyzer_test.rs b/tools/ide/lsp_headless_rust_analyzer_test.rs index 7588b5b0bf..ddd5f2bdc6 100644 --- a/tools/ide/lsp_headless_rust_analyzer_test.rs +++ b/tools/ide/lsp_headless_rust_analyzer_test.rs @@ -102,7 +102,7 @@ fn rust_project_definition_resolves_through_selected_features() { }), ) .expect("rust-analyzer opens the fixture"); - let result = poll_definition( + let result = quiescent_definition( &mut session, &fixture.lib_uri, &fixture.lib_text, @@ -175,7 +175,7 @@ fn rust_project_hides_feature_gated_items_without_the_feature() { }), ) .expect("rust-analyzer opens the fixture"); - let result = poll_definition( + let result = quiescent_definition( &mut session, &fixture.lib_uri, &fixture.lib_text, diff --git a/tools/testing/hermetic/BUILD.bazel b/tools/testing/hermetic/BUILD.bazel index ae02e678ba..341d734680 100644 --- a/tools/testing/hermetic/BUILD.bazel +++ b/tools/testing/hermetic/BUILD.bazel @@ -857,6 +857,7 @@ rust_binary( deps = [ ":hermetic", "//cli/families:dx_families", + "//cli/test_scratch:dx_test_scratch", "//tools/testing:dx_testing", "//tools/testing/nested:dx_nested", ], diff --git a/tools/testing/hermetic/maven_pin.rs b/tools/testing/hermetic/maven_pin.rs index 3407c0b821..f39c628a85 100644 --- a/tools/testing/hermetic/maven_pin.rs +++ b/tools/testing/hermetic/maven_pin.rs @@ -1,7 +1,7 @@ use std::fs::File; use std::path::{Path, PathBuf}; use std::process::{ExitCode, Stdio}; -use std::time::{Duration, Instant}; +use std::time::Duration; const PIN_DEADLINE: Duration = Duration::from_mins(30); @@ -47,24 +47,17 @@ fn pin(case: &dx_nested::Case, name: &str) -> Result { let mut child = command .spawn() .map_err(|error| format!("cannot start the pin: {error}"))?; - let started = Instant::now(); - let status = loop { - if let Some(status) = child - .try_wait() - .map_err(|error| format!("cannot wait for the pin: {error}"))? - { - break status; - } - if started.elapsed() > PIN_DEADLINE { - drop(child.kill()); - drop(child.wait()); + let status = match dx_test_scratch::wait::exit_within(child, PIN_DEADLINE) + .map_err(|error| format!("cannot wait for the pin: {error}"))? + { + dx_test_scratch::wait::Exit::Exited(status) => status, + dx_test_scratch::wait::Exit::Killed(_) => { return Err(format!( "pin exceeded {}s; last output:\n{}", PIN_DEADLINE.as_secs(), tail(&log_path) )); } - std::thread::sleep(Duration::from_secs(5)); }; if !status.success() { return Err(tail(&log_path)); diff --git a/tools/testing/lsp/BUILD.bazel b/tools/testing/lsp/BUILD.bazel index 646a412027..b33153a16e 100644 --- a/tools/testing/lsp/BUILD.bazel +++ b/tools/testing/lsp/BUILD.bazel @@ -18,7 +18,7 @@ rust_library( deps = all_crate_deps( package_name = "tools/testing/dx_lsp", normal = True, - ), + ) + ["//cli/test_scratch:dx_test_scratch"], ) rust_test( @@ -34,7 +34,7 @@ rust_test( package_name = "tools/testing/dx_lsp", normal = True, normal_dev = True, - ), + ) + ["//cli/test_scratch:dx_test_scratch"], ) real_source_target( diff --git a/tools/testing/lsp/src/lib.rs b/tools/testing/lsp/src/lib.rs index 412671d36d..fe2a5d532c 100644 --- a/tools/testing/lsp/src/lib.rs +++ b/tools/testing/lsp/src/lib.rs @@ -5,7 +5,7 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TryRecvError}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread; use std::time::{Duration, Instant}; @@ -148,7 +148,13 @@ pub struct Session { next_id: i64, child: Child, log: RefCell>, - stderr: Arc>>, + stderr: Arc, +} + +#[derive(Default)] +struct StderrLog { + bytes: Mutex>, + grew: Condvar, } const STDERR_KEEP_BYTES: usize = 64 * 1024; @@ -182,7 +188,7 @@ impl Session { let stdin = child.stdin.take().ok_or_else(|| piped("stdin"))?; let stdout = child.stdout.take().ok_or_else(|| piped("stdout"))?; let mut stderr = child.stderr.take().ok_or_else(|| piped("stderr"))?; - let stderr_log = Arc::new(Mutex::new(Vec::new())); + let stderr_log = Arc::new(StderrLog::default()); let stderr_sink = Arc::clone(&stderr_log); thread::spawn(move || { let mut chunk = [0u8; 4096]; @@ -190,12 +196,17 @@ impl Session { if read == 0 { break; } - let mut kept = stderr_sink.lock().unwrap_or_else(PoisonError::into_inner); + let mut kept = stderr_sink + .bytes + .lock() + .unwrap_or_else(PoisonError::into_inner); kept.extend(chunk.iter().take(read)); if kept.len() > STDERR_KEEP_BYTES { let excess = kept.len() - STDERR_KEEP_BYTES; kept.drain(..excess); } + drop(kept); + stderr_sink.grew.notify_all(); } }); let (sender, events) = mpsc::channel(); @@ -260,6 +271,7 @@ impl Session { fn stderr_tail(&self) -> String { let bytes = self .stderr + .bytes .lock() .unwrap_or_else(PoisonError::into_inner) .clone(); @@ -401,22 +413,46 @@ impl Session { what: &str, deadline: Instant, ) -> Result { + self.drain()?; + let mut kept = self + .stderr + .bytes + .lock() + .unwrap_or_else(PoisonError::into_inner); loop { - self.drain()?; - let text = String::from_utf8_lossy( - &self.stderr.lock().unwrap_or_else(PoisonError::into_inner), - ) - .into_owned(); + let text = String::from_utf8_lossy(&kept).into_owned(); if text.contains(needle) { + drop(kept); + self.drain()?; return Ok(text); } - if Instant::now() >= deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + drop(kept); return Err(Error::Timeout(format!( "{what}; stderr: {}", self.stderr_tail() ))); } - thread::sleep(Duration::from_millis(25)); + kept = self + .stderr + .grew + .wait_timeout(kept, left) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + } + + pub fn wait_quiescent(&self, what: &str, deadline: Instant) -> Result<(), Error> { + self.drain()?; + let latest = self.log.borrow().iter().rev().find_map(server_quiescent); + if latest == Some(true) { + return Ok(()); + } + loop { + if server_quiescent(&self.next_event(what, deadline)?) == Some(true) { + return Ok(()); + } } } @@ -445,7 +481,7 @@ impl Session { serde_json::json!({ "processId": null, "rootUri": root_uri, - "capabilities": {}, + "capabilities": {"experimental": {"serverStatusNotification": true}}, "initializationOptions": null, }), )?; @@ -460,20 +496,12 @@ impl Session { self.wait_response(id, "shutdown", Instant::now() + Duration::from_secs(15))?; ok_result(&response)?; self.notify("exit", serde_json::Value::Null)?; - let deadline = Instant::now() + Duration::from_secs(15); - loop { - match self - .child - .try_wait() - .map_err(|err| Error::Transport(format!("cannot reap lsp server: {err}")))? - { - Some(_) => return Ok(()), - None if Instant::now() < deadline => thread::sleep(Duration::from_millis(25)), - None => { - drop(self.child.kill()); - drop(self.child.wait()); - return Err(Error::Timeout("lsp server exit".to_owned())); - } + match dx_test_scratch::wait::child_exits(&mut self.child, Duration::from_secs(15)) { + Ok(_) => Ok(()), + Err(error) => { + drop(self.child.kill()); + drop(self.child.wait()); + Err(Error::Timeout(format!("lsp server exit: {error}"))) } } } @@ -584,7 +612,7 @@ pub fn definition_uri( ok_result(&response) } -pub fn poll_definition( +pub fn quiescent_definition( session: &mut Session, file_uri: &str, text: &str, @@ -592,28 +620,19 @@ pub fn poll_definition( what: &str, deadline: Instant, ) -> Result { - let mut last = serde_json::Value::Null; - loop { - match definition_uri( - session, - file_uri, - text, - needle, - what, - Instant::now() + Duration::from_secs(15), - ) { - Ok(result) if result != serde_json::Value::Null && result != serde_json::json!([]) => { - return Ok(result); - } - Ok(result) => last = result, - Err(Error::Timeout(_)) => {} - Err(err) => return Err(err), - } - if Instant::now() >= deadline { - return Ok(last); - } - thread::sleep(Duration::from_secs(5)); + session.wait_quiescent(&format!("{what}: the server settling"), deadline)?; + definition_uri(session, file_uri, text, needle, what, deadline) +} + +fn server_quiescent(message: &serde_json::Value) -> Option { + if message.get("method").and_then(serde_json::Value::as_str) + != Some("experimental/serverStatus") + { + return None; } + message + .pointer("/params/quiescent") + .and_then(serde_json::Value::as_bool) } pub fn first_location(result: &serde_json::Value, what: &str) -> Result { @@ -747,7 +766,7 @@ mod tests { .expect("frame is utf8") }; let script = format!( - "printf '%s' '{}'; printf '%s' '{}'; echo boom >&2; sleep 5", + "printf '%s' '{}'; printf '%s' '{}'; echo boom >&2; exec cat >/dev/null", publish(serde_json::json!([])), publish(serde_json::json!([{"message": "bad"}])), ); diff --git a/tools/testing/nested/probe/main.rs b/tools/testing/nested/probe/main.rs index cd1e4dd179..18f8fa80ca 100644 --- a/tools/testing/nested/probe/main.rs +++ b/tools/testing/nested/probe/main.rs @@ -1,6 +1,6 @@ #![deny(clippy::indexing_slicing, clippy::string_slice)] -use std::io::Write; +use std::io::{Read as _, Write}; use std::process::ExitCode; fn code(arg: Option<&String>) -> ExitCode { @@ -33,27 +33,25 @@ fn run(args: &[String]) -> Result { } Ok(ExitCode::SUCCESS) } - Some("sleep") => { - std::thread::sleep(std::time::Duration::from_secs( - args.get(1).and_then(|secs| secs.parse().ok()).unwrap_or(60), - )); + Some("hold") => { + std::io::stdin() + .read_to_end(&mut Vec::new()) + .map_err(|error| format!("hold: {error}"))?; Ok(ExitCode::SUCCESS) } Some("emit") => { eprintln!("{}", args.get(1).map_or("", String::as_str)); Ok(code(args.get(2))) } - Some("heartbeat") => { - let file = args.get(1).ok_or("heartbeat file")?; - loop { - std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(file) - .and_then(|mut out| out.write_all(b"x\n")) - .map_err(|error| format!("heartbeat: {error}"))?; - std::thread::sleep(std::time::Duration::from_millis(20)); + Some("echo") => { + let mut out = std::io::stdout().lock(); + for line in std::io::stdin().lines() { + let line = line.map_err(|error| format!("echo: {error}"))?; + writeln!(out, "{line}") + .and_then(|()| out.flush()) + .map_err(|error| format!("echo: {error}"))?; } + Ok(ExitCode::SUCCESS) } Some("exit") => Ok(code(args.get(1))), Some(other) => { diff --git a/tools/testing/nested/src/lib.rs b/tools/testing/nested/src/lib.rs index 8fe0464548..56cc5962a1 100644 --- a/tools/testing/nested/src/lib.rs +++ b/tools/testing/nested/src/lib.rs @@ -925,14 +925,14 @@ fn servers_from(processes: &Processes, user_root: &Path) -> Vec { } fn wait_gone(pids: &[u32], limit: Duration) -> Vec { - let started = Instant::now(); - loop { - let left: Vec = pids.iter().copied().filter(|pid| alive(*pid)).collect(); - if left.is_empty() || started.elapsed() >= limit { - return left; - } - std::thread::sleep(Duration::from_millis(100)); - } + let deadline = Instant::now() + limit; + pids.iter() + .copied() + .filter(|pid| { + let left = deadline.saturating_duration_since(Instant::now()); + !dx_os_sys::exit::wait_gone(*pid, left).unwrap_or(false) && alive(*pid) + }) + .collect() } fn workspace_prefixes(workspaces: &Path) -> Vec { @@ -1263,6 +1263,7 @@ const REAP_ENV: &str = "DX_NESTED_REAP"; /// Names the file in the slot home that receives the reaper's stderr. const REAPER_LOG: &str = "reaper.log"; +const REAPER_WAITING: &str = "nested bazel reaper: waiting for owner"; /// Starts a detached shim that sweeps the slot's workspaces once `owner` is gone, however it died. #[cfg(unix)] @@ -1315,8 +1316,16 @@ fn reap(owner: &str, workspaces: &Path) -> i32 { eprintln!("nested bazel shim: {REAP_ENV} is not a pid"); return 2; }; - while alive(owner) { - std::thread::sleep(Duration::from_secs(1)); + eprintln!("{REAPER_WAITING} {owner}"); + loop { + match dx_os_sys::exit::wait_gone(owner, Duration::from_secs(3600)) { + Ok(true) => break, + Ok(false) => {} + Err(error) => { + eprintln!("nested bazel reaper: cannot wait for owner {owner}: {error}"); + return 2; + } + } } let real = std::fs::canonicalize(workspaces).unwrap_or_else(|_| workspaces.to_path_buf()); eprintln!( @@ -2293,6 +2302,44 @@ fn probe_command(args: &[&str]) -> Command { command } +#[cfg(test)] +#[track_caller] +fn reaper_waiting(home: &Path) { + let log = home.join(REAPER_LOG); + let waiting = || std::fs::read_to_string(&log).is_ok_and(|text| text.contains(REAPER_WAITING)); + if let Err(error) = dx_test_scratch::wait::watch_until( + &log, + "the reaper waiting", + Duration::from_secs(30), + waiting, + ) { + panic!("{error}"); + } +} + +#[cfg(all(test, unix))] +#[track_caller] +fn exited_unreaped(pid: u32) { + let raw = i32::try_from(pid).expect("pid"); + let waited = + dx_test_scratch::wait::within("the child exiting", Duration::from_secs(10), move || { + dx_os_sys::process::await_exit_unreaped(raw) + }); + match waited { + Ok(Ok(())) => {} + Ok(Err(error)) => panic!("waitid {pid}: {error}"), + Err(error) => panic!("{error}"), + } +} + +#[cfg(test)] +fn held(args: &[&str]) -> Child { + probe_command(&[&["hold"][..], args].concat()) + .stdin(std::process::Stdio::piped()) + .spawn() + .expect("spawn a held probe") +} + #[cfg(test)] #[cfg(unix)] mod tests { @@ -2717,14 +2764,8 @@ mod tests { #[test] fn a_process_is_owned_only_when_its_command_line_names_the_user_root() { let root = Path::new("/nested/owned/root"); - let mut child = probe_command(&["sleep", "30", &root.to_string_lossy()]) - .spawn() - .expect("spawn"); + let mut child = held(&[&root.to_string_lossy()]); let pid = child.id(); - let started = Instant::now(); - while !owned_by(pid, root) && started.elapsed() < Duration::from_secs(5) { - std::thread::sleep(Duration::from_millis(20)); - } let owned = owned_by(pid, root); let other = owned_by(pid, Path::new("/nested/other/root")); let unrelated = owned_by(std::process::id(), root); @@ -3036,24 +3077,16 @@ mod tests { } fn stand_in(workspace: &Path) -> Child { - probe_command(&[ - "sleep", - "60", + held(&[ &format!("--workspace_directory={}", workspace.display()), "--output_base=/home/u/.cache/bazel/_bazel_u/abc", ]) - .spawn() - .expect("spawn stand-in server") } - fn wait_until(what: &str, mut done: impl FnMut() -> bool) { - let started = Instant::now(); - while !done() { - assert!( - started.elapsed() < Duration::from_secs(15), - "timed out waiting for {what}" - ); - std::thread::sleep(Duration::from_millis(50)); + #[track_caller] + fn gone(pid: u32) { + if let Err(error) = dx_test_scratch::wait::pid_gone(pid, Duration::from_secs(15)) { + panic!("{error}"); } } @@ -3070,10 +3103,8 @@ mod tests { let mut stray = stand_in(&workspaces.join("consumer")); let other = stand_in(&outside_root.join("consumer")); let (stray_pid, other_pid) = (stray.id(), other.id()); - wait_until("both stand-ins", || { - servers_in_workspaces(&workspaces) == vec![stray_pid] - && servers_in_workspaces(&outside_root) == vec![other_pid] - }); + assert_eq!(servers_in_workspaces(&workspaces), vec![stray_pid]); + assert_eq!(servers_in_workspaces(&outside_root), vec![other_pid]); assert_eq!(kill_servers_in_workspaces(&workspaces), [] as [u32; 0]); drop(stray.wait()); assert!(!alive(stray_pid)); @@ -3087,7 +3118,7 @@ mod tests { let mut server = Server::acquire(config(dir.path(), &probe())).expect("acquire"); let mut stray = stand_in(&server.home().join("w/consumer")); let pid = stray.id(); - wait_until("the stand-in", || server.servers() == vec![pid]); + assert_eq!(server.servers(), vec![pid]); assert_eq!(server.shutdown(), [] as [u32; 0]); drop(stray.wait()); assert!(!alive(pid)); @@ -3099,7 +3130,7 @@ mod tests { let server = Server::acquire(config(dir.path(), &probe())).expect("acquire"); let mut stray = stand_in(&server.home().join("w/consumer")); let pid = stray.id(); - wait_until("the stand-in", || server.servers() == vec![pid]); + assert_eq!(server.servers(), vec![pid]); drop(server); drop(stray.wait()); assert!(!alive(pid)); @@ -3112,9 +3143,7 @@ mod tests { std::fs::create_dir_all(&workspace).expect("mkdir"); let mut stray = stand_in(&workspace); let pid = stray.id(); - wait_until("the stand-in", || { - servers_in_workspaces(&dir.path().join("w")) == vec![pid] - }); + assert_eq!(servers_in_workspaces(&dir.path().join("w")), vec![pid]); let server = Server::acquire(config(dir.path(), &probe())).expect("acquire"); drop(stray.wait()); assert!(!alive(pid)); @@ -3128,18 +3157,16 @@ mod tests { let home = dir.path().to_path_buf(); let workspaces = home.join("w"); std::fs::create_dir_all(&workspaces).expect("mkdir"); - let mut owner = probe_command(&["sleep", "60"]).spawn().expect("owner"); + let mut owner = held(&[]); let mut stray = stand_in(&workspaces.join("consumer")); let pid = stray.id(); - wait_until("the stand-in", || { - servers_in_workspaces(&workspaces) == vec![pid] - }); + assert_eq!(servers_in_workspaces(&workspaces), vec![pid]); let mut reaper = spawn_reaper(&bazel_wrapper_runfile(), owner.id(), &home).expect("reaper"); - std::thread::sleep(Duration::from_millis(1500)); + reaper_waiting(&home); assert!(alive(pid)); owner.kill().expect("kill owner"); drop(owner.wait()); - wait_until("the reaper to stop the stand-in", || !alive(pid)); + gone(pid); drop(stray.wait()); drop(reaper.wait()); } @@ -3151,9 +3178,10 @@ mod tests { let workspaces = dir.path().join("w"); let child = stand_in(&workspaces.join("consumer")); let pid = child.id(); - wait_until("stand-in in the table", || { - servers_in_workspaces_from(&Processes::snapshot(), &workspaces) == vec![pid] - }); + assert_eq!( + servers_in_workspaces_from(&Processes::snapshot(), &workspaces), + vec![pid] + ); stop(child, &workspaces); } @@ -3162,7 +3190,8 @@ mod tests { fn snapshot_treats_zombies_as_gone() { let mut child = probe_command(&["exit", "0"]).spawn().expect("spawn true"); let pid = child.id(); - wait_until("zombie", || dx_process::procs::zombie(pid)); + exited_unreaped(pid); + assert!(dx_process::procs::zombie(pid)); assert!(!Processes::snapshot().alive(pid)); drop(child.wait()); } @@ -3369,10 +3398,7 @@ mod portable_tests { fn alive_treats_an_unreaped_child_as_dead() { let mut child = probe_command(&["exit", "0"]).spawn().expect("spawn"); let pid = child.id(); - let start = Instant::now(); - while alive(pid) && start.elapsed() < Duration::from_secs(10) { - std::thread::sleep(Duration::from_millis(20)); - } + exited_unreaped(pid); assert!(!alive(pid), "exited but unreaped child counted as alive"); child.wait().expect("reap"); } @@ -3443,27 +3469,13 @@ mod portable_tests { "--workspace_directory={}", workspaces.join("consumer").display() ); - let mut owner = probe_command(&["sleep", "60"]).spawn().expect("owner"); - let mut stray = probe_command(&["sleep", "60", &flag]) - .spawn() - .expect("stray"); + let mut owner = held(&[]); + let mut stray = held(&[&flag]); let pid = stray.id(); - let wait_until = |what: &str, done: &dyn Fn() -> bool| { - let started = Instant::now(); - while !done() { - assert!( - started.elapsed() < Duration::from_secs(30), - "timed out waiting for {what}" - ); - std::thread::sleep(Duration::from_millis(50)); - } - }; - wait_until("the stand-in", &|| { - servers_in_workspaces(&workspaces).contains(&pid) - }); + assert!(servers_in_workspaces(&workspaces).contains(&pid)); let mut reaper = spawn_reaper(&bazel_wrapper_runfile(), owner.id(), &home).expect("reaper"); let log = || std::fs::read_to_string(home.join(REAPER_LOG)).unwrap_or_default(); - std::thread::sleep(Duration::from_millis(1500)); + reaper_waiting(&home); let early = reaper.try_wait(); assert!( matches!(early, Ok(None)), @@ -3473,17 +3485,13 @@ mod portable_tests { assert!(alive(pid)); owner.kill().expect("kill owner"); let _: std::io::Result = owner.wait(); - let started = Instant::now(); - while alive(pid) { - if started.elapsed() >= Duration::from_secs(30) { - panic!( - "timed out waiting for the reaper to stop the stand-in\nreaper: {:?}\nreaper.log:\n{}\nservers_in_workspaces: {:?}", - reaper.try_wait(), - log(), - servers_in_workspaces(&workspaces) - ); - } - std::thread::sleep(Duration::from_millis(50)); + if let Err(error) = dx_test_scratch::wait::pid_gone(pid, Duration::from_secs(30)) { + panic!( + "the reaper did not stop the stand-in: {error}\nreaper: {:?}\nreaper.log:\n{}\nservers_in_workspaces: {:?}", + reaper.try_wait(), + log(), + servers_in_workspaces(&workspaces) + ); } let _: std::io::Result = stray.wait(); let _: std::io::Result = reaper.wait(); @@ -3495,16 +3503,8 @@ mod portable_tests { let scratch = tempfile::tempdir().expect("tempdir"); let workspace = scratch.path().join("ws"); let flag = format!("--workspace_directory={}", workspace.display()); - let mut child = probe_command(&["sleep", "30", &flag]) - .spawn() - .expect("spawn"); + let mut child = held(&[&flag]); let pid = child.id(); - let started = Instant::now(); - while !servers_in_workspaces(scratch.path()).contains(&pid) - && started.elapsed() < Duration::from_secs(5) - { - std::thread::sleep(Duration::from_millis(20)); - } let found = servers_in_workspaces(scratch.path()).contains(&pid); let elsewhere = servers_in_workspaces(&scratch.path().join("other")).contains(&pid); child.kill().expect("kill"); @@ -3519,63 +3519,110 @@ mod suspend_tests { use super::*; use std::time::Duration; - fn heartbeat(file: &Path) -> Child { - let mut command = probe_command(&["heartbeat", &file.to_string_lossy()]); - command.spawn().expect("spawn heartbeat") + struct Echo { + child: Child, + input: std::process::ChildStdin, + replies: std::sync::mpsc::Receiver, + } + + impl Echo { + fn start() -> Echo { + let mut child = probe_command(&["echo"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .expect("spawn echo"); + let input = child.stdin.take().expect("echo stdin"); + let output = child.stdout.take().expect("echo stdout"); + let (sender, replies) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let lines = std::io::BufRead::lines(std::io::BufReader::new(output)); + for line in lines.map_while(Result::ok) { + if sender.send(line).is_err() { + break; + } + } + }); + Echo { + child, + input, + replies, + } + } + + fn send(&mut self, text: &str) { + use std::io::Write as _; + writeln!(self.input, "{text}") + .and_then(|()| self.input.flush()) + .expect("write to echo"); + } + + #[track_caller] + fn reply(&self) -> String { + self.replies + .recv_timeout(Duration::from_secs(10)) + .expect("the echo child answers within 10s") + } } - fn size(file: &Path) -> u64 { - std::fs::metadata(file).map_or(0, |meta| meta.len()) + impl Drop for Echo { + fn drop(&mut self) { + drop(self.child.kill()); + drop(self.child.wait()); + } } - fn wait_for_growth(file: &Path, from: u64) -> bool { - let deadline = Instant::now() + Duration::from_secs(10); - while Instant::now() < deadline { - if size(file) > from { - return true; - } - std::thread::sleep(Duration::from_millis(50)); + #[track_caller] + fn stopped(pid: u32) { + #[cfg(unix)] + { + let raw = i32::try_from(pid).expect("pid"); + let stop = dx_test_scratch::wait::within( + "the child stopping", + Duration::from_secs(10), + move || dx_os_sys::process::await_stop(raw), + ); + assert!( + matches!(stop, Ok(Ok(Some(_)))), + "the child never stopped: {stop:?}" + ); } - false + #[cfg(not(unix))] + let _: u32 = pid; } #[test] fn suspend_stops_a_child_and_resume_restarts_it() { - let dir = tempfile::tempdir().expect("tempdir"); - let file = dir.path().join("beat"); - let mut child = heartbeat(&file); - assert!(wait_for_growth(&file, 0)); - let mut frozen = suspend(child.id()).expect("suspend"); - std::thread::sleep(Duration::from_millis(200)); - let held = size(&file); - std::thread::sleep(Duration::from_millis(500)); - assert_eq!(size(&file), held, "the child kept running while suspended"); + let mut echo = Echo::start(); + echo.send("before"); + assert_eq!(echo.reply(), "before"); + let mut frozen = suspend(echo.child.id()).expect("suspend"); + stopped(echo.child.id()); + echo.send("during"); + assert!( + echo.replies.try_recv().is_err(), + "the child answered while suspended" + ); assert!(frozen.resume()); - assert!(wait_for_growth(&file, held), "the child did not restart"); - drop(child.kill()); - drop(child.wait()); + assert_eq!(echo.reply(), "during", "the child did not restart"); } #[test] fn dropping_the_guard_resumes_the_child() { - let dir = tempfile::tempdir().expect("tempdir"); - let file = dir.path().join("beat"); - let mut child = heartbeat(&file); - assert!(wait_for_growth(&file, 0)); - let frozen = suspend(child.id()).expect("suspend"); - std::thread::sleep(Duration::from_millis(200)); - let held = size(&file); + let mut echo = Echo::start(); + echo.send("before"); + assert_eq!(echo.reply(), "before"); + let frozen = suspend(echo.child.id()).expect("suspend"); + stopped(echo.child.id()); + echo.send("during"); drop(frozen); - assert!(wait_for_growth(&file, held), "the child did not restart"); - drop(child.kill()); - drop(child.wait()); + assert_eq!(echo.reply(), "during", "the child did not restart"); } #[test] fn suspending_a_dead_pid_fails() { - let mut child = heartbeat(&std::env::temp_dir().join("nested-suspend-dead")); + let mut child = probe_command(&["exit", "0"]).spawn().expect("spawn"); let pid = child.id(); - drop(child.kill()); drop(child.wait()); assert!(suspend(pid).is_err()); } diff --git a/tools/testing/nested_bazel_harness_test.rs b/tools/testing/nested_bazel_harness_test.rs index a587926d19..2377143ac6 100644 --- a/tools/testing/nested_bazel_harness_test.rs +++ b/tools/testing/nested_bazel_harness_test.rs @@ -1,6 +1,6 @@ //! Offline self-tests of the nested Bazel harness: the pinned binary runs without bazelisk, a locked consumer resolves `rules_dx` extensions from its repository cache sets, and nested servers stop with their test binary, and a restarted server refetches no repository rule unless its declared environment changed, which the probe proves the guard catches, a consumer cannot load an internal `.bzl`, and a root-only extension warns about the tags a dependency sets. -use std::time::{Duration, Instant}; +use std::time::Duration; use dx_nested as nested; use dx_testing::{read_runfiles, resolve_runfiles, run}; @@ -587,12 +587,7 @@ fn without_a_shared_root_a_test_extracts_fetches_and_stops_its_server() { .trim() .parse() .unwrap_or_else(|_| panic!("probe printed no server pid: {}", probe.combined())); - let started = Instant::now(); - while nested::alive(pid) && started.elapsed() < Duration::from_secs(3) { - std::thread::sleep(Duration::from_millis(100)); + if let Err(error) = dx_test_scratch::wait::pid_gone(pid, Duration::from_secs(3)) { + panic!("nested Bazel server {pid} outlived its test binary: {error}"); } - assert!( - !nested::alive(pid), - "nested Bazel server {pid} outlived its test binary" - ); } diff --git a/tools/testing/process_probe/BUILD.bazel b/tools/testing/process_probe/BUILD.bazel index 613a5e1461..9902032b26 100644 --- a/tools/testing/process_probe/BUILD.bazel +++ b/tools/testing/process_probe/BUILD.bazel @@ -26,6 +26,7 @@ rust_binary( "//cli/os_sys:dx_os_sys", "//cli/output:dx_output", "//cli/path:dx_path", + "//cli/test_scratch:dx_test_scratch", ], ) diff --git a/tools/testing/process_probe/probe_test.rs b/tools/testing/process_probe/probe_test.rs index 02e3d72a2e..a00c9af976 100644 --- a/tools/testing/process_probe/probe_test.rs +++ b/tools/testing/process_probe/probe_test.rs @@ -440,19 +440,16 @@ impl Drop for Release { #[cfg(unix)] fn sigints_logged(log: &std::path::Path, expected: usize) -> Vec { - let deadline = Instant::now() + Duration::from_secs(10); - loop { - let bytes = std::fs::read(log).expect("log"); - if bytes.len() >= expected { - return bytes; - } - assert!( - Instant::now() < deadline, - "the probe logged {} of {expected} SIGINTs", - bytes.len() - ); - std::thread::sleep(Duration::from_millis(10)); + let logged = || std::fs::read(log).expect("log"); + let what = format!("the probe logging {expected} SIGINTs"); + if let Err(error) = + dx_test_scratch::wait::watch_until(log, &what, Duration::from_secs(10), || { + logged().len() >= expected + }) + { + panic!("{error}; it logged {}", logged().len()); } + logged() } #[cfg(unix)] @@ -475,11 +472,7 @@ fn counted_sigints_are_logged_and_do_not_stop_the_probe() { .spawn() .expect("probe starts"), ); - let deadline = Instant::now() + Duration::from_secs(10); - while !log.exists() { - assert!(Instant::now() < deadline, "probe never armed"); - std::thread::sleep(Duration::from_millis(10)); - } + dx_testing::wait_armed(&log); for n in 1..=2 { // SAFETY: kill takes plain integers and has no memory preconditions. assert_eq!(unsafe { kill(i32::try_from(child.0.id()).unwrap(), 2) }, 0); @@ -492,17 +485,8 @@ fn counted_sigints_are_logged_and_do_not_stop_the_probe() { ); assert_eq!(std::fs::read(&log).expect("log"), b"II"); std::fs::write(&gate, b"").expect("release the probe"); - let deadline = Instant::now() + Duration::from_secs(10); - let status = loop { - if let Some(status) = child.0.try_wait().expect("probe status") { - break status; - } - assert!( - Instant::now() < deadline, - "the probe did not exit after its gate opened" - ); - std::thread::sleep(Duration::from_millis(10)); - }; + let status = dx_test_scratch::wait::child_exits(&mut child.0, Duration::from_secs(10)) + .unwrap_or_else(|error| panic!("the probe did not exit after its gate opened: {error}")); assert_eq!(status.code(), Some(0), "the probe must exit cleanly"); } @@ -547,11 +531,7 @@ fn an_alive_lock_is_held_until_the_probe_dies() { .arg("--sleep-ms=30000") .spawn() .expect("probe starts"); - let deadline = Instant::now() + Duration::from_secs(10); - while !lock.exists() { - assert!(Instant::now() < deadline, "probe never armed"); - std::thread::sleep(Duration::from_millis(10)); - } + dx_testing::wait_armed(&lock); assert!( dx_testing::alive_lock_held(&lock), "a live probe must hold its lock" diff --git a/tools/testing/process_probe/src/main.rs b/tools/testing/process_probe/src/main.rs index 875ba61f42..88ea8ce1a6 100644 --- a/tools/testing/process_probe/src/main.rs +++ b/tools/testing/process_probe/src/main.rs @@ -374,14 +374,8 @@ fn run_descendant(plan: &Plan) -> Result { } fn wait_for_lock(path: &str) -> Result<(), String> { - let deadline = std::time::Instant::now() + Duration::from_secs(10); - while !std::path::Path::new(path).exists() { - if std::time::Instant::now() >= deadline { - return Err(format!("the descendant never took {path}")); - } - std::thread::sleep(Duration::from_millis(10)); - } - Ok(()) + dx_test_scratch::wait::path_appears(std::path::Path::new(path), Duration::from_secs(10)) + .map_err(|error| format!("the descendant never took {path}: {error}")) } fn hold_alive_lock(path: &str) -> io::Result { @@ -502,10 +496,10 @@ fn sleep_until_gate(plan: &Plan) { std::thread::sleep(plan.sleep); return; }; - let deadline = std::time::Instant::now() + plan.sleep; - while !std::path::Path::new(gate).exists() && std::time::Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } + drop(dx_test_scratch::wait::path_appears( + std::path::Path::new(gate), + plan.sleep, + )); } struct Failure { diff --git a/tools/testing/src/lib.rs b/tools/testing/src/lib.rs index 86f4deafe8..25abd32ccf 100644 --- a/tools/testing/src/lib.rs +++ b/tools/testing/src/lib.rs @@ -97,13 +97,13 @@ fn captured_text(buffer: &Captured) -> String { } fn wait_for(handle: std::thread::JoinHandle<()>, limit: std::time::Duration) { - let end = std::time::Instant::now() + limit; - while !handle.is_finished() && std::time::Instant::now() < end { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - if handle.is_finished() { - drop(handle.join()); - } + drop(dx_test_scratch::wait::within( + "the output reader", + limit, + move || { + drop(handle.join()); + }, + )); } pub fn run_within( @@ -132,22 +132,10 @@ pub fn run_command( child.stdout.take().map(|pipe| drain(pipe, out.clone())), child.stderr.take().map(|pipe| drain(pipe, err.clone())), ]; - let deadline = std::time::Instant::now() + limit; - let mut status = None; - while status.is_none() { - status = child.try_wait()?; - if status.is_none() { - if std::time::Instant::now() >= deadline { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - } - let timed_out = status.is_none(); - if timed_out { - drop(child.kill()); - status = Some(child.wait()?); - } + let (status, timed_out) = match dx_test_scratch::wait::exit_within(child, limit)? { + dx_test_scratch::wait::Exit::Exited(status) => (status, false), + dx_test_scratch::wait::Exit::Killed(status) => (status, true), + }; let grace = if timed_out { std::time::Duration::from_secs(2) } else { @@ -157,7 +145,7 @@ pub fn run_command( wait_for(reader, grace); } let run = Run { - status: status.ok_or_else(|| std::io::Error::other("child has no exit status"))?, + status, stdout: captured_text(&out), stderr: captured_text(&err), }; @@ -330,8 +318,14 @@ fn existing(runfiles: &runfiles::Runfiles, key: &str) -> Option { .filter(|path| path.exists()) } +fn opened_runfiles() -> &'static Result { + static OPENED: std::sync::OnceLock> = + std::sync::OnceLock::new(); + OPENED.get_or_init(|| runfiles::Runfiles::create().map_err(|error| error.to_string())) +} + pub fn rlocation(key: &str) -> std::io::Result { - let opened = runfiles::Runfiles::create(); + let opened = opened_runfiles(); if let Some(found) = opened .as_ref() .ok() @@ -345,7 +339,7 @@ pub fn rlocation(key: &str) -> std::io::Result { return Ok(found); } } - let detail = match opened { + let detail = match opened.as_ref() { Ok(_) => format!("{key} is not in {}", runfiles_source()), Err(error) => format!("cannot open {} for {key}: {error}", runfiles_source()), }; @@ -733,45 +727,33 @@ pub fn empty_git_repo(dir: &Path) { std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").expect("git HEAD"); } +#[track_caller] +#[expect(clippy::panic, reason = "test helper: a failed wait fails the test")] pub fn assert_alive_lock_released(lock: &Path) { assert!(lock.exists(), "the probe never armed: {}", lock.display()); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while alive_lock_held(lock) { - assert!( - std::time::Instant::now() < deadline, - "an owned process survived: {}", - lock.display() - ); - std::thread::sleep(std::time::Duration::from_millis(20)); + if let Err(error) = dx_test_scratch::wait::lock_free(lock, std::time::Duration::from_secs(10)) { + panic!("an owned process survived: {error}"); } } +#[track_caller] +#[expect(clippy::panic, reason = "test helper: a failed wait fails the test")] pub fn wait_armed(lock: &Path) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while !lock.exists() { - assert!( - std::time::Instant::now() < deadline, - "probe never armed: {}", - lock.display() - ); - std::thread::sleep(std::time::Duration::from_millis(10)); + if let Err(error) = + dx_test_scratch::wait::path_appears(lock, std::time::Duration::from_secs(10)) + { + panic!("probe never armed: {error}"); } } +#[track_caller] pub fn assert_still_held(lock: &Path) { wait_armed(lock); - let end = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - assert!( - alive_lock_held(lock), - "the detached server died with the run: {}", - lock.display() - ); - if std::time::Instant::now() >= end { - return; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } + assert!( + alive_lock_held(lock), + "the detached server died with the run: {}", + lock.display() + ); } #[must_use] From 1c7af21445212ae091fb3f0d6e95649401d97b13 Mon Sep 17 00:00:00 2001 From: Martin Kuntz Jacobsen Date: Tue, 24 Nov 2026 09:33:19 +0100 Subject: [PATCH 2/3] tests: wait on events instead of sleeps in the cli crate tests Process, lease, prune, lock, http, shim, launcher, os_sys and worktree tests now wait on the real event with a deadline: a pid exiting, a lock coming free, a path appearing, a fifo or pipe that never gets a writer, or a peer closing its socket. Long-running sleep children become cat or read on a held pipe. The launcher copy goes through cp so no forked thread inherits a write fd, which removes the ETXTBSY retry loop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xut2hyBydsMejdwk6QdKus --- cli/atomic_fs/src/lease.rs | 84 ++++++++-------------- cli/http/src/lib_tests.rs | 3 +- cli/launcher/src/launch_tests.rs | 24 +++---- cli/lock/src/lib.rs | 44 +++++++++--- cli/lock/tests/fixture_resolver.rs | 2 +- cli/os_sys/src/process_tests.rs | 12 ++-- cli/os_sys/src/signals_tests.rs | 4 +- cli/os_sys/src/spawn_tests.rs | 6 +- cli/process/src/groups_tests.rs | 6 +- cli/process/src/lifecycle_tests.rs | 111 ++++++++++++----------------- cli/process/src/procs_tests.rs | 47 +++++++----- cli/process/src/runner_tests.rs | 14 +--- cli/setup/src/prune/apply.rs | 17 +++-- cli/setup/src/prune/hold_tests.rs | 32 ++++----- cli/shim/BUILD.bazel | 1 + cli/shim/tests/e2e.rs | 12 ++-- cli/shim/tests/support/mod.rs | 3 +- cli/test_scratch/src/lib.rs | 47 ------------ cli/test_scratch/src/wait.rs | 23 +++++- cli/worktree/src/host.rs | 8 +-- cli/worktree/src/tests.rs | 2 +- 21 files changed, 226 insertions(+), 276 deletions(-) diff --git a/cli/atomic_fs/src/lease.rs b/cli/atomic_fs/src/lease.rs index 295ad122c3..aae40467fb 100644 --- a/cli/atomic_fs/src/lease.rs +++ b/cli/atomic_fs/src/lease.rs @@ -267,10 +267,10 @@ mod tests { "exclusive acquisition reports the holder instead of waiting" ); drop(shared); - eventually("releasing the shared lease frees the generation", || { - try_acquire_exclusive(&root, GenerationUse::Environment, HEX_A) - .expect("probe after release") - }); + free( + &lease_path(&root, GenerationUse::Environment, HEX_A).expect("path"), + "releasing the shared lease frees the generation", + ); scratch.close().expect("cleanup"); } @@ -286,9 +286,7 @@ mod tests { let held = try_lock_file(&path, true).expect("lock").expect("free"); assert!(try_lock_file(&path, false).expect("probe").is_none()); drop(held); - eventually("release of the held path", || { - try_lock_file(&path, false).expect("probe") - }); + free(&path, "release of the held path"); scratch.close().expect("cleanup"); } @@ -307,14 +305,12 @@ mod tests { drop(first); assert!(try_lock_file(&path, false).expect("probe").is_none()); drop(second); - let exclusive = eventually("release of both shared holders", || { - try_lock_file(&path, false).expect("probe") - }); + let exclusive = dx_test_scratch::wait::locked(&path, RELEASE) + .unwrap_or_else(|error| panic!("release of both shared holders: {error}")); assert!(try_lock_file_shared(&path, false).expect("probe").is_none()); drop(exclusive); - eventually("release of the exclusive holder", || { - try_lock_file_shared(&path, false).expect("probe") - }); + dx_test_scratch::wait::locked_shared(&path, RELEASE) + .unwrap_or_else(|error| panic!("release of the exclusive holder: {error}")); scratch.close().expect("cleanup"); } @@ -350,9 +346,7 @@ mod tests { Err(io::ErrorKind::WouldBlock) ); drop(first); - eventually("release of the first holder", || { - acquire_exclusive_at(&path, Duration::from_millis(100)).ok() - }); + free(&path, "release of the first holder"); } #[test] @@ -396,12 +390,9 @@ mod tests { "a handed-off shared handle keeps the generation locked" ); drop(file); - eventually( + free( + &lease_path(&root, GenerationUse::Environment, HEX_A).expect("path"), "the generation frees once the handed-off handle drops", - || { - (!shared_held(&root, GenerationUse::Environment, HEX_A).expect("final probe")) - .then_some(()) - }, ); scratch.close().expect("cleanup"); } @@ -412,49 +403,32 @@ mod tests { .arg("--exact") .env("DX_LEASE_CHILD", mode) .env("DX_LEASE_ROOT", root) + .stdin(std::process::Stdio::piped()) .spawn() .expect("spawn lease child") } + const RELEASE: Duration = Duration::from_secs(30); + fn wait_for(path: &Path, what: &str) { - let start = std::time::Instant::now(); - while !path.exists() { - // LCOV_EXCL_START - reason: test timeout, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - assert!( - start.elapsed() <= Duration::from_secs(30), - "timed out waiting for {what}" - ); - // LCOV_EXCL_STOP - reason: end test timeout, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - std::thread::sleep(Duration::from_millis(25)); - } + dx_test_scratch::wait::path_appears(path, RELEASE) + .unwrap_or_else(|error| panic!("{what}: {error}")); } - fn eventually(what: &str, mut probe: impl FnMut() -> Option) -> T { - let start = std::time::Instant::now(); - loop { - if let Some(value) = probe() { - return value; - } // LCOV_EXCL_LINE - reason: the probe succeeds on the first poll, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - // LCOV_EXCL_START - reason: test timeout, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - assert!( - start.elapsed() <= Duration::from_secs(30), - "timed out waiting for {what}" - ); - std::thread::sleep(Duration::from_millis(25)); - // LCOV_EXCL_STOP - reason: end test timeout, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } + fn free(path: &Path, what: &str) { + dx_test_scratch::wait::lock_free(path, RELEASE) + .unwrap_or_else(|error| panic!("{what}: {error}")); } fn child_main(root: &Path, mode: &str) { let ready = root.join("child-ready"); - let release = root.join("child-release"); match mode { "die" => { // LCOV_EXCL_START - reason: runs only in the spawned child, issue: 8104, policy: docs/cli/commands/build-test-coverage.md let _held = acquire_shared(root, GenerationUse::Generated, HEX_B, Duration::ZERO) .expect("child acquires"); std::fs::write(&ready, b"ready").expect("signal ready"); - wait_for(&release, "release"); + drop(io::Read::read_to_end(&mut io::stdin(), &mut Vec::new())); } // LCOV_EXCL_STOP - reason: end runs only in the spawned child, issue: 8104, policy: docs/cli/commands/build-test-coverage.md "contend" => { @@ -502,10 +476,10 @@ mod tests { child.kill().expect("kill the holder"); let status = child.wait().expect("reap the holder"); assert!(!status.success(), "the holder dies abnormally"); - eventually("a killed holder must release its lease", || { - (!shared_held(&root, GenerationUse::Generated, HEX_B).expect("release probe")) - .then_some(()) - }); + free( + &lease_path(&root, GenerationUse::Generated, HEX_B).expect("path"), + "a killed holder must release its lease", + ); scratch.close().expect("cleanup"); } @@ -542,10 +516,10 @@ mod tests { "a shared acquire during an exclusive cleanup hold fails instead of waiting forever" ); drop(exclusive); - eventually("release of the exclusive cleanup hold", || { - (!shared_held(&root, GenerationUse::Generated, HEX_B).expect("release probe")) - .then_some(()) - }); + free( + &lease_path(&root, GenerationUse::Generated, HEX_B).expect("path"), + "release of the exclusive cleanup hold", + ); std::fs::remove_file(root.join("child-verdict")).expect("reset the verdict"); let mut admitted = spawn_child( "shared_acquire_fails_closed_while_cleanup_holds_exclusive", diff --git a/cli/http/src/lib_tests.rs b/cli/http/src/lib_tests.rs index bb246b25ee..588e8c090b 100644 --- a/cli/http/src/lib_tests.rs +++ b/cli/http/src/lib_tests.rs @@ -110,7 +110,8 @@ fn answer(stream: TcpStream, reply: &Reply, log: &Mutex>, full: &Mut drop(out.write_all(body)); drop(out.flush()); if let Reply::Stall(..) = reply { - std::thread::sleep(Duration::from_secs(30)); + drop(out.set_read_timeout(Some(Duration::from_secs(30)))); + drop(std::io::copy(&mut reader, &mut std::io::sink())); } } diff --git a/cli/launcher/src/launch_tests.rs b/cli/launcher/src/launch_tests.rs index 01bd4a7984..0a141e101c 100644 --- a/cli/launcher/src/launch_tests.rs +++ b/cli/launcher/src/launch_tests.rs @@ -375,20 +375,16 @@ fn run_scrubs_unset_variables() { .unwrap(); let launcher = dx_testing::env_file("DX_EXEC_LAUNCHER"); let app = dir.join("app.exe"); - std::fs::copy(&launcher, &app).unwrap(); - let mut tries = 0; - let status = loop { - match std::process::Command::new(&app) - .env("EXEC_LAUNCHER_UNSET_PROBE", "1") - .status() - { - Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy && tries < 50 => { - tries += 1; - std::thread::sleep(std::time::Duration::from_millis(20)); - } - other => break other.unwrap(), - } - }; + let copied = std::process::Command::new("cp") + .arg(&launcher) + .arg(&app) + .status() + .unwrap(); + assert!(copied.success(), "cp the launcher: {copied}"); + let status = std::process::Command::new(&app) + .env("EXEC_LAUNCHER_UNSET_PROBE", "1") + .status() + .unwrap(); assert_eq!(status.code(), Some(0)); } diff --git a/cli/lock/src/lib.rs b/cli/lock/src/lib.rs index 0fcf998565..caa0fe60cc 100644 --- a/cli/lock/src/lib.rs +++ b/cli/lock/src/lib.rs @@ -628,16 +628,44 @@ mod tests { #[derive(Default)] struct Counting { asked: std::sync::Mutex>, - in_flight: AtomicUsize, - peak: AtomicUsize, + flight: std::sync::Mutex, + changed: std::sync::Condvar, + overlap: usize, + } + + #[derive(Default)] + struct Flight { + now: usize, + peak: usize, + } + + impl Counting { + fn overlapping(overlap: usize) -> Self { + Self { + overlap, + ..Self::default() + } + } + + fn peak(&self) -> usize { + self.flight.lock().expect("flight").peak + } } impl Fetch for Counting { fn sha256(&self, url: &str) -> Result { - let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; - self.peak.fetch_max(now, Ordering::SeqCst); - std::thread::sleep(std::time::Duration::from_millis(20)); - self.in_flight.fetch_sub(1, Ordering::SeqCst); + let mut flight = self.flight.lock().expect("flight"); + flight.now += 1; + flight.peak = flight.peak.max(flight.now); + self.changed.notify_all(); + let (mut flight, _) = self + .changed + .wait_timeout_while(flight, std::time::Duration::from_secs(10), |flight| { + flight.peak < self.overlap + }) + .expect("flight"); + flight.now -= 1; + drop(flight); self.asked.lock().expect("asked").push(url.to_owned()); if url.ends_with("/missing") { return Err(Error::new("HTTP 404")); @@ -674,9 +702,9 @@ mod tests { .map(|n| package(&format!("p{n}"), &format!("https://example.com/p{n}"))) .collect(); let mut lock = lock_of(packages, BTreeMap::new()); - let fetch = Counting::default(); + let fetch = Counting::overlapping(2); fill_all_digests(&mut lock, None, &fetch).expect("filled"); - let peak = fetch.peak.load(Ordering::SeqCst); + let peak = fetch.peak(); assert!((2..=FETCH_JOBS).contains(&peak), "peak {peak}"); for entry in &lock.packages { for archive in &entry.archives { diff --git a/cli/lock/tests/fixture_resolver.rs b/cli/lock/tests/fixture_resolver.rs index 6b6ed06311..ebf9078c7f 100644 --- a/cli/lock/tests/fixture_resolver.rs +++ b/cli/lock/tests/fixture_resolver.rs @@ -101,7 +101,7 @@ fn main() -> ExitCode { let index = std::env::args().nth(1).unwrap_or_default(); if index == "--hang" { loop { - std::thread::sleep(std::time::Duration::from_secs(60)); + std::thread::park(); } } match resolve(&index) { diff --git a/cli/os_sys/src/process_tests.rs b/cli/os_sys/src/process_tests.rs index ebb6b18345..3bd0a707c8 100644 --- a/cli/os_sys/src/process_tests.rs +++ b/cli/os_sys/src/process_tests.rs @@ -39,11 +39,11 @@ fn pid_zero_and_unknown_signals_are_rejected() { #[test] fn a_child_can_be_signalled_and_reaped() { - let mut child = std::process::Command::new("/bin/sleep") - .arg("30") + let mut child = std::process::Command::new("/bin/cat") + .stdin(std::process::Stdio::piped()) .process_group(0) .spawn() - .expect("sleep"); + .expect("cat"); let pid = i32::try_from(child.id()).expect("pid"); assert_eq!(group_of(pid).expect("getpgid"), pid); assert_eq!(stopped_by(pid).expect("waitid"), None); @@ -56,10 +56,10 @@ fn a_child_can_be_signalled_and_reaped() { #[cfg(target_os = "linux")] #[test] fn an_unattributed_signal_reaches_the_child() { - let mut child = std::process::Command::new("/bin/sleep") - .arg("30") + let mut child = std::process::Command::new("/bin/cat") + .stdin(std::process::Stdio::piped()) .spawn() - .expect("sleep"); + .expect("cat"); let pid = i32::try_from(child.id()).expect("pid"); queue_unattributed(pid, SIGTERM).expect("rt_sigqueueinfo"); let status = child.wait().expect("wait"); diff --git a/cli/os_sys/src/signals_tests.rs b/cli/os_sys/src/signals_tests.rs index 415f813ce4..5b679585a3 100644 --- a/cli/os_sys/src/signals_tests.rs +++ b/cli/os_sys/src/signals_tests.rs @@ -55,7 +55,9 @@ fn unlink_on_stop_child() { unlink_on_stop(Path::new(&path)).expect("watch"); let pid = i32::try_from(std::process::id()).expect("pid fits pid_t"); crate::process::signal(pid, libc::SIGTERM).expect("signal self"); - std::thread::sleep(std::time::Duration::from_secs(30)); + loop { + std::thread::park(); + } } #[test] diff --git a/cli/os_sys/src/spawn_tests.rs b/cli/os_sys/src/spawn_tests.rs index 8cd4bb8a9f..ec5be761cf 100644 --- a/cli/os_sys/src/spawn_tests.rs +++ b/cli/os_sys/src/spawn_tests.rs @@ -5,10 +5,10 @@ use crate::tty::{foreground_group, open_pty}; #[test] fn a_child_in_a_terminal_leads_its_foreground_group() { let (master, slave) = open_pty().expect("pty"); - let mut command = Command::new("/bin/sleep"); - command.arg("30"); + let mut command = Command::new("/bin/cat"); + command.stdin(std::process::Stdio::piped()); in_terminal(&mut command, slave); - let mut child = command.spawn().expect("sleep"); + let mut child = command.spawn().expect("cat"); let pid = i32::try_from(child.id()).expect("pid"); let held = foreground_group(&master); let group = group_of(pid); diff --git a/cli/process/src/groups_tests.rs b/cli/process/src/groups_tests.rs index eded2c705c..06aa2faf9a 100644 --- a/cli/process/src/groups_tests.rs +++ b/cli/process/src/groups_tests.rs @@ -501,12 +501,10 @@ fn a_group_that_ignores_the_first_signal_is_killed() { let dir = scratch.path().join("groups"); std::fs::create_dir_all(&dir).expect("dir"); let armed = scratch.path().join("armed"); - let script = format!( - "trap '' TERM; : > '{}'; while :; do sleep 1; done", - armed.display() - ); + let script = format!("trap '' TERM; : > '{}'; read -r line", armed.display()); let mut child = Command::new("/bin/sh") .args(["-c", &script]) + .stdin(std::process::Stdio::piped()) .process_group(0) .spawn() .expect("shell starts"); diff --git a/cli/process/src/lifecycle_tests.rs b/cli/process/src/lifecycle_tests.rs index 599a6d82fe..b06d2eeee7 100644 --- a/cli/process/src/lifecycle_tests.rs +++ b/cli/process/src/lifecycle_tests.rs @@ -383,8 +383,9 @@ fn timeout_kills_a_group_whose_leader_exits_on_term() { let scratch = dx_test_scratch::scratch("dx-lifecycle-term-group").unwrap(); let pidfile = scratch.path().join("child.pid"); let script = format!( - "sh -c 'trap \"\" TERM; echo $$ > {pid}; while :; do sleep 1; done' & wait", - pid = pidfile.display() + "sh -c 'trap \"\" TERM; echo $$ > {pid}; {block}' & wait", + pid = pidfile.display(), + block = blocked(scratch.path()), ); let spec = controlled_spec( scratch.path(), @@ -395,30 +396,20 @@ fn timeout_kills_a_group_whose_leader_exits_on_term() { run_within(&spec, INTERACTIVE).expect("timeout is an outcome"), ChildOutcome::TimedOut ); - let pid = std::fs::read_to_string(&pidfile) + let pid: u32 = std::fs::read_to_string(&pidfile) .expect("the descendant recorded its pid") .trim() - .to_owned(); - let deadline = Instant::now() + Duration::from_secs(10); - loop { - let alive = std::process::Command::new("kill") - .args(["-0", &pid]) - .stderr(std::process::Stdio::null()) - .status() - .is_ok_and(|status| status.success()); - if !alive { - break; - // LCOV_EXCL_START - reason: failure-only arm or message, never evaluated when the test passes, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } - assert!( - Instant::now() < deadline, - // LCOV_EXCL_STOP - reason: end of excluded branch, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - "descendant {pid} survived the run" - ); - // LCOV_EXCL_START - reason: failure-only arm or message, never evaluated when the test passes, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - std::thread::sleep(Duration::from_millis(50)); - // LCOV_EXCL_STOP - reason: end of excluded branch, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } + .parse() + .expect("a pid"); + dx_test_scratch::wait::pid_gone(pid, Duration::from_secs(10)).unwrap(); +} + +#[cfg(unix)] +fn blocked(dir: &std::path::Path) -> String { + format!( + "mkfifo \"{0}\" && read -r line < \"{0}\"", + dir.join("blocked.fifo").display() + ) } fn daemon_probe( @@ -1120,22 +1111,20 @@ fn counting_probe(scratch: &std::path::Path) -> (Probe, std::path::PathBuf) { .arg("--sleep-ms=30000") .process_group(0); let child = Probe(command.spawn().expect("probe starts")); - let deadline = Instant::now() + Duration::from_secs(10); - while !log.exists() { - assert!(Instant::now() < deadline, "probe never armed"); - std::thread::sleep(Duration::from_millis(10)); - } + wait_armed(&log); (child, log) } #[cfg(unix)] fn sigints(log: &std::path::Path, expected: usize) -> usize { let count = || std::fs::read(log).map_or(0, |bytes| bytes.len()); - let deadline = Instant::now() + Duration::from_secs(5); - while count() < expected && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } - std::thread::sleep(Duration::from_millis(100)); + dx_test_scratch::wait::watch_until( + log, + "the probe counting SIGINT", + Duration::from_secs(10), + || count() >= expected, + ) + .unwrap(); count() } @@ -1244,9 +1233,10 @@ fn streamed_self_exit_stops_the_rest_of_the_owned_group() { let lock = scratch.path().join("leftover.alive"); let sink = Sink::default(); let script = format!( - "'{probe}' --alive-lock='{lock}' --sleep-ms=30000 >/dev/null 2>&1 & while [ ! -e '{lock}' ]; do sleep 0.05; done; exit 0", + "mkfifo '{up}' || exit 9; '{probe}' --alive-lock='{lock}' --stdout-text=up --sleep-ms=30000 >'{up}' 2>/dev/null & head -c 2 '{up}' >/dev/null; exit 0", probe = dx_testing::process_probe().display(), lock = lock.display(), + up = scratch.path().join("up.fifo").display(), ); let spec = streamed( scratch.path(), @@ -1396,7 +1386,7 @@ fn streamed_stop_during_withdraw_is_a_cancel() { use std::sync::atomic::{AtomicBool, Ordering}; let scratch = dx_test_scratch::scratch("dx-lifecycle-").unwrap(); let sink = Sink::default(); - let script = "trap '' TERM; sleep 3"; + let script = format!("trap '' TERM; {}", blocked(scratch.path())); let spec = streamed( scratch.path(), vec!["/bin/sh".into(), "-c".into(), script.into()], @@ -1464,32 +1454,16 @@ fn lease_free(path: &std::path::Path) -> bool { } fn wait_lease_free(path: &std::path::Path) { - let deadline = Instant::now() + Duration::from_secs(20); - while !lease_free(path) { - // LCOV_EXCL_START - reason: failure-only arm or message, never evaluated when the test passes, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - assert!( - Instant::now() < deadline, - "the held lease never came free: {}", - path.display() - ); - std::thread::sleep(Duration::from_millis(50)); - // LCOV_EXCL_STOP - reason: end of excluded branch, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } + dx_test_scratch::wait::lock_free(path, Duration::from_secs(20)).unwrap(); } fn wait_alive(lock: &std::path::Path) { wait_armed(lock); - let deadline = Instant::now() + Duration::from_secs(10); - while !dx_testing::alive_lock_held(lock) { - // LCOV_EXCL_START - reason: failure-only arm or message, never evaluated when the test passes, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - assert!( - Instant::now() < deadline, - "probe never took its alive lock: {}", - lock.display() - ); - std::thread::sleep(Duration::from_millis(10)); - // LCOV_EXCL_STOP - reason: end of excluded branch, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } + assert!( + dx_testing::alive_lock_held(lock), + "probe never took its alive lock: {}", + lock.display() + ); } #[test] @@ -1851,8 +1825,9 @@ fn a_prepared_command_keeps_its_removed_variable_out_of_the_child() { #[test] fn a_stop_probe_ends_a_prepared_command_before_its_deadline() { let _fork = dx_testing::forking(); + let scratch = dx_test_scratch::scratch("dx-lifecycle-").unwrap(); let mut command = Command::new("/bin/sh"); - command.args(["-c", "sleep 30"]); + command.args(["-c", &blocked(scratch.path())]); let started = Instant::now(); let outcome = run_command_until( &mut command, @@ -1911,17 +1886,22 @@ fn stream_stdin_is_null_only_for_an_inherited_terminal_in_an_own_group() { fn a_stop_reaches_only_the_runs_still_registered() { let _fork = dx_testing::forking(); static TABLE: [Slot; FORWARD_SLOTS] = [const { Slot::new() }; FORWARD_SLOTS]; + static SENT: Mutex> = Mutex::new(Vec::new()); fn ignore(_: i32) {} + fn send(target: i32, signo: i32) { + SENT.lock().unwrap().push(target); + backend::send(target, signo); + } let scratch = dx_test_scratch::scratch("dx-forward-table").unwrap(); let (mut a, a_log) = counting_probe(scratch.path()); let other = dx_test_scratch::scratch("dx-forward-table-b").unwrap(); - let (b, b_log) = counting_probe(other.path()); + let (b, _) = counting_probe(other.path()); let first = Forwarding::register_in(&TABLE, -a.0.id().cast_signed()); let mut second = Forwarding::register_in(&TABLE, -b.0.id().cast_signed()); second.clear(); - forward_from(&TABLE, 2, ignore, backend::send); + forward_from(&TABLE, 2, ignore, send); + assert_eq!(*SENT.lock().unwrap(), [-a.0.id().cast_signed()]); assert_eq!(sigints(&a_log, 1), 1); - assert_eq!(sigints(&b_log, 1), 0); assert!(first.claimed()); assert!(!second.claimed()); assert_survived(&mut a); @@ -1978,10 +1958,7 @@ fn a_stop_seen_after_registering_sends_one_sigint() { if calls.fetch_add(1, Ordering::SeqCst) == 0 { return None; } - dx_test_scratch::eventually("sigint log", Duration::from_secs(10), || { - log.exists().then_some(()) - }) - .unwrap(); + dx_test_scratch::wait::path_appears(&log, Duration::from_secs(10)).unwrap(); Some(2) }; assert_eq!( @@ -2062,7 +2039,7 @@ fn a_drain_retries_interrupts_and_keeps_what_it_read_after_an_error() { fn a_child_that_ignores_term_is_killed_after_the_graceful_wait() { let _fork = dx_testing::forking(); let scratch = dx_test_scratch::scratch("dx-lifecycle-").unwrap(); - let script = "trap '' TERM; exec sleep 30"; + let script = format!("trap '' TERM; {}", blocked(scratch.path())); let spec = controlled_spec( scratch.path(), vec!["/bin/sh".into(), "-c".into(), script.into()], diff --git a/cli/process/src/procs_tests.rs b/cli/process/src/procs_tests.rs index 2e0a9719c6..d7e285f371 100644 --- a/cli/process/src/procs_tests.rs +++ b/cli/process/src/procs_tests.rs @@ -27,10 +27,9 @@ fn an_exited_child_with_an_open_handle_is_not_alive() { .spawn() .expect("spawn"); let pid = child.id(); - while child.try_wait().expect("poll").is_none() { - std::thread::sleep(std::time::Duration::from_millis(10)); - } + dx_test_scratch::wait::pid_gone(pid, std::time::Duration::from_secs(30)).unwrap(); assert!(!pid_alive(pid)); + child.wait().expect("wait"); } #[cfg(windows)] @@ -64,20 +63,26 @@ fn the_live_table_has_this_process_and_its_parent() { fn command_lines_see_a_child_with_a_marker_and_memory() { let _fork = dx_testing::forking(); let mut child = Command::new("cmd") - .args(["/C", "ping -n 30 127.0.0.1 >nul & rem dx-procs-marker"]) + .args(["/K", "echo ready& rem dx-procs-marker"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) .spawn() .expect("spawn"); let pid = child.id(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - let found = loop { - let found = command_lines() - .into_iter() - .find(|info| info.pid == pid && info.rss_bytes > 0); - if found.is_some() || std::time::Instant::now() >= deadline { - break found; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - }; + let stdout = child.stdout.take().expect("stdout"); + let ready = dx_test_scratch::wait::within( + "cmd running", + std::time::Duration::from_secs(30), + move || { + let mut line = String::new(); + std::io::BufRead::read_line(&mut std::io::BufReader::new(stdout), &mut line) + .map(|_| line) + }, + ) + .unwrap() + .expect("read cmd output"); + assert!(ready.starts_with("ready"), "{ready:?}"); + let found = command_lines().into_iter().find(|info| info.pid == pid); child.kill().expect("kill"); child.wait().expect("wait"); let info = found.expect("child listed"); @@ -142,11 +147,15 @@ fn an_unreaped_child_is_a_zombie() { .spawn() .expect("spawn"); let pid = child.id(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while !zombie(pid) { - assert!(std::time::Instant::now() < deadline, "no zombie"); - std::thread::sleep(std::time::Duration::from_millis(20)); - } + let raw = i32::try_from(pid).expect("pid fits"); + dx_test_scratch::wait::within( + "the child exiting", + std::time::Duration::from_secs(30), + move || dx_os_sys::process::await_exit_unreaped(raw), + ) + .unwrap() + .expect("waitid"); + assert!(zombie(pid), "no zombie"); assert!(!zombie(std::process::id())); child.wait().expect("wait"); } diff --git a/cli/process/src/runner_tests.rs b/cli/process/src/runner_tests.rs index 3121e483c6..7c850bc3b6 100644 --- a/cli/process/src/runner_tests.rs +++ b/cli/process/src/runner_tests.rs @@ -303,19 +303,7 @@ fn holding_run_does_not_inherit_held() { #[cfg(unix)] fn lock_comes_free(path: &std::path::Path) -> bool { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - while dx_atomic_fs::lease::try_lock_file(path, false) - .expect("probe") - .is_none() - { - // LCOV_EXCL_START - reason: failure-only retry, never reached when the lock is free at once, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - if std::time::Instant::now() >= deadline { - return false; - } - std::thread::sleep(std::time::Duration::from_millis(20)); - // LCOV_EXCL_STOP - reason: end of excluded branch, issue: 8104, policy: docs/cli/commands/build-test-coverage.md - } - true + dx_test_scratch::wait::lock_free(path, std::time::Duration::from_secs(2)).is_ok() } // LCOV_EXCL_START - reason: failure-only message, never evaluated when the test passes, issue: 8104, policy: docs/cli/commands/build-test-coverage.md diff --git a/cli/setup/src/prune/apply.rs b/cli/setup/src/prune/apply.rs index 743fffc618..5045d8e8ec 100644 --- a/cli/setup/src/prune/apply.rs +++ b/cli/setup/src/prune/apply.rs @@ -337,13 +337,8 @@ mod tests { } fn wait_for(path: &Path, what: &str) { - let start = std::time::Instant::now(); - while !path.exists() { - assert!( - start.elapsed() <= Duration::from_secs(30), - "timed out waiting for {what}" - ); - std::thread::sleep(Duration::from_millis(25)); + if let Err(error) = dx_test_scratch::wait::path_appears(path, Duration::from_secs(30)) { + panic!("{what}: {error}"); } } @@ -411,6 +406,14 @@ mod tests { fs::write(workspace.join("child-release"), b"go").expect("release the reader"); let status = child.wait().expect("reap the reader"); assert!(status.success(), "the reader exits cleanly"); + let lease = dx_atomic_fs::lease::lease_path( + &dx_path::state::local_dir(&workspace), + dx_atomic_fs::lease::GenerationUse::Generated, + &stale_gen, + ) + .expect("lease path"); + dx_test_scratch::wait::lock_free(&lease, Duration::from_secs(30)) + .expect("the reader's lease comes free"); let outcome = apply_plan(&workspace, &plan).expect("re-apply"); assert_eq!( outcome.skipped_leased_generations, diff --git a/cli/setup/src/prune/hold_tests.rs b/cli/setup/src/prune/hold_tests.rs index 935c402669..759e3c2451 100644 --- a/cli/setup/src/prune/hold_tests.rs +++ b/cli/setup/src/prune/hold_tests.rs @@ -276,7 +276,7 @@ fn hold_vs_apply_race_never_sees_partial_generation() { (GenerationUse::Generated, held.pair().generated.as_str()), ] { let sentinel = generation_dir(&workspace, kind, hex).join(SENTINEL); - std::thread::sleep(Duration::from_millis(2)); + std::thread::yield_now(); assert_eq!( fs::read_to_string(&sentinel).expect("held generation is whole"), hex @@ -353,11 +353,11 @@ fn a_streamed_child_keeps_its_selection_through_cleanup() { held: held.into_files(), }; let run = std::thread::spawn(move || run_streamed(spec, CleanupBudget::STANDARD, &|| None)); - let deadline = Instant::now() + WAIT; - while !(alive.exists() && dx_testing::alive_lock_held(&alive)) { - assert!(Instant::now() < deadline, "the probe never started"); - std::thread::sleep(Duration::from_millis(10)); - } + dx_testing::wait_armed(&alive); + assert!( + dx_testing::alive_lock_held(&alive), + "the probe never started" + ); select(&workspace, &setup_pair('3', '4')); let outcome = prune(&workspace); assert_eq!(outcome.skipped_leased_generations.len(), 2, "{outcome:?}"); @@ -370,18 +370,16 @@ fn a_streamed_child_keeps_its_selection_through_cleanup() { run.join().expect("run thread").expect("probe runs"), StreamOutcome::Exited(Exit::Code(0)) ); - let deadline = Instant::now() + WAIT; - loop { - let outcome = prune(&workspace); - if outcome.skipped_leased_generations.is_empty() { - break; - } - assert!( - Instant::now() < deadline, - "the lease outlived the child tree" - ); - std::thread::sleep(Duration::from_millis(50)); + let dx_dir = dx_path::state::local_dir(&workspace); + for (kind, hex) in [ + (GenerationUse::Environment, digest('1')), + (GenerationUse::Generated, digest('2')), + ] { + let lease = dx_atomic_fs::lease::lease_path(&dx_dir, kind, &hex).expect("lease path"); + dx_test_scratch::wait::lock_free(&lease, WAIT).expect("the lease outlived the child tree"); } + let outcome = prune(&workspace); + assert!(outcome.skipped_leased_generations.is_empty(), "{outcome:?}"); assert!( !old_gen.exists(), "cleanup removes the generation once the child is gone" diff --git a/cli/shim/BUILD.bazel b/cli/shim/BUILD.bazel index aae6b728d1..94e2192f5c 100644 --- a/cli/shim/BUILD.bazel +++ b/cli/shim/BUILD.bazel @@ -130,6 +130,7 @@ rust_test( deps = [ ":dx_shim", "//cli/digest:dx_digest", + "//cli/test_scratch:dx_test_scratch", "//tools/testing:dx_testing", "@crates//:tempfile", ], diff --git a/cli/shim/tests/e2e.rs b/cli/shim/tests/e2e.rs index 3415bb82f8..c4901da231 100644 --- a/cli/shim/tests/e2e.rs +++ b/cli/shim/tests/e2e.rs @@ -510,11 +510,13 @@ fn sigterm_mid_download_leaves_no_part_file() { .flatten() .any(|e| e.file_name().to_string_lossy().ends_with(".tmp")) }; - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); - while !has_part() { - assert!(std::time::Instant::now() < deadline, "no download started"); - std::thread::sleep(std::time::Duration::from_millis(20)); - } + dx_test_scratch::wait::watch_until( + &dir.join("download"), + "a download starting", + std::time::Duration::from_secs(20), + has_part, + ) + .unwrap(); Command::new("kill") .args(["-TERM", &child.id().to_string()]) .status() diff --git a/cli/shim/tests/support/mod.rs b/cli/shim/tests/support/mod.rs index 0eb7837e3e..5f5dd97cb8 100644 --- a/cli/shim/tests/support/mod.rs +++ b/cli/shim/tests/support/mod.rs @@ -91,7 +91,8 @@ fn serve(stream: TcpStream, routes: &Mutex>) { Reply::Status(code) => respond(&mut out, code, b"", 0), Reply::Stall => { drop(respond_partial(&mut out)); - std::thread::sleep(std::time::Duration::from_secs(60)); + drop(out.set_read_timeout(Some(std::time::Duration::from_secs(60)))); + drop(std::io::copy(&mut reader, &mut std::io::sink())); Ok(()) } }); diff --git a/cli/test_scratch/src/lib.rs b/cli/test_scratch/src/lib.rs index 5beb7514b1..20e0e02f1d 100644 --- a/cli/test_scratch/src/lib.rs +++ b/cli/test_scratch/src/lib.rs @@ -149,23 +149,6 @@ pub fn remove_directory_link(path: &Path) -> std::io::Result<()> { removed } -pub fn eventually( - what: &str, - deadline: std::time::Duration, - mut probe: impl FnMut() -> Option, -) -> Result { - let start = std::time::Instant::now(); - loop { - if let Some(value) = probe() { - return Ok(value); - } - if start.elapsed() >= deadline { - return Err(format!("timed out waiting for {what}")); - } - std::thread::sleep(std::time::Duration::from_millis(25)); - } -} - #[must_use] pub fn running_as_root() -> bool { #[cfg(unix)] @@ -353,28 +336,6 @@ mod tests { assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), ""); } - #[test] - fn eventually_returns_the_first_some() { - let mut calls = 0; - let got = eventually("x", std::time::Duration::from_secs(5), || { - calls += 1; - Some(7) - }) - .unwrap(); - assert_eq!((got, calls), (7, 1)); - } - - #[test] - fn eventually_retries_until_the_probe_succeeds() { - let mut calls = 0; - let got = eventually("x", std::time::Duration::from_secs(5), || { - calls += 1; - (calls == 3).then_some(calls) - }) - .unwrap(); - assert_eq!(got, 3); - } - #[cfg(unix)] #[test] fn running_as_root_matches_reading_a_mode_000_file() { @@ -386,14 +347,6 @@ mod tests { assert_eq!(running_as_root(), std::fs::read(&locked).is_ok()); } - #[test] - fn eventually_fails_after_the_deadline() { - assert_eq!( - eventually::<()>("a thing", std::time::Duration::from_millis(50), || None), - Err("timed out waiting for a thing".to_owned()) - ); - } - #[test] fn write_refuses_paths_that_leave_the_root() { let dir = scratch("dx-test-scratch-escape-").unwrap(); diff --git a/cli/test_scratch/src/wait.rs b/cli/test_scratch/src/wait.rs index ee3dd3eb53..4b0235d779 100644 --- a/cli/test_scratch/src/wait.rs +++ b/cli/test_scratch/src/wait.rs @@ -1,3 +1,4 @@ +use std::fs::File; use std::path::Path; use std::process::{Child, ExitStatus}; use std::sync::mpsc::{self, RecvTimeoutError}; @@ -61,17 +62,35 @@ pub fn watch_until( Ok(()) } -pub fn lock_free(path: &Path, limit: Duration) -> Result<(), String> { +fn lock_within( + path: &Path, + limit: Duration, + lock: fn(&File) -> std::io::Result<()>, +) -> Result { let file = std::fs::OpenOptions::new() .read(true) .write(true) .open(path) .map_err(|error| format!("open {}: {error}", path.display()))?; let what = format!("the lock on {} coming free", path.display()); - within(&what, limit, move || file.lock())? + within(&what, limit, move || lock(&file).map(|()| file))? .map_err(|error| format!("lock {}: {error}", path.display())) } +pub fn locked(path: &Path, limit: Duration) -> Result { + lock_within(path, limit, File::lock) +} + +pub fn locked_shared(path: &Path, limit: Duration) -> Result { + lock_within(path, limit, File::lock_shared) +} + +pub fn lock_free(path: &Path, limit: Duration) -> Result<(), String> { + locked(path, limit)? + .unlock() + .map_err(|error| format!("unlock {}: {error}", path.display())) +} + pub fn pid_gone(pid: u32, limit: Duration) -> Result<(), String> { match dx_os_sys::exit::wait_gone(pid, limit) { Ok(true) => Ok(()), diff --git a/cli/worktree/src/host.rs b/cli/worktree/src/host.rs index 4e592f95c3..701a7c8745 100644 --- a/cli/worktree/src/host.rs +++ b/cli/worktree/src/host.rs @@ -831,8 +831,8 @@ mod tests { let sub = dir.path().join("sub"); std::fs::create_dir_all(&sub).expect("sub"); assert!(!process_in(dir.path())); - let mut child = std::process::Command::new("sleep") - .arg("30") + let mut child = std::process::Command::new("cat") + .stdin(std::process::Stdio::piped()) .current_dir(&sub) .spawn() .expect("spawn"); @@ -849,9 +849,9 @@ mod tests { let dir = tempfile::tempdir().expect("dir"); let bin = tempfile::tempdir().expect("bin"); let git = bin.path().join("git"); - std::os::unix::fs::symlink("/bin/sleep", &git).expect("link"); + std::os::unix::fs::symlink("/bin/cat", &git).expect("link"); let mut child = std::process::Command::new(&git) - .arg("30") + .stdin(std::process::Stdio::piped()) .current_dir(dir.path()) .spawn() .expect("spawn"); diff --git a/cli/worktree/src/tests.rs b/cli/worktree/src/tests.rs index fd5c77c8ee..a4926f1a40 100644 --- a/cli/worktree/src/tests.rs +++ b/cli/worktree/src/tests.rs @@ -3937,7 +3937,7 @@ mod hooks { for command in [ "echo dx test", "cat tools/dx", - "timeout 5 sleep 1", + "timeout 5 true", "bash -c 'echo dx'", "bash -euo pipefail script.sh", "bash -o pipefail -c 'echo hi'", From 91576ca250f260d1de531b2b5337a72fff2984a2 Mon Sep 17 00:00:00 2001 From: Martin Kuntz Jacobsen Date: Tue, 24 Nov 2026 09:45:59 +0100 Subject: [PATCH 3/3] tests: review fixes for the cli event waits Park in a function that never returns, bound the signals child with exit_within so a broken stop path fails instead of hanging, keep the SIGINT wait at 5 s, and keep failure-only messages on covered lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xut2hyBydsMejdwk6QdKus --- cli/lock/tests/fixture_resolver.rs | 10 +++++++--- cli/os_sys/src/signals_tests.rs | 14 +++++++++++--- cli/process/src/lifecycle_tests.rs | 5 ++--- cli/setup/src/prune/apply.rs | 5 ++--- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/cli/lock/tests/fixture_resolver.rs b/cli/lock/tests/fixture_resolver.rs index ebf9078c7f..249cdf5eb4 100644 --- a/cli/lock/tests/fixture_resolver.rs +++ b/cli/lock/tests/fixture_resolver.rs @@ -97,12 +97,16 @@ fn resolve(index_path: &str) -> Result { Ok(json!({ "packages": listed }).to_string()) } +fn park_forever() -> ! { + loop { + std::thread::park(); + } +} + fn main() -> ExitCode { let index = std::env::args().nth(1).unwrap_or_default(); if index == "--hang" { - loop { - std::thread::park(); - } + park_forever(); } match resolve(&index) { Ok(resolution) => { diff --git a/cli/os_sys/src/signals_tests.rs b/cli/os_sys/src/signals_tests.rs index 5b679585a3..bd81b5017c 100644 --- a/cli/os_sys/src/signals_tests.rs +++ b/cli/os_sys/src/signals_tests.rs @@ -55,6 +55,10 @@ fn unlink_on_stop_child() { unlink_on_stop(Path::new(&path)).expect("watch"); let pid = i32::try_from(std::process::id()).expect("pid fits pid_t"); crate::process::signal(pid, libc::SIGTERM).expect("signal self"); + park_forever(); +} + +fn park_forever() -> ! { loop { std::thread::park(); } @@ -65,12 +69,16 @@ fn sigterm_removes_the_watched_path_and_exits_143() { let dir = std::env::var_os("TEST_TMPDIR").map_or_else(std::env::temp_dir, Into::into); let part = dir.join(format!("unlink-on-stop-{}.part", std::process::id())); std::fs::write(&part, b"partial").expect("write"); - let status = std::process::Command::new(std::env::current_exe().expect("exe")) + let child = std::process::Command::new(std::env::current_exe().expect("exe")) .args(["--exact", "signals::signals_tests::unlink_on_stop_child"]) .env(UNLINK_CHILD, &part) - .status() + .spawn() .expect("run the child"); - assert_eq!(status.code(), Some(143)); + let exit = dx_test_scratch::wait::exit_within(child, std::time::Duration::from_secs(30)) + .expect("wait for the child"); + let exited_143 = + matches!(&exit, dx_test_scratch::wait::Exit::Exited(status) if status.code() == Some(143)); + assert!(exited_143, "{exit:?}"); assert!(!part.exists()); } diff --git a/cli/process/src/lifecycle_tests.rs b/cli/process/src/lifecycle_tests.rs index b06d2eeee7..a9e00324f8 100644 --- a/cli/process/src/lifecycle_tests.rs +++ b/cli/process/src/lifecycle_tests.rs @@ -1121,7 +1121,7 @@ fn sigints(log: &std::path::Path, expected: usize) -> usize { dx_test_scratch::wait::watch_until( log, "the probe counting SIGINT", - Duration::from_secs(10), + Duration::from_secs(5), || count() >= expected, ) .unwrap(); @@ -1461,8 +1461,7 @@ fn wait_alive(lock: &std::path::Path) { wait_armed(lock); assert!( dx_testing::alive_lock_held(lock), - "probe never took its alive lock: {}", - lock.display() + "probe never took its alive lock" ); } diff --git a/cli/setup/src/prune/apply.rs b/cli/setup/src/prune/apply.rs index 5045d8e8ec..471f6ecbd2 100644 --- a/cli/setup/src/prune/apply.rs +++ b/cli/setup/src/prune/apply.rs @@ -337,9 +337,8 @@ mod tests { } fn wait_for(path: &Path, what: &str) { - if let Err(error) = dx_test_scratch::wait::path_appears(path, Duration::from_secs(30)) { - panic!("{what}: {error}"); - } + dx_test_scratch::wait::path_appears(path, Duration::from_secs(30)) + .unwrap_or_else(|error| panic!("{what}: {error}")); } #[test]