Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(tether): propagate supervised command failures (#4598)

Worktrunk Botcf5b0153719f
diff --git a/src/commands/step/tether.rs b/src/commands/step/tether.rs
index 3afa6a801..221fb1be9 100644
--- a/src/commands/step/tether.rs
+++ b/src/commands/step/tether.rs
@@ -28,6 +28,7 @@
use std::path::Path;
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use anyhow::{Context, Result};
@@ -89,24 +90,38 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
let id = child.id();
// Reaper: polls for worktree removal or command interruption, then kills
- // the tree so the supervised child exits and `wait` returns.
+ // the tree so the supervised child exits and `wait` returns. It records
+ // the teardown first, so the status of a command it killed is not
+ // mistaken for the command failing.
+ let torn_down = Arc::new(AtomicBool::new(false));
if worktree.is_some() || cfg!(unix) {
+ let torn_down = Arc::clone(&torn_down);
std::thread::spawn(move || {
while !worktree.as_deref().is_some_and(worktree_gone) && !interrupted() {
std::thread::sleep(POLL_INTERVAL);
}
+ torn_down.store(true, Ordering::SeqCst);
kill_process_tree(id);
});
}
// Block until the child exits — killed by the reaper, or on its own.
+ // Not `ForegroundSignals::wait`: it reads a child's SIGTERM death as the
+ // command being cancelled, and here that SIGTERM is the reaper's own
+ // teardown. Cancellation comes only from signals this process received.
#[cfg(unix)]
- let waited = signals.wait(&child).map(|outcome| outcome.status);
+ let wait_result = {
+ let forwarder = signals.forward_to_children(vec![Arc::clone(&child)], || {});
+ let waited = worktrunk::shell_exec::wait_shared_child(&child, None);
+ let admission = forwarder.admission_interrupt_signal();
+ let stopped = forwarder.stop();
+ waited.and_then(|status| Ok((status, stopped?.or(admission))))
+ };
#[cfg(windows)]
- let waited = child.wait();
- match waited {
- Ok(status) => trace.complete(status.success()),
- Err(e) => trace.fail(&e),
+ let wait_result = child.wait().map(|status| (status, None));
+ match &wait_result {
+ Ok((status, _)) => trace.complete(status.success()),
+ Err(e) => trace.fail(e),
}
// Final sweep: on a self-exit, descendants may still be running (Unix:
@@ -116,6 +131,15 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
// A reaper still sleeping between polls (the command self-exited) dies
// with this process when it returns.
+ let (status, cancellation) = wait_result.context("Failed to wait for tethered command")?;
+ if let Some(signal) = cancellation {
+ return Err(worktrunk::git::WorktrunkError::Interrupted { signal, hint: None }.into());
+ }
+ // Teardown on worktree removal is tether's normal job; only a command
+ // that exits on its own reports its status.
+ if !status.success() && !torn_down.load(Ordering::SeqCst) {
+ return Err(worktrunk::git::WorktrunkError::from_child_status(&status, None).into());
+ }
Ok(())
}
diff --git a/tests/integration_tests/step_tether.rs b/tests/integration_tests/step_tether.rs
index 8c75d345a..3121aa3cf 100644
--- a/tests/integration_tests/step_tether.rs
+++ b/tests/integration_tests/step_tether.rs
@@ -93,7 +93,7 @@ fn test_tether_kills_process_group_when_worktree_removed(mut repo: TestRepo) {
// Clean up before asserting so a failure can't leak the sleeps.
let _ = kill(Pid::from_raw(-pgid), nix::sys::signal::Signal::SIGKILL);
let _ = child.kill();
- let _ = child.wait();
+ let status = child.wait().expect("wait for tether supervisor");
let _ = std::fs::remove_dir_all(repo.home_path().join("trash"));
assert!(
@@ -104,6 +104,10 @@ fn test_tether_kills_process_group_when_worktree_removed(mut repo: TestRepo) {
supervisor_exited,
"[{mechanism}] the tether supervisor must exit after teardown"
);
+ assert!(
+ status.success(),
+ "[{mechanism}] teardown on worktree removal is not a failure: {status:?}"
+ );
}
}
@@ -138,7 +142,7 @@ fn test_tether_kills_process_group_when_command_exits(repo: TestRepo) {
/// that command before it exits.
#[rstest]
fn test_tether_kills_process_group_when_interrupted(repo: TestRepo) {
- use std::os::unix::process::CommandExt;
+ use std::os::unix::process::{CommandExt, ExitStatusExt};
let pidfile = repo.home_path().join("tether-interrupted.pgid");
let snippet = format!(
@@ -151,7 +155,7 @@ fn test_tether_kills_process_group_when_interrupted(repo: TestRepo) {
.current_dir(repo.path())
.stdin(Stdio::null())
.stdout(Stdio::null())
- .stderr(Stdio::null())
+ .stderr(Stdio::piped())
.process_group(0);
let mut supervisor = command.spawn().expect("spawn wt step tether");
wait_for_file_content(&pidfile);
@@ -177,10 +181,16 @@ fn test_tether_kills_process_group_when_interrupted(repo: TestRepo) {
// Clean up before asserting so a failure cannot leak the sleep.
let _ = kill(Pid::from_raw(-pgid), nix::sys::signal::Signal::SIGKILL);
let _ = supervisor.kill();
- let _ = supervisor.wait();
+ let output = supervisor
+ .wait_with_output()
+ .expect("wait for tether supervisor");
assert!(supervisor_exited, "the supervisor should exit after Ctrl-C");
assert!(group_gone, "Ctrl-C must kill the supervised process group");
+ // Cancellation exits as interrupted, without reporting the child's
+ // termination as a failure.
+ assert_eq!(output.status.signal(), Some(2), "{output:?}");
+ assert_eq!(String::from_utf8_lossy(&output.stderr), "");
}
/// The global `-C <dir>` flag runs the tethered command in that directory —
@@ -226,3 +236,15 @@ fn test_tether_runs_command_in_working_dir(repo: TestRepo) {
"the tethered command must run in the -C directory"
);
}
+
+#[rstest]
+fn test_tether_propagates_command_exit_status(repo: TestRepo) {
+ let status = repo
+ .wt_command()
+ .args(["step", "tether", "--", "sh", "-c", "exit 7"])
+ .current_dir(repo.path())
+ .status()
+ .expect("run wt step tether");
+
+ assert_eq!(status.code(), Some(7));
+}