Skip to content

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

fix(concurrent): report originating signal as wt's exit code after escalation (#2724)

Maximilian Roos1fa70d3e08d8
diff --git a/src/output/concurrent.rs b/src/output/concurrent.rs
index 92df8f11e..50db133ce 100644
--- a/src/output/concurrent.rs
+++ b/src/output/concurrent.rs
@@ -36,6 +36,10 @@
use std::io::{BufRead, BufReader, Read, Write};
use std::path::Path;
use std::process::{Child, Stdio};
+#[cfg(unix)]
+use std::sync::Arc;
+#[cfg(unix)]
+use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::mpsc::{self, Sender};
use std::thread;
use std::time::Instant;
@@ -165,14 +169,54 @@ pub fn run_concurrent_commands(
}
#[cfg(unix)]
- {
- // All children have exited — shut the signal forwarder down.
- signal_thread.stop();
+ let originating_signal = {
+ // All children have exited — shut the signal forwarder down. Returns
+ // the first signal the forwarder observed (None if no signal arrived).
+ signal_thread.stop()
+ };
+ #[cfg(not(unix))]
+ let originating_signal: Option<i32> = None;
+
+ // If wt's forwarder escalated SIGINT → SIGTERM → SIGKILL, a child may have
+ // died from SIGTERM (or SIGKILL) even though the user only sent SIGINT.
+ // From the user's outside view, the originating signal is what they sent;
+ // wt's internal escalation is an implementation detail that shouldn't
+ // surface as a different exit code (e.g., 143 instead of 130). Override
+ // each child's reported signal with the originating signal so wt's
+ // `exit_code()` and `interrupt_exit_code()` reflect the user's intent.
+ if let Some(orig) = originating_signal {
+ for outcome in &mut outcomes {
+ override_with_originating_signal(outcome, orig);
+ }
}
Ok(outcomes)
}
+/// Replace a child's signal-derived `ChildProcessExited` error with one whose
+/// `signal` / `code` / `message` reflect the originating signal wt received
+/// (rather than whichever signal the forwarder's escalation chain ultimately
+/// killed the child with). No-op if the outcome isn't a signal-derived error.
+fn override_with_originating_signal(outcome: &mut anyhow::Result<()>, originating: i32) {
+ let Err(err) = outcome else { return };
+ let Some(WorktrunkError::ChildProcessExited {
+ signal: Some(child_sig),
+ ..
+ }) = err.downcast_ref::<WorktrunkError>()
+ else {
+ return;
+ };
+ if *child_sig == originating {
+ return;
+ }
+ *outcome = Err(WorktrunkError::ChildProcessExited {
+ code: 128 + originating,
+ message: format!("terminated by signal {originating}"),
+ signal: Some(originating),
+ }
+ .into());
+}
+
/// Serial fallback for `WORKTRUNK_TEST_SERIAL_CONCURRENT`.
///
/// Runs each command to completion before starting the next — same prefix-line
@@ -408,15 +452,24 @@ fn render_prefix(index: usize, label: &str, width: usize) -> String {
struct SignalForwarder {
handle: signal_hook::iterator::Handle,
listener: thread::JoinHandle<()>,
+ /// First signal the forwarder observed, or 0 if none arrived. Lets the
+ /// caller report the user's originating signal (e.g., SIGINT) as wt's
+ /// exit code even when escalation ultimately killed the child with a
+ /// later signal (e.g., SIGTERM/SIGKILL).
+ originating_signal: Arc<AtomicI32>,
}
#[cfg(unix)]
impl SignalForwarder {
- fn stop(self) {
+ fn stop(self) -> Option<i32> {
// Closing the signal-hook handle unblocks `Signals::forever()` so
// the listener thread returns; join it to avoid a leak.
self.handle.close();
let _ = self.listener.join();
+ match self.originating_signal.load(Ordering::SeqCst) {
+ 0 => None,
+ sig => Some(sig),
+ }
}
}
@@ -426,9 +479,16 @@ fn spawn_signal_forwarder(
pgids: Vec<i32>,
) -> SignalForwarder {
let handle = signals.handle();
+ let originating_signal = Arc::new(AtomicI32::new(0));
+ let originating = Arc::clone(&originating_signal);
let listener = thread::spawn(move || {
let mut seen_once = false;
for sig in signals.forever() {
+ // Record the user's first signal so the caller can report it as
+ // wt's exit code regardless of any internal escalation. Only the
+ // first wins — later signals here are either the user impatiently
+ // re-pressing Ctrl-C or wt's own escalation chain firing.
+ let _ = originating.compare_exchange(0, sig, Ordering::SeqCst, Ordering::SeqCst);
if !seen_once {
// First signal: graceful escalation per child
// (SIGINT → SIGTERM → SIGKILL with grace windows).
@@ -449,7 +509,11 @@ fn spawn_signal_forwarder(
}
});
- SignalForwarder { handle, listener }
+ SignalForwarder {
+ handle,
+ listener,
+ originating_signal,
+ }
}
#[cfg(test)]
@@ -543,4 +607,85 @@ mod tests {
let outcomes = run_concurrent_commands(&[]).expect("no spawn should happen");
assert!(outcomes.is_empty());
}
+
+ /// `override_with_originating_signal` table-test: covers the four shapes
+ /// of outcome — `Ok`, non-`WorktrunkError` `Err`, exit-code `Err` (no
+ /// signal), and signal-derived `Err` matching vs differing from the
+ /// originating signal. Only the differing-signal case mutates.
+ #[test]
+ fn test_override_with_originating_signal() {
+ let originating = 2; // SIGINT
+
+ // Ok: untouched.
+ let mut ok: anyhow::Result<()> = Ok(());
+ override_with_originating_signal(&mut ok, originating);
+ assert!(ok.is_ok());
+
+ // Err but not WorktrunkError: untouched.
+ let mut other: anyhow::Result<()> = Err(anyhow::anyhow!("spawn failed"));
+ override_with_originating_signal(&mut other, originating);
+ assert_eq!(other.unwrap_err().to_string(), "spawn failed");
+
+ // ChildProcessExited with no signal (plain non-zero exit): untouched.
+ let mut exit_err: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "exit status: 1".into(),
+ signal: None,
+ }
+ .into());
+ override_with_originating_signal(&mut exit_err, originating);
+ let err = exit_err.unwrap_err();
+ let we = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ we,
+ WorktrunkError::ChildProcessExited {
+ signal: None,
+ code: 1,
+ ..
+ }
+ ));
+
+ // ChildProcessExited with same signal as originating: untouched.
+ let mut same: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {
+ code: 130,
+ message: "terminated by signal 2".into(),
+ signal: Some(2),
+ }
+ .into());
+ override_with_originating_signal(&mut same, originating);
+ let err = same.unwrap_err();
+ let we = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ we,
+ WorktrunkError::ChildProcessExited {
+ signal: Some(2),
+ code: 130,
+ ..
+ }
+ ));
+
+ // ChildProcessExited with different signal (escalation case):
+ // overridden to the originating signal's code/message/signal.
+ let mut escalated: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {
+ code: 143,
+ message: "terminated by signal 15".into(),
+ signal: Some(15),
+ }
+ .into());
+ override_with_originating_signal(&mut escalated, originating);
+ let err = escalated.unwrap_err();
+ let we = err.downcast_ref::<WorktrunkError>().unwrap();
+ match we {
+ WorktrunkError::ChildProcessExited {
+ code,
+ message,
+ signal,
+ } => {
+ assert_eq!(*code, 130);
+ assert_eq!(*signal, Some(2));
+ assert_eq!(message, "terminated by signal 2");
+ }
+ _ => panic!("expected ChildProcessExited, got {we:?}"),
+ }
+ }
}
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 68c3f60aa..73f743ce7 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -1397,6 +1397,57 @@ two = "sh -c 'echo start-two >> slow_two.log; sleep 30; echo done-two >> slow_tw
}
}
+/// When children trap SIGINT, wt's forwarder escalates SIGINT → SIGTERM,
+/// and the children actually die from SIGTERM. But the user only sent SIGINT
+/// — wt's exit code must reflect that (130), not the escalated signal (143).
+/// Otherwise users who Ctrl-C a `wt step <concurrent-alias>` whose children
+/// happen to swallow SIGINT (or are slow under load) see "terminated by
+/// SIGTERM" / exit 143 even though they pressed Ctrl-C.
+#[rstest]
+#[cfg(unix)]
+fn test_alias_concurrent_sigint_reports_origin_after_escalation(repo: TestRepo) {
+ use crate::common::wait_for_file_content;
+ use nix::sys::signal::{Signal, kill};
+ use nix::unistd::Pid;
+ use std::os::unix::process::CommandExt;
+ use std::process::Stdio;
+
+ // Children trap SIGINT (ignore it) but NOT SIGTERM — so wt's
+ // SIGINT → SIGTERM escalation is what actually kills them.
+ repo.write_test_config(
+ r#"
+[aliases.intignored]
+one = "sh -c 'trap \"\" INT; echo start-one >> ignored_one.log; sleep 30'"
+two = "sh -c 'trap \"\" INT; echo start-two >> ignored_two.log; sleep 30'"
+"#,
+ );
+ repo.commit("initial");
+
+ let mut cmd = repo.wt_command();
+ cmd.args(["step", "intignored"]);
+ cmd.current_dir(repo.root_path());
+ cmd.stdout(Stdio::null());
+ cmd.stderr(Stdio::null());
+ cmd.process_group(0);
+ let mut child = cmd.spawn().expect("failed to spawn wt step intignored");
+
+ wait_for_file_content(&repo.root_path().join("ignored_one.log"));
+ wait_for_file_content(&repo.root_path().join("ignored_two.log"));
+
+ let wt_pgid = Pid::from_raw(child.id() as i32);
+ kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT)
+ .expect("failed to send SIGINT to wt's process group");
+
+ let status = child.wait().expect("failed to wait for wt");
+
+ use std::os::unix::process::ExitStatusExt;
+ assert!(
+ status.signal() == Some(2) || status.code() == Some(130),
+ "wt should report the originating SIGINT (signal 2 / code 130) even \
+ when escalation killed children with SIGTERM, got: {status:?}"
+ );
+}
+
/// A second SIGINT (user mashing Ctrl-C) must escalate to SIGKILL on every
/// child immediately — otherwise a child that traps SIGINT keeps the group
/// alive for up to N × 400ms of per-pgid escalation, with subsequent