Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: replace wait-timeout so a signal-handler panic can't abort wt (#3857)
Worktrunk Bot831bb97cfb3f
diff --git a/Cargo.lock b/Cargo.lockindex 1b6565a53..0898b785d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3284,6 +3284,17 @@ dependencies = ["lazy_static",]+[[package]]+name = "shared_child"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"+dependencies = [+ "libc",+ "sigchld",+ "windows-sys 0.60.2",+]+[[package]]name = "shared_library"version = "0.1.9"@@ -3336,6 +3347,17 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]+name = "sigchld"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"+dependencies = [+ "libc",+ "os_pipe",+ "signal-hook 0.3.18",+]+[[package]]name = "signal-hook"version = "0.3.18"@@ -4283,15 +4305,6 @@ dependencies = ["utf8parse",]-[[package]]-name = "wait-timeout"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"-dependencies = [- "libc",-]-[[package]]name = "walkdir"version = "2.5.0"@@ -4851,6 +4864,7 @@ dependencies = ["serde","serde_json","sha2 0.11.0",+ "shared_child","shell-escape","shellexpand","signal-hook 0.4.4",@@ -4875,7 +4889,6 @@ dependencies = ["urlencoding","vergen-gitcl","vt100",- "wait-timeout","which","wrap-ansi","wt-perf",diff --git a/Cargo.toml b/Cargo.tomlindex 52c50009b..ba77dc04f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -250,7 +250,11 @@ petname = { version = "=3.2.0", default-features = false, features = ["default-wpetname-macros = "=3.2.0"tempfile = "3.27"-wait-timeout = "0.2"++# Timed waits on child processes (`Cmd::timeout`, `Cmd::delayed_stream`, the+# picker's pager). Replaced `wait-timeout`, whose SIGCHLD handler aborts the+# process when its self-pipe write fails — see "Timed waits" in `shell_exec`.+shared_child = "1.1"# Interactive picker (`wt switch`) TUI stack, pulled in only by the `cli`# feature's `dep:` entries. These are platform-neutral (skim 4.x is thediff --git a/src/commands/picker/pager.rs b/src/commands/picker/pager.rsindex 7139d3d1d..b4e521e99 100644--- a/src/commands/picker/pager.rs+++ b/src/commands/picker/pager.rs@@ -7,7 +7,7 @@ use std::process::{Command, Stdio};use std::sync::OnceLock;use std::time::Duration;-use wait_timeout::ChildExt;+use shared_child::SharedChild;use worktrunk::config::UserConfig;use worktrunk::shell::extract_filename_from_path;@@ -91,7 +91,7 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S.stderr(Stdio::null()).env("COLUMNS", width.to_string());worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- let mut child = match cmd.spawn() {+ let child = match SharedChild::spawn(&mut cmd) {Ok(child) => child,Err(e) => {tracing::debug!(error = %e, "Failed to spawn pager: {}", e);@@ -101,7 +101,7 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S// Write input to stdin in a thread to avoid deadlock.// Thread will unblock when: (a) write completes, or (b) pipe breaks (pager exits/killed).- let stdin = child.stdin.take();+ let stdin = child.take_stdin();let input = text.to_string();let writer_thread = std::thread::spawn(move || {if let Some(mut stdin) = stdin {@@ -111,7 +111,7 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S});// Read output in a thread to avoid deadlock (can't read stdout after stdin fills)- let stdout = child.stdout.take();+ let stdout = child.take_stdout();let reader_thread = std::thread::spawn(move || {stdout.map(|mut stdout| {let mut output = Vec::new();@@ -133,15 +133,10 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S}tracing::debug!(status = %status, "Pager exited with status: {}", status);}- Ok(None) => {- // Timed out - kill pager and clean up- tracing::debug!(timeout = ?PAGER_TIMEOUT, "Pager timed out after {:?}", PAGER_TIMEOUT);- let _ = child.kill();- let _ = child.wait();- let _ = reader_thread.join();- }- Err(e) => {- tracing::debug!(error = %e, "Failed to wait for pager: {}", e);+ // Timed out, or the wait failed outright. Either way the pager owes us+ // nothing more: kill it, reap it, and fall back to the raw text below.+ outcome => {+ tracing::debug!(?outcome, timeout = ?PAGER_TIMEOUT, "Pager did not exit within {:?}", PAGER_TIMEOUT);let _ = child.kill();let _ = child.wait();let _ = reader_thread.join();@@ -213,6 +208,27 @@ mod tests {assert_eq!(result, "HELLO WORLD");}+ /// A pager that never exits must not freeze skim's event loop: it is killed at+ /// `PAGER_TIMEOUT` and the preview falls back to the unpaged text.+ ///+ /// Explicit `exec`, because the kill reaches the pager and not its children:+ /// a grandchild inherits the stdout pipe, and the reader thread this function+ /// joins blocks until *it* exits. `sh -c "sleep 30"` forks here, so without+ /// the `exec` the wait runs the full 30 s despite the pager being dead.+ #[test]+ #[cfg(unix)]+ fn test_pipe_through_pager_times_out() {+ let input = "line 1\nline 2";+ let start = std::time::Instant::now();+ let result = pipe_through_pager(input, "exec sleep 30", 80);+ let elapsed = start.elapsed();+ assert_eq!(result, input);+ assert!(+ elapsed < PAGER_TIMEOUT * 4,+ "the timeout did not bound the wait: {elapsed:?}"+ );+ }+#[test]fn test_pipe_through_pager_invalid_command() {// Invalid pager command should return original textdiff --git a/src/shell_exec.rs b/src/shell_exec.rsindex bd29e4110..53fcfc17d 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -46,6 +46,25 @@//! keep running as orphans. [`cancel_background_commands`] lets the foreground//! thread stop that work — both what is running and what has yet to start —//! once nobody is left to read its results.+//!+//! ## Timed waits+//!+//! Unix has no "wait for this child, but give up after N milliseconds" syscall,+//! so every deadline here (`Cmd::timeout`, `Cmd::delayed_stream`, the picker's+//! pager) goes through [`shared_child::SharedChild`]: `waitid(WNOWAIT)` for the+//! blocking wait, and for the timed one a `SIGCHLD` self-pipe it polls against+//! the deadline. Windows needs none of that — it waits the process handle.+//!+//! **Why not `wait-timeout`.** wt used it until #3856. Its `SIGCHLD` handler+//! pokes an `AF_UNIX` socketpair with `send()` and `panic!`s on any errno but+//! `WouldBlock`; the handler is `extern "C"`, so that panic cannot unwind and+//! goes straight to `abort()`. Under a sandbox that denies the send (the Codex+//! CLI's `workspace-write` mode) every timed wait in wt became an uncatchable+//! `SIGABRT` with no diagnostic. `shared_child` reaches the same signal through+//! `signal_hook`, whose wake deliberately discards write errors — a missed+//! wakeup costs at worst a wait that runs to its deadline, which is what a+//! deadline is for. It also probes the wake fd and falls back to `write()` on a+//! pipe, so the syscall that sandbox denies is not even on the path.use std::collections::BTreeSet;use std::ffi::{OsStr, OsString};@@ -58,7 +77,7 @@ use std::sync::{Arc, Mutex, OnceLock};use std::time::{Duration, Instant};use anyhow::Context;-use wait_timeout::ChildExt;+use shared_child::SharedChild;use crate::git::{GitError, WorktrunkError};use crate::sync::Semaphore;@@ -158,9 +177,8 @@ fn is_cancellable_thread() -> bool {/// Register a freshly spawned child as cancellable for as long as the returned/// guard lives. Returns `None` when this thread's commands aren't subject to/// cancellation (see [`is_cancellable_thread`]).-fn track_if_cancellable(child: &std::process::Child) -> Option<BackgroundPid> {+fn track_if_cancellable(pid: u32) -> Option<BackgroundPid> {is_cancellable_thread().then(|| {- let pid = child.id();BACKGROUND_PIDS.lock().unwrap().insert(pid);let guard = BackgroundPid(pid);// Re-read after publishing the PID, closing the window between this@@ -968,15 +986,15 @@ fn run_with_timeout_impl(cmd.process_group(0);}- let mut child = cmd- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()?;- let _tracked = track_if_cancellable(&child);+ let child = SharedChild::spawn(+ cmd.stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped()),+ )?;+ let _tracked = track_if_cancellable(child.id());- let mut child_stdout = child.stdout.take();- let mut child_stderr = child.stderr.take();+ let mut child_stdout = child.take_stdout();+ let mut child_stderr = child.take_stderr();std::thread::scope(|s| {let stdout_thread = s.spawn(|| {@@ -996,8 +1014,8 @@ fn run_with_timeout_impl(Ok::<_, std::io::Error>(buf)});- match child.wait_timeout(timeout)? {- Some(status) => {+ match child.wait_timeout(timeout) {+ Ok(Some(status)) => {let stdout = stdout_thread.join().unwrap()?;let stderr = stderr_thread.join().unwrap()?;Ok(std::process::Output {@@ -1006,14 +1024,18 @@ fn run_with_timeout_impl(stderr,})}- None => {+ // Timed out, or the wait itself failed. A failed wait has to tear the+ // tree down too: propagating it instead would leave the child running,+ // and the scope's join then blocks on `read_to_end` until the child+ // closes its pipes — the caller waits out the full runtime the timeout+ // exists to bound, and gets back an error that isn't `TimedOut`.+ outcome => {kill_timed_out_tree(child.id());let _ = child.kill();let _ = child.wait();- Err(std::io::Error::new(- ErrorKind::TimedOut,- "command timed out",- ))+ Err(outcome.err().unwrap_or_else(|| {+ std::io::Error::new(ErrorKind::TimedOut, "command timed out")+ }))}}})@@ -1025,6 +1047,12 @@ fn run_with_timeout_impl(/// pid is the pgid and the TERM → KILL escalation reaches every member. SIGTERM/// first for the same reason [`signal_background_pid`] uses it: git's lockfile/// handlers run on TERM, so an interrupted git cleans up after itself.+///+/// Signalling by pid is safe here because the caller still holds an unreaped+/// [`shared_child::SharedChild`]: a timed wait uses `waitid(WNOWAIT)`, so a child+/// that exited on the deadline's other side is a zombie that keeps its pid+/// reserved until the caller's own `wait()`. The pid cannot name a different+/// process group by the time the signal lands.#[cfg(unix)]fn kill_timed_out_tree(pid: u32) {forward_signal_with_escalation(pid as i32, signal_hook::consts::SIGTERM);@@ -1611,7 +1639,7 @@ impl Cmd {match cmd.spawn() {Ok(mut child) => {- let _tracked = track_if_cancellable(&child);+ let _tracked = track_if_cancellable(child.id());// Write stdin data in an inner scope so the handle DROPS// (closing the pipe) before `wait_with_output` — otherwise a// child that reads stdin to EOF (e.g. `git … --stdin`) blocks@@ -1641,7 +1669,7 @@ impl Cmd {.stderr(Stdio::piped());match cmd.spawn() {Ok(child) => {- let _tracked = track_if_cancellable(&child);+ let _tracked = track_if_cancellable(child.id());child.wait_with_output()}Err(e) => Err(e),@@ -1774,7 +1802,7 @@ impl Cmd {return Err(e);}};- let _first_tracked = track_if_cancellable(&first_child);+ let _first_tracked = track_if_cancellable(first_child.id());let first_stdout = first_child.stdout.take()@@ -1814,7 +1842,7 @@ impl Cmd {return Err(e);}};- let _second_tracked = track_if_cancellable(&second_child);+ let _second_tracked = track_if_cancellable(second_child.id());// `first`'s stderr must be drained concurrently with `second`'s// execution; otherwise pathological stderr volume (~64 KiB pipe@@ -2152,7 +2180,7 @@ impl Cmd {.stdout(Stdio::piped()).stderr(Stdio::piped());- let mut child = match cmd.spawn() {+ let child = match SharedChild::spawn(&mut cmd) {Ok(child) => child,Err(e) => {trace.fail(&e);@@ -2160,8 +2188,8 @@ impl Cmd {}};- let stdout = child.stdout.take().expect("stdout was piped");- let stderr = child.stderr.take().expect("stderr was piped");+ let stdout = child.take_stdout().expect("stdout was piped");+ let stderr = child.take_stderr().expect("stderr was piped");// Shared state: when true, output streams directly; when false, buffers.let streaming = Arc::new(AtomicBool::new(false));@@ -2644,6 +2672,42 @@ mod tests {assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);}+ /// The `wait-timeout` crate has to stay out of the dependency graph, however+ /// it gets there.+ ///+ /// Its `SIGCHLD` handler pokes a socketpair with `send()` and `panic!`s on any+ /// errno but `WouldBlock`. That handler is `extern "C"`, so the panic cannot+ /// unwind — it goes straight to `abort()`. Under a sandbox that denies the send+ /// (the Codex CLI's `workspace-write` mode), every timed wait in `wt` became an+ /// uncatchable `SIGABRT` with no diagnostic (#3856). `shared_child` wakes+ /// through `signal_hook`, which discards wake-write errors by design.+ ///+ /// The lockfile is read at runtime, not `include_str!`d: a compile-time embed+ /// has to ship in every packaged build, which `embedded_assets_ship_in_package`+ /// enforces and `Cargo.lock` doesn't satisfy. Tests only ever run from the+ /// source tree, so the manifest dir is always there.+ #[test]+ fn test_wait_timeout_crate_stays_out_of_the_dependency_graph() {+ let lockfile = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock");+ let lockfile = std::fs::read_to_string(&lockfile).expect("read Cargo.lock");+ assert!(+ !lockfile.contains("name = \"wait-timeout\""),+ "wait-timeout is back in the dependency graph; its SIGCHLD handler \+ aborts wt when the self-pipe write fails (#3856)"+ );+ }++ /// A command that can't be spawned at all fails as a spawn error, not as a+ /// timeout — the deadline path never starts, so the caller doesn't wait it out.+ #[test]+ fn test_cmd_timeout_surfaces_a_spawn_failure() {+ let err = Cmd::new("worktrunk-no-such-program-3856")+ .timeout(Duration::from_secs(30))+ .run()+ .unwrap_err();+ assert_ne!(err.kind(), std::io::ErrorKind::TimedOut);+ }+/// The timeout has to bound wall-clock, not just signal the direct child./// A grandchild inherits the child's stderr pipe, so one that survives the/// kill holds the write end open and the output readers block on it — which