mirror of
https://github.com/max-sixty/worktrunk.git
synced 2026-11-22 00:52:51 +08:00
fix(signals): stop foreground loops when wt itself receives Ctrl-C (#4533)
## What regressed Since v0.80.0, Ctrl-C during `wt remove a b c` no longer stops the batch when the pre-remove hook catches SIGINT and exits normally, as pre-commit does (`trap '...' INT; exit 130`). Reproduced with a hook that traps INT, exits 130 and otherwise sleeps, plus a process-group SIGINT: v0.80.0 stops at `a` and keeps every worktree; current main removes `b` and `c`, branches included, and runs their hooks. `wt step prune` did the same with a hook that exits 0 after catching the key: every candidate was removed and wt exited 0. Two changes combined. #4400 moved foreground children into the caller's native job group and followed the shell's wait-and-cooperative-exit rule, so a child that handles the key keeps its own exit status. #4357 made a multi-target remove continue past a failing target. ## The rule Max chose the batch-runner convention (make, ninja, cargo) over the shell's: Ctrl-C that wt itself receives stops the current command. The terminal delivers SIGINT to the whole foreground job, so wt receives the key alongside the child. A shell waits and exits only if the child died of the signal, because the child might be an interactive program using Ctrl-C as input. A batch runner's steps aren't interactive, and the user pressing Ctrl-C means "stop the batch". For a destructive loop like remove or prune, that rule is also the one the data-safety principle asks for. The child still handles the key its own way, and wt never signals it for INT. Once the child exits, the command starts nothing more and exits interrupted (native SIGINT re-raise / 130), whatever status the child chose. Numeric exit codes such as 130 are still never read as cancellation; wt's own receipt is the evidence. ## What changes - `src/signal_forwarder.rs`: the existing per-operation cancellation (`CommandOperation`) gains a SIGINT flag beside its SIGTERM one. Foreground scopes register it, so the scope reports cancellation when its child exits, and later admissions in the same command are refused. The output drain's fresh flag, which existed to ignore keys the children had already handled, is gone. - Covered loops: hook pipelines (including Warn-strategy post-* hooks), multi-step aliases, `for-each`, multi-target `remove` and `prune`. - A command's final interactive child keeps the key as input and its own exit status: help and `config show` pagers, `--execute` programs and custom `wt-*` subcommands opt in through `Cmd::hand_off_terminal` (`TerminalInterrupt::ChildInput`). So does an alias's last serial step (`ForegroundStdin::HandOff`), since the alias is the whole command; `agent = "claude"` keeps claude's status after the user stops a turn with Ctrl-C. Otherwise pressing Ctrl-C in `less`, a REPL started by `-x` or such an alias, then quitting normally, would turn into exit 130. Earlier alias steps, concurrent groups and every hook step still cancel. - Unchanged: between children, idle SIGINT still kills wt natively. Detached background hooks, timeout-bounded captures in their own process group and the picker hold no foreground scope. A SIGINT sent only to wt is still not forwarded to the child; wt waits for it to finish, then stops. Windows is unchanged: wt installs no console Ctrl-C handler, so the default handler already ends wt and nothing more starts. - AGENTS.md "Signal Handling" and the `signal_forwarder` / `shell_exec` / `concurrent` module docs state the new rule. ## Verification - New unix integration tests, each pressing Ctrl-C (a group SIGINT) after wt has admitted a child that catches it: `remove` with a hook exiting 130 and with one exiting 0 keeps both targets; a post-start pipeline doesn't run its next step after a step exits 130; `for-each` visits one worktree when the child exits 0. All four fail on the old semantics. `test_alias_last_step_keeps_status_after_caught_ctrl_c` covers the alias handoff. The exit-0 remove case also fails if the scope stops reporting the latch and only refuses later admissions, since the current target would still be removed. - Existing tests that asserted the old rule now assert cancellation: the PTY `caught_keyboard_interrupt_cancels_following_step`, `test_alias_pid_signal_policy` (PID-only INT) and `test_alias_group_sigint_does_not_escalate`. The children still handle every key exactly once and wt never dies while they run. `test_alias_caught_sigint_preserves_successful_descendant_output` is deleted because its premise is the old rule. The pager and custom-subcommand cases in `custom_commands_and_help_pagers_preserve_native_signals` pass unchanged. - The alias signal harness moved to `tests/common` as `SignalJob` for reuse. - `cargo nextest run --all-features` (5377 passed), `cargo clippy --all-targets --all-features -- -D warnings`, pre-commit on the changed files. Manual repro of remove and prune before and after. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a4573593db
commit
0559edce3b
@@ -76,7 +76,7 @@ Worktrunk touches the network only when the user asks for it. The first Reposito
|
||||
|
||||
### Signal Handling: Ctrl-C Cancels the Current Command
|
||||
|
||||
Foreground commands share the caller's native job group. A child terminated by SIGINT or SIGTERM stops every foreground loop before its next step, including Warn hook pipelines and worktree loops. A caught Ctrl-C retains the child's normal exit semantics, including an ordinary exit code 130; do not infer cancellation from numeric exit codes. SIGTERM addressed to wt cancels its owned work even if the child catches it. Use err.interrupt_signal() from ErrorExt and propagate WorktrunkError::Interrupted through loops. Capture mode also classifies native SIGINT/SIGTERM exits; other child signals remain visible failures. See src/shell_exec.rs and src/signal_forwarder.rs for the contracts.
|
||||
Foreground commands share the caller's native job group. A child terminated by SIGINT or SIGTERM stops every foreground loop before its next step, including Warn hook pipelines and worktree loops. A terminal Ctrl-C that wt itself receives while a child runs cancels the command, as in make or cargo: the child handles the key its own way, then wt starts nothing more and exits interrupted, whatever status the child chose. wt's receipt is the evidence; never infer cancellation from numeric exit codes such as 130. A final interactive child (a pager, an --execute program, a custom subcommand, an alias's last serial step) owns the key as input instead, and its exit status stands. SIGTERM addressed to wt cancels its owned work even if the child catches it. Use err.interrupt_signal() from ErrorExt and propagate WorktrunkError::Interrupted through loops. Capture mode also classifies native SIGINT/SIGTERM exits; other child signals remain visible failures. See src/shell_exec.rs and src/signal_forwarder.rs for the contracts.
|
||||
|
||||
### Project Commands Run Only After Approval
|
||||
|
||||
|
||||
@@ -134,6 +134,10 @@ impl PipelineKind {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ForegroundStdin {
|
||||
Inherit,
|
||||
/// [`Self::Inherit`] for the command's final interactive child, which also
|
||||
/// owns a terminal Ctrl-C as input
|
||||
/// ([`worktrunk::shell_exec::TerminalInterrupt::ChildInput`]).
|
||||
HandOff,
|
||||
Closed,
|
||||
}
|
||||
|
||||
@@ -481,16 +485,28 @@ pub fn render_template_preview(
|
||||
///
|
||||
/// `Single` steps run one at a time; `Concurrent` steps run all their
|
||||
/// commands in parallel via the prefixed-line executor.
|
||||
///
|
||||
/// A terminal Ctrl-C wt receives during a step stops the pipeline. An alias is
|
||||
/// the whole command, so its last `Single` step with inherited input is the
|
||||
/// command's final interactive child instead ([`ForegroundStdin::HandOff`]).
|
||||
pub fn execute_pipeline_foreground(
|
||||
steps: &[ForegroundStep],
|
||||
repo: &Repository,
|
||||
wt_path: &Path,
|
||||
failure_strategy: FailureStrategy,
|
||||
) -> anyhow::Result<()> {
|
||||
for fg_step in steps {
|
||||
for (index, fg_step) in steps.iter().enumerate() {
|
||||
match &fg_step.step {
|
||||
PreparedStep::Single(cmd) => {
|
||||
run_one_command(cmd, fg_step, repo, wt_path, failure_strategy)?;
|
||||
let stdin = match fg_step.stdin {
|
||||
ForegroundStdin::Inherit
|
||||
if index + 1 == steps.len() && !fg_step.announce.is_hook() =>
|
||||
{
|
||||
ForegroundStdin::HandOff
|
||||
}
|
||||
stdin => stdin,
|
||||
};
|
||||
run_one_command(cmd, fg_step, stdin, repo, wt_path, failure_strategy)?;
|
||||
}
|
||||
PreparedStep::Concurrent(cmds) => {
|
||||
run_concurrent_group(cmds, fg_step, repo, wt_path, failure_strategy)?;
|
||||
@@ -582,6 +598,7 @@ fn run_concurrent_group(
|
||||
fn run_one_command(
|
||||
cmd: &PreparedCommand,
|
||||
fg_step: &ForegroundStep,
|
||||
stdin: ForegroundStdin,
|
||||
repo: &Repository,
|
||||
wt_path: &Path,
|
||||
failure_strategy: FailureStrategy,
|
||||
@@ -600,7 +617,7 @@ fn run_one_command(
|
||||
&command_str,
|
||||
log_label.as_deref(),
|
||||
directives.clone(),
|
||||
fg_step.stdin,
|
||||
stdin,
|
||||
fg_step.redirect_stdout_to_stderr,
|
||||
fg_step.announce.is_hook(),
|
||||
);
|
||||
|
||||
@@ -34,9 +34,13 @@ use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use worktrunk::git::WorktrunkError;
|
||||
#[cfg(unix)]
|
||||
use worktrunk::shell_exec::TerminalInterrupt;
|
||||
#[cfg(not(unix))]
|
||||
use worktrunk::shell_exec::wait_shared_child;
|
||||
use worktrunk::shell_exec::{DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR};
|
||||
#[cfg(unix)]
|
||||
use worktrunk::signal_forwarder::ForegroundSignals;
|
||||
use worktrunk::trace::CommandTrace;
|
||||
|
||||
use crate::cli::build_command;
|
||||
@@ -147,7 +151,7 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Res
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
let signals = worktrunk::signal_forwarder::ForegroundSignals::install()?;
|
||||
let signals = ForegroundSignals::install(TerminalInterrupt::ChildInput)?;
|
||||
let mut trace = CommandTrace::new(None, &path.display().to_string());
|
||||
#[cfg(unix)]
|
||||
let spawned = signals.spawn(&mut cmd);
|
||||
|
||||
+2
-1
@@ -1810,7 +1810,8 @@ impl std::fmt::Display for GitError {
|
||||
#[derive(Debug)]
|
||||
pub enum WorktrunkError {
|
||||
/// Physical child outcome, independently of observed operation cancellation.
|
||||
/// A caught interrupt may leave a normal child exit, including zero.
|
||||
/// A child that catches Ctrl-C may exit normally, even with zero, while
|
||||
/// `cancellation` records the interrupt wt itself received.
|
||||
ChildProcessExited {
|
||||
code: i32,
|
||||
physical_signal: Option<i32>,
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> Result<bool> {
|
||||
match Cmd::shell(pager_cmd)
|
||||
.stdin_bytes(help_text.as_bytes())
|
||||
.env("LESS", less_flags)
|
||||
.forward_signals()
|
||||
.hand_off_terminal()
|
||||
.stream()
|
||||
{
|
||||
Ok(()) => Ok(true),
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
//! Commands retain EOF semantics, including output from surviving descendants,
|
||||
//! regardless of ordinary exit status. Cancellation drains queued bytes and
|
||||
//! releases pipes even when an unowned descendant retains a write end.
|
||||
//! Once direct waits finish, the signal listener releases its command lease;
|
||||
//! a newly delivered interrupt cancels any remaining output wait.
|
||||
//! Ctrl-C reaches the native job through the kernel; a caught key preserves
|
||||
//! each child's normal status. PID-targeted SIGTERM reaches owned direct children.
|
||||
//! Once direct waits finish, the signal listener releases its command lease.
|
||||
//! Ctrl-C reaches the native job through the kernel. Each child handles it its
|
||||
//! own way; wt's receipt of the key cancels the group once they exit, including
|
||||
//! any remaining output wait. PID-targeted SIGTERM reaches owned direct children.
|
||||
//!
|
||||
//! Every admitted child runs to completion. Spawn failures occupy the same
|
||||
//! per-command outcome slots as child exits; the pipeline owns identity and
|
||||
@@ -43,6 +43,8 @@ use worktrunk::command_log::log_command;
|
||||
#[cfg(unix)]
|
||||
use worktrunk::git::ErrorExt;
|
||||
use worktrunk::git::WorktrunkError;
|
||||
#[cfg(unix)]
|
||||
use worktrunk::shell_exec::TerminalInterrupt;
|
||||
use worktrunk::shell_exec::{
|
||||
ShellConfig, apply_cd_directive_env, scrub_directive_env_vars, scrub_git_discovery_env_vars,
|
||||
wait_foreground_child,
|
||||
@@ -97,7 +99,7 @@ pub fn run_concurrent_commands(
|
||||
|
||||
// Install before spawn so startup signals remain queued.
|
||||
#[cfg(unix)]
|
||||
let signals = ForegroundSignals::install()?;
|
||||
let signals = ForegroundSignals::install(TerminalInterrupt::Cancels)?;
|
||||
|
||||
let mut children = Vec::with_capacity(cmds.len());
|
||||
let mut outcomes = (0..cmds.len()).map(|_| Ok(())).collect::<Vec<_>>();
|
||||
@@ -218,9 +220,9 @@ fn drain_children(
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
if outcomes.len() == child_count {
|
||||
// The execution lease ends here; the provider observes only
|
||||
// newly delivered INT while descendants retain output pipes.
|
||||
signal_thread.finish_children()?;
|
||||
// The execution lease ends here. A Ctrl-C received at any
|
||||
// point stops waiting for descendants that hold the pipes.
|
||||
signal_thread.finish_children();
|
||||
}
|
||||
if outcomes.len() == child_count && signal_thread.interrupt_signal().is_some() {
|
||||
for pipe in &mut pipes {
|
||||
@@ -447,7 +449,7 @@ fn run_serial_with_prefix(
|
||||
let mut outcomes = Vec::with_capacity(cmds.len());
|
||||
for (index, cmd) in cmds.iter().enumerate() {
|
||||
#[cfg(unix)]
|
||||
let signals = ForegroundSignals::install()?;
|
||||
let signals = ForegroundSignals::install(TerminalInterrupt::Cancels)?;
|
||||
match spawn_child(
|
||||
shell,
|
||||
index,
|
||||
|
||||
@@ -350,7 +350,7 @@ pub fn execute(argv: Vec<String>, dir: &Path) -> anyhow::Result<()> {
|
||||
let cmd = Cmd::new(program)
|
||||
.args(argv)
|
||||
.inherit_stdin()
|
||||
.forward_signals()
|
||||
.hand_off_terminal()
|
||||
.current_dir(dir)
|
||||
.scrub_git_discovery_env();
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -2271,9 +2271,7 @@ pub fn execute_shell_command(
|
||||
eprint!("{}", anstyle::Reset);
|
||||
stderr().flush().ok(); // Ignore flush errors - reset is best-effort, command execution should proceed
|
||||
|
||||
let mut cmd = Cmd::shell(command)
|
||||
.current_dir(working_dir)
|
||||
.forward_signals();
|
||||
let mut cmd = Cmd::shell(command).current_dir(working_dir);
|
||||
|
||||
// User hooks discover their repo from the cwd wt sets, not an inherited
|
||||
// GIT_DIR/GIT_WORK_TREE (issue #3373). Aliases keep the inherited context.
|
||||
@@ -2290,8 +2288,9 @@ pub fn execute_shell_command(
|
||||
}
|
||||
|
||||
cmd = match stdin {
|
||||
ForegroundStdin::Inherit => cmd.inherit_stdin(),
|
||||
ForegroundStdin::Closed => cmd.stdin(Stdio::null()),
|
||||
ForegroundStdin::Inherit => cmd.inherit_stdin().forward_signals(),
|
||||
ForegroundStdin::HandOff => cmd.inherit_stdin().hand_off_terminal(),
|
||||
ForegroundStdin::Closed => cmd.stdin(Stdio::null()).forward_signals(),
|
||||
};
|
||||
|
||||
if let Some(path) = directives.cd_file {
|
||||
|
||||
+35
-11
@@ -24,8 +24,10 @@
|
||||
//! The shell owns the foreground job and the kernel delivers Ctrl-C, Ctrl-Z
|
||||
//! and hangup to it. No terminal handoff or private foreground group is needed.
|
||||
//!
|
||||
//! [`Cmd::forward_signals`] observes direct exit while waiting, preserving a
|
||||
//! child's normal exit when it handles Ctrl-C.
|
||||
//! [`Cmd::forward_signals`] observes direct exit while waiting. A terminal
|
||||
//! Ctrl-C that wt itself receives meanwhile cancels the command once the child
|
||||
//! exits, whatever status the child chose; [`Cmd::hand_off_terminal`] leaves
|
||||
//! the key to a final interactive child instead (see [`TerminalInterrupt`]).
|
||||
//! SIGTERM addressed only to wt is forwarded
|
||||
//! to owned direct children and cancels the command. Child signal exits propagate
|
||||
//! through `WorktrunkError::ChildProcessExited` to stop foreground loops.
|
||||
@@ -267,6 +269,21 @@ fn track_if_cancellable(pid: u32) -> Option<BackgroundPid> {
|
||||
})
|
||||
}
|
||||
|
||||
/// What a terminal Ctrl-C that wt itself receives means while a foreground
|
||||
/// child runs. Either way the child handles the key its own way; wt never
|
||||
/// signals it for INT.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TerminalInterrupt {
|
||||
/// The child is one step of the command, such as a hook, an alias step or
|
||||
/// a `for-each` visit. Once it exits the command starts nothing more and
|
||||
/// exits interrupted, whatever status the child chose.
|
||||
Cancels,
|
||||
/// The command hands the terminal to its final, interactive child: a pager,
|
||||
/// an `--execute` program, a custom subcommand, an alias's last serial step.
|
||||
/// The key is that child's input, and its own exit status stands.
|
||||
ChildInput,
|
||||
}
|
||||
|
||||
/// Whether a cancellation would signal `pid` right now.
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn is_cancellable_pid(pid: u32) -> bool {
|
||||
@@ -1237,7 +1254,7 @@ pub struct Cmd {
|
||||
/// Stdin configuration for stream() (defaults to null; stdin_data takes precedence)
|
||||
stdin_cfg: Option<std::process::Stdio>,
|
||||
/// Observe terminal signals and forward PID-targeted cancellation during stream().
|
||||
forward_signals: bool,
|
||||
forward_signals: Option<TerminalInterrupt>,
|
||||
/// If true, treat a SIGPIPE exit as success. This is the default for pager
|
||||
/// producers, where the consumer closing early is expected. Direct user
|
||||
/// programs can opt out with [`Cmd::propagate_sigpipe`].
|
||||
@@ -1551,7 +1568,7 @@ impl Cmd {
|
||||
shell_wrap,
|
||||
stdout_cfg: None,
|
||||
stdin_cfg: None,
|
||||
forward_signals: false,
|
||||
forward_signals: None,
|
||||
ignore_sigpipe: true,
|
||||
external_label: None,
|
||||
directive_cd_file: None,
|
||||
@@ -1838,11 +1855,19 @@ impl Cmd {
|
||||
|
||||
/// Preserve terminal Ctrl-C delivery and forward SIGTERM to live children.
|
||||
///
|
||||
/// The child shares the caller's foreground group. A handled Ctrl-C keeps
|
||||
/// its normal status; cancellation and signal exits stop foreground loops.
|
||||
/// The child shares the caller's foreground group, so it receives the key
|
||||
/// alongside wt. wt's own receipt of SIGINT cancels the command once the
|
||||
/// child exits ([`TerminalInterrupt::Cancels`]); signal exits do too.
|
||||
/// Only affects `.stream()` on Unix. No-op on Windows.
|
||||
pub fn forward_signals(mut self) -> Self {
|
||||
self.forward_signals = true;
|
||||
self.forward_signals = Some(TerminalInterrupt::Cancels);
|
||||
self
|
||||
}
|
||||
|
||||
/// [`Cmd::forward_signals`] for the command's final, interactive child,
|
||||
/// which owns a terminal Ctrl-C as input ([`TerminalInterrupt::ChildInput`]).
|
||||
pub fn hand_off_terminal(mut self) -> Self {
|
||||
self.forward_signals = Some(TerminalInterrupt::ChildInput);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -2278,10 +2303,9 @@ impl Cmd {
|
||||
// Install the SIGINT/SIGTERM handler BEFORE spawn so a signal arriving
|
||||
// mid-spawn is queued, not default-killed.
|
||||
#[cfg(unix)]
|
||||
let signals = if self.forward_signals {
|
||||
Some(crate::signal_forwarder::ForegroundSignals::install()?)
|
||||
} else {
|
||||
None
|
||||
let signals = match self.forward_signals {
|
||||
Some(mode) => Some(crate::signal_forwarder::ForegroundSignals::install(mode)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
// Apply environment and spawn
|
||||
|
||||
+37
-33
@@ -1,7 +1,15 @@
|
||||
//! Foreground commands share the caller's Unix job group, independently of stdin.
|
||||
//!
|
||||
//! The terminal delivers Ctrl-C and Ctrl-Z to the whole job. A handled Ctrl-C
|
||||
//! therefore leaves each child's own exit status intact. SIGTERM addressed to
|
||||
//! The terminal delivers Ctrl-C and Ctrl-Z to the whole job, so wt and its
|
||||
//! child both receive the key. Like make or cargo, and unlike a shell's
|
||||
//! wait-and-cooperative-exit, wt treats its own receipt of SIGINT while a
|
||||
//! child runs as cancellation: the child handles the key its own way and is
|
||||
//! never signalled for it, but once it exits the command starts nothing more
|
||||
//! and exits interrupted, whatever status the child chose. Receipt is the
|
||||
//! evidence; a numeric exit status such as 130 never is. A child the command
|
||||
//! hands the terminal to ([`TerminalInterrupt::ChildInput`]: a pager, an
|
||||
//! `--execute` program, a custom subcommand, an alias's last serial step) owns
|
||||
//! the key as input instead, and its exit status stands. SIGTERM addressed to
|
||||
//! wt cancels its command and is forwarded to live direct children by PID;
|
||||
//! SharedChild serializes those deliveries with reaping. No caller group is killed.
|
||||
//! A group-wide TERM may also reach a child through this PID forwarding;
|
||||
@@ -13,12 +21,13 @@
|
||||
//! handlers retain native default behavior, including between pipeline steps.
|
||||
//! A confirmed INT/TERM child exit wakes all current foreground scopes, so
|
||||
//! parallel output waits also stop. Execution leases end with direct waits;
|
||||
//! output observers remain through EOF and distinguish newly delivered keys
|
||||
//! using a flag registered at that transition, rather than notification timing.
|
||||
//! output observers remain through EOF and keep reading the scope's latched
|
||||
//! SIGINT flag, so a key received at any point stops the remaining drain.
|
||||
//! A command-operation guard retains cancellation across gaps between foreground
|
||||
//! scopes without disabling idle native defaults. New scopes share that operation's
|
||||
//! latch; dropping the guard makes the next operation independent.
|
||||
|
||||
use crate::shell_exec::TerminalInterrupt;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
use std::thread;
|
||||
@@ -94,6 +103,9 @@ static ACTIVITY: OnceLock<Result<Mutex<Activity>, String>> = OnceLock::new();
|
||||
struct OperationCancellation {
|
||||
signal: Arc<AtomicI32>,
|
||||
terminated: Arc<AtomicBool>,
|
||||
/// Terminal SIGINT wt received while a [`TerminalInterrupt::Cancels`]
|
||||
/// scope ran. Those scopes register this flag; handoff scopes do not.
|
||||
interrupted: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl OperationCancellation {
|
||||
@@ -102,7 +114,7 @@ impl OperationCancellation {
|
||||
Some(SIGTERM)
|
||||
} else {
|
||||
match self.signal.load(Ordering::SeqCst) {
|
||||
0 => None,
|
||||
0 => self.interrupted.load(Ordering::SeqCst).then_some(SIGINT),
|
||||
signal => Some(signal),
|
||||
}
|
||||
}
|
||||
@@ -236,7 +248,11 @@ impl Drop for Registration {
|
||||
pub struct ForegroundSignals {
|
||||
signals: Signals,
|
||||
terminated: Arc<AtomicBool>,
|
||||
/// SIGINT received since install. A `Cancels` scope shares the operation's
|
||||
/// flag and keeps observing it while children run; a `ChildInput` scope
|
||||
/// consults its own flag only until spawn commits admission.
|
||||
interrupted: Arc<AtomicBool>,
|
||||
terminal_interrupt: TerminalInterrupt,
|
||||
scope: Arc<Interruption>,
|
||||
lease: Lease,
|
||||
registration: Registration,
|
||||
@@ -250,7 +266,7 @@ pub struct ForegroundOutcome {
|
||||
|
||||
impl ForegroundSignals {
|
||||
/// Install before spawning so startup signals remain queued.
|
||||
pub fn install() -> std::io::Result<Self> {
|
||||
pub fn install(terminal_interrupt: TerminalInterrupt) -> std::io::Result<Self> {
|
||||
let state = Lease::state()?;
|
||||
// Fallible setup precedes admission, so an unwinding setup leaves
|
||||
// existing leases intact. Recover as the other Activity owners do.
|
||||
@@ -269,7 +285,10 @@ impl ForegroundSignals {
|
||||
.as_ref()
|
||||
.map(|operation| operation.terminated.clone())
|
||||
.unwrap_or_default();
|
||||
let interrupted = Arc::new(AtomicBool::new(false));
|
||||
let interrupted = match (&operation, terminal_interrupt) {
|
||||
(Some(operation), TerminalInterrupt::Cancels) => operation.interrupted.clone(),
|
||||
_ => Arc::default(),
|
||||
};
|
||||
let mut registration = Registration(Vec::new());
|
||||
for &signal in watched {
|
||||
if signal == SIGTERM && operation.is_some() {
|
||||
@@ -301,6 +320,7 @@ impl ForegroundSignals {
|
||||
signals,
|
||||
terminated,
|
||||
interrupted,
|
||||
terminal_interrupt,
|
||||
scope,
|
||||
registration,
|
||||
lease: Lease(state),
|
||||
@@ -384,7 +404,8 @@ impl ForegroundSignals {
|
||||
let Self {
|
||||
mut signals,
|
||||
terminated,
|
||||
interrupted: _,
|
||||
interrupted,
|
||||
terminal_interrupt,
|
||||
scope,
|
||||
registration,
|
||||
lease,
|
||||
@@ -402,8 +423,8 @@ impl ForegroundSignals {
|
||||
let _ = child.send_signal(SIGCONT);
|
||||
}
|
||||
}
|
||||
// Wake output drains; a caught terminal INT still keeps the
|
||||
// child's normal exit status, including a successful exit.
|
||||
// Wake output drains. Terminal INT stays with the children:
|
||||
// the drain observes the latched flag once they have exited.
|
||||
wake();
|
||||
}
|
||||
});
|
||||
@@ -411,7 +432,7 @@ impl ForegroundSignals {
|
||||
handle,
|
||||
listener: Some(listener),
|
||||
terminated,
|
||||
output_interrupted: None,
|
||||
interrupted: (terminal_interrupt == TerminalInterrupt::Cancels).then_some(interrupted),
|
||||
scope,
|
||||
_registration: registration,
|
||||
_lease: Some(lease),
|
||||
@@ -423,7 +444,8 @@ pub struct ActiveForwarder {
|
||||
handle: Handle,
|
||||
listener: Option<thread::JoinHandle<()>>,
|
||||
terminated: Arc<AtomicBool>,
|
||||
output_interrupted: Option<Arc<AtomicBool>>,
|
||||
/// The scope's latched SIGINT, absent for a terminal handoff.
|
||||
interrupted: Option<Arc<AtomicBool>>,
|
||||
scope: Arc<Interruption>,
|
||||
_lease: Option<Lease>,
|
||||
_registration: Registration,
|
||||
@@ -439,26 +461,8 @@ impl ActiveForwarder {
|
||||
}
|
||||
|
||||
/// Release direct execution while continuing to observe output cancellation.
|
||||
/// Registering a fresh flag here excludes older, already handled Ctrl-C
|
||||
/// deliveries, even when their iterator notifications are still queued.
|
||||
pub fn finish_children(&mut self) -> std::io::Result<()> {
|
||||
if let Some(lease) = &self._lease {
|
||||
let watched = lease
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
.watched
|
||||
.contains(&SIGINT);
|
||||
if watched {
|
||||
let flag = Arc::new(AtomicBool::new(false));
|
||||
self._registration
|
||||
.0
|
||||
.push(signal_hook::flag::register(SIGINT, flag.clone())?);
|
||||
self.output_interrupted = Some(flag);
|
||||
}
|
||||
self._lease.take();
|
||||
}
|
||||
Ok(())
|
||||
pub fn finish_children(&mut self) {
|
||||
self._lease.take();
|
||||
}
|
||||
|
||||
pub fn interrupt_signal(&self) -> Option<i32> {
|
||||
@@ -467,7 +471,7 @@ impl ActiveForwarder {
|
||||
} else {
|
||||
self.scope.signal().or_else(|| {
|
||||
if self
|
||||
.output_interrupted
|
||||
.interrupted
|
||||
.as_ref()
|
||||
.is_some_and(|flag| flag.load(Ordering::SeqCst))
|
||||
{
|
||||
|
||||
@@ -52,6 +52,104 @@ pub fn wait_for_foreground_admission(repo: &TestRepo, children: &[i32]) {
|
||||
});
|
||||
}
|
||||
|
||||
/// wt running as a native job in a process group of its own, so a group signal
|
||||
/// reaches wt and its children as a terminal key would, but not the test runner.
|
||||
/// Signal fixtures synchronize through files and avoid background descendants.
|
||||
/// An owned, unreaped keeper reserves the native group for scoped cleanup.
|
||||
#[cfg(unix)]
|
||||
pub struct SignalJob {
|
||||
child: Option<std::process::Child>,
|
||||
keeper: std::process::Child,
|
||||
pub release: std::path::PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl SignalJob {
|
||||
pub fn spawn(repo: &TestRepo, args: &[&str], stderr: std::process::Stdio) -> Self {
|
||||
use std::os::unix::process::CommandExt;
|
||||
// This owned, unreaped child reserves the caller group's numeric ID
|
||||
// even after wt finishes or a group interrupt kills the keeper.
|
||||
let keeper = std::process::Command::new("sleep")
|
||||
.arg("300")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut job = Self {
|
||||
child: None,
|
||||
keeper,
|
||||
release: repo.root_path().join("release"),
|
||||
};
|
||||
let mut command = repo.wt_command();
|
||||
command.args(args);
|
||||
command
|
||||
.current_dir(repo.root_path())
|
||||
.env("RUST_LOG", crate::common::FOREGROUND_TRACE_FILTER)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(stderr)
|
||||
.process_group(job.group().as_raw());
|
||||
job.child = Some(command.spawn().unwrap());
|
||||
job
|
||||
}
|
||||
|
||||
pub fn pid(&self) -> nix::unistd::Pid {
|
||||
nix::unistd::Pid::from_raw(self.child.as_ref().unwrap().id() as i32)
|
||||
}
|
||||
|
||||
pub fn group(&self) -> nix::unistd::Pid {
|
||||
nix::unistd::Pid::from_raw(self.keeper.id() as i32)
|
||||
}
|
||||
|
||||
pub fn running(&mut self) -> bool {
|
||||
self.child.as_mut().unwrap().try_wait().unwrap().is_none()
|
||||
}
|
||||
|
||||
pub fn release(&self) {
|
||||
std::fs::write(&self.release, "release").unwrap();
|
||||
}
|
||||
|
||||
/// Press Ctrl-C once wt has admitted the child that wrote its PID to
|
||||
/// `pid_file`, so wt receives the key while that child runs, not during startup.
|
||||
/// Needs `-vv` among the spawn arguments for the admission trace.
|
||||
pub fn interrupt_admitted_child(&self, repo: &TestRepo, pid_file: &Path) {
|
||||
wait_for_file_content(pid_file);
|
||||
let pid: i32 = std::fs::read_to_string(pid_file)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap();
|
||||
wait_for_foreground_admission(repo, &[pid]);
|
||||
nix::sys::signal::killpg(self.group(), nix::sys::signal::Signal::SIGINT).unwrap();
|
||||
}
|
||||
|
||||
pub fn wait(&mut self) -> std::process::ExitStatus {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
loop {
|
||||
if let Some(status) = self.child.as_mut().unwrap().try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "wt did not finish");
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for SignalJob {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::write(&self.release, "release");
|
||||
// No wait for the keeper precedes this signal. Its reserved PID pins
|
||||
// the group's identity, independently of wt's cached wait status.
|
||||
let _ = nix::sys::signal::killpg(self.group(), nix::sys::signal::Signal::SIGKILL);
|
||||
if let Some(child) = &mut self.child {
|
||||
let _ = child.wait();
|
||||
}
|
||||
let _ = self.keeper.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Block SIGTTIN and SIGTTOU signals to prevent test processes from being
|
||||
/// stopped when PTY operations interact with terminal control in background
|
||||
/// process groups.
|
||||
|
||||
@@ -287,6 +287,35 @@ fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Ctrl-C stops the loop even when the child catches it and exits successfully:
|
||||
/// wt received the key itself, so no later worktree is visited.
|
||||
#[rstest]
|
||||
#[cfg(unix)]
|
||||
fn test_for_each_stops_on_caught_ctrl_c(repo: TestRepo) {
|
||||
let marker_dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = marker_dir.path().join("pid");
|
||||
let script = format!(
|
||||
"trap 'exit 0' INT; touch {dir}/\"$(basename \"$PWD\")\"; echo $$ > {pid}; while :; do sleep 0.1; done",
|
||||
dir = shell_escape::unix::escape(marker_dir.path().join("visited").to_string_lossy()),
|
||||
pid = shell_escape::unix::escape(pid_file.to_string_lossy()),
|
||||
);
|
||||
std::fs::create_dir(marker_dir.path().join("visited")).unwrap();
|
||||
let mut job = crate::common::SignalJob::spawn(
|
||||
&repo,
|
||||
&["-vv", "step", "for-each", "--", "sh", "-c", &script],
|
||||
std::process::Stdio::null(),
|
||||
);
|
||||
job.interrupt_admitted_child(&repo, &pid_file);
|
||||
assert_eq!(crate::common::shell_exit_code(&job.wait()), Some(130));
|
||||
let visited = std::fs::read_dir(marker_dir.path().join("visited"))
|
||||
.unwrap()
|
||||
.count();
|
||||
assert_eq!(
|
||||
visited, 1,
|
||||
"Ctrl-C must stop the loop after its first visit"
|
||||
);
|
||||
}
|
||||
|
||||
/// An interrupted `--format=json` run still owes its consumer the results it
|
||||
/// collected before the signal: the machine-readable answer is emitted on the
|
||||
/// abort path too, not just on the completing one.
|
||||
|
||||
@@ -559,12 +559,15 @@ for line in sys.stdin:
|
||||
);
|
||||
}
|
||||
|
||||
/// A real terminal Ctrl-C that the hook handles, once or twice, stops the
|
||||
/// pipeline: the worker exits successfully, then wt exits interrupted without
|
||||
/// running the next step.
|
||||
#[rstest]
|
||||
#[case::single_one(false, 1)]
|
||||
#[case::single_two(false, 2)]
|
||||
#[case::concurrent_one(true, 1)]
|
||||
#[case::concurrent_two(true, 2)]
|
||||
fn caught_keyboard_interrupt_preserves_success_and_following_step(
|
||||
fn caught_keyboard_interrupt_cancels_following_step(
|
||||
repo: TestRepo,
|
||||
#[case] concurrent: bool,
|
||||
#[case] keys: usize,
|
||||
@@ -607,7 +610,7 @@ while count < {keys}:
|
||||
.unwrap();
|
||||
let mut shell = Shell::start(&repo);
|
||||
shell.send(&format!(
|
||||
"RUST_LOG={} \"$WT_JOB_TEST_BINARY\" -vv hook post-start --yes --foreground; printf 'RESULT_%s\\n' \"$?\"\n",
|
||||
"RUST_LOG={} \"$WT_JOB_TEST_BINARY\" -vv hook post-start --yes --foreground\n",
|
||||
crate::common::FOREGROUND_TRACE_FILTER
|
||||
));
|
||||
let info = native_info(&repo, "worker-info");
|
||||
@@ -633,12 +636,17 @@ while count < {keys}:
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
shell.wait_for("RESULT_0");
|
||||
// The worker exits successfully after handling every key; wt's own
|
||||
// receipt of the key still stops the pipeline. Bash aborts a compound
|
||||
// command after wt's native SIGINT, so read the status from fresh input.
|
||||
shell.wait_for("job-test> ");
|
||||
shell.send("printf 'RESULT_%s\\n' \"$?\"\n");
|
||||
shell.wait_for("RESULT_130");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(repo.root_path().join("count")).unwrap(),
|
||||
keys.to_string()
|
||||
);
|
||||
assert!(repo.root_path().join("next").exists());
|
||||
assert!(!repo.root_path().join("next").exists());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
|
||||
@@ -1331,6 +1331,43 @@ fn test_remove_interrupt_stops_batch(
|
||||
);
|
||||
}
|
||||
|
||||
/// Ctrl-C stops the batch even when the hook catches it and exits with an
|
||||
/// ordinary status, whether that is pre-commit's 130 or success: wt received
|
||||
/// the key itself, so neither the current nor a later target is removed.
|
||||
#[cfg(unix)]
|
||||
#[rstest]
|
||||
#[case::exit_130(130)]
|
||||
#[case::exit_0(0)]
|
||||
fn test_remove_ctrl_c_caught_by_hook_stops_batch(mut repo: TestRepo, #[case] hook_exit: i32) {
|
||||
let pid_file = repo.root_path().join("hook-pid");
|
||||
let hook = format!(
|
||||
"trap 'exit {hook_exit}' INT; echo $$ > {}; while :; do sleep 0.1; done",
|
||||
shell_escape::unix::escape(pid_file.to_string_lossy())
|
||||
);
|
||||
repo.write_project_config(&format!("pre-remove = {hook:?}"));
|
||||
repo.commit("Add pre-remove hook that catches Ctrl-C");
|
||||
let interrupted = repo.add_worktree("interrupted");
|
||||
let later = repo.add_worktree("later");
|
||||
let mut job = crate::common::SignalJob::spawn(
|
||||
&repo,
|
||||
&[
|
||||
"-vv",
|
||||
"remove",
|
||||
"interrupted",
|
||||
"later",
|
||||
"--foreground",
|
||||
"--yes",
|
||||
],
|
||||
std::process::Stdio::null(),
|
||||
);
|
||||
job.interrupt_admitted_child(&repo, &pid_file);
|
||||
assert_eq!(crate::common::shell_exit_code(&job.wait()), Some(130));
|
||||
assert!(
|
||||
interrupted.exists() && later.exists(),
|
||||
"Ctrl-C must stop all removals"
|
||||
);
|
||||
}
|
||||
|
||||
/// Signals from execution-time Git commands cancel removal just like hook
|
||||
/// signals. The hook arms the shim only after validation has succeeded;
|
||||
/// everything except the selected Git boundary delegates to real Git.
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::common::{
|
||||
// Used only by the `#[cfg(unix)]` signal tests below; gate the import to match,
|
||||
// or it reads as unused on Windows under `-D warnings`.
|
||||
#[cfg(unix)]
|
||||
use crate::common::SLEEP_FOR_ABSENCE_CHECK;
|
||||
use crate::common::{SLEEP_FOR_ABSENCE_CHECK, SignalJob};
|
||||
use ansi_str::AnsiStr;
|
||||
use insta_cmd::assert_cmd_snapshot;
|
||||
use rstest::rstest;
|
||||
@@ -1163,100 +1163,6 @@ fail = "exit 1"
|
||||
);
|
||||
}
|
||||
|
||||
// Signal fixtures synchronize through files and avoid background descendants.
|
||||
// An owned, unreaped keeper reserves the native group for scoped cleanup.
|
||||
#[cfg(unix)]
|
||||
struct AliasSignalJob {
|
||||
child: Option<std::process::Child>,
|
||||
keeper: std::process::Child,
|
||||
release: std::path::PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl AliasSignalJob {
|
||||
fn spawn(repo: &TestRepo) -> Self {
|
||||
Self::spawn_with_stderr(repo, Stdio::null())
|
||||
}
|
||||
|
||||
fn spawn_with_stderr(repo: &TestRepo, stderr: Stdio) -> Self {
|
||||
Self::spawn_command(repo, &["step", "signal-test"], stderr)
|
||||
}
|
||||
|
||||
fn spawn_traced(repo: &TestRepo, stderr: Stdio) -> Self {
|
||||
Self::spawn_command(repo, &["-vv", "step", "signal-test"], stderr)
|
||||
}
|
||||
|
||||
fn spawn_command(repo: &TestRepo, args: &[&str], stderr: Stdio) -> Self {
|
||||
use std::os::unix::process::CommandExt;
|
||||
// This owned, unreaped child reserves the caller group's numeric ID
|
||||
// even after wt finishes or a group interrupt kills the keeper.
|
||||
let keeper = std::process::Command::new("sleep")
|
||||
.arg("300")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut job = Self {
|
||||
child: None,
|
||||
keeper,
|
||||
release: repo.root_path().join("release"),
|
||||
};
|
||||
let mut command = repo.wt_command();
|
||||
command.args(args);
|
||||
command
|
||||
.current_dir(repo.root_path())
|
||||
.env("RUST_LOG", crate::common::FOREGROUND_TRACE_FILTER)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(stderr)
|
||||
.process_group(job.group().as_raw());
|
||||
job.child = Some(command.spawn().unwrap());
|
||||
job
|
||||
}
|
||||
|
||||
fn pid(&self) -> nix::unistd::Pid {
|
||||
nix::unistd::Pid::from_raw(self.child.as_ref().unwrap().id() as i32)
|
||||
}
|
||||
|
||||
fn group(&self) -> nix::unistd::Pid {
|
||||
nix::unistd::Pid::from_raw(self.keeper.id() as i32)
|
||||
}
|
||||
|
||||
fn running(&mut self) -> bool {
|
||||
self.child.as_mut().unwrap().try_wait().unwrap().is_none()
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
std::fs::write(&self.release, "release").unwrap();
|
||||
}
|
||||
|
||||
fn wait(&mut self) -> std::process::ExitStatus {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
loop {
|
||||
if let Some(status) = self.child.as_mut().unwrap().try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "alias did not finish");
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for AliasSignalJob {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::write(&self.release, "release");
|
||||
// No wait for the keeper precedes this signal. Its reserved PID pins
|
||||
// the group's identity, independently of wt's cached wait status.
|
||||
let _ = nix::sys::signal::killpg(self.group(), nix::sys::signal::Signal::SIGKILL);
|
||||
if let Some(child) = &mut self.child {
|
||||
let _ = child.wait();
|
||||
}
|
||||
let _ = self.keeper.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signal_alias(repo: &TestRepo, concurrent: bool, caught_int: Option<bool>) -> Vec<&'static str> {
|
||||
let labels = if concurrent {
|
||||
@@ -1338,7 +1244,7 @@ os.kill(os.getpid(), signal.SIGKILL)
|
||||
)
|
||||
.unwrap();
|
||||
let stderr_path = repo.root_path().join("stderr");
|
||||
let mut job = AliasSignalJob::spawn_command(
|
||||
let mut job = SignalJob::spawn(
|
||||
&repo,
|
||||
&["hook", "post-start", "--yes", "--foreground"],
|
||||
Stdio::from(std::fs::File::create(&stderr_path).unwrap()),
|
||||
@@ -1365,7 +1271,8 @@ os.kill(os.getpid(), signal.SIGKILL)
|
||||
}
|
||||
|
||||
/// Native policy: TERM aimed at wt cancels owned work even when its
|
||||
/// child handles TERM successfully; PID-only INT is observed without delivery.
|
||||
/// child handles TERM successfully. PID-only INT is never delivered to the
|
||||
/// child, which runs to completion; wt's receipt still cancels the next step.
|
||||
#[rstest]
|
||||
#[case::single_term(false, true)]
|
||||
#[case::concurrent_term(true, true)]
|
||||
@@ -1377,7 +1284,7 @@ fn test_alias_pid_signal_policy(repo: TestRepo, #[case] concurrent: bool, #[case
|
||||
let labels = signal_alias(&repo, concurrent, Some(true));
|
||||
let stderr_path = repo.root_path().join("stderr");
|
||||
let stderr = std::fs::File::create(&stderr_path).unwrap();
|
||||
let mut job = AliasSignalJob::spawn_traced(&repo, stderr.into());
|
||||
let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], stderr.into());
|
||||
let children = ready_alias_children(&repo, &labels, job.group());
|
||||
// A child can announce readiness before wt returns from spawn. This test
|
||||
// sends its signal to an admitted command, not during startup cancellation.
|
||||
@@ -1413,13 +1320,14 @@ fn test_alias_pid_signal_policy(repo: TestRepo, #[case] concurrent: bool, #[case
|
||||
);
|
||||
}
|
||||
job.release();
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let status = job.wait();
|
||||
assert!(
|
||||
status.success(),
|
||||
"PID-only INT changed an admitted command's status: {status:?}\n{}",
|
||||
status.code() == Some(130) || status.signal() == Some(2),
|
||||
"PID-only INT must cancel after the child's success: {status:?}\n{}",
|
||||
std::fs::read_to_string(stderr_path).unwrap()
|
||||
);
|
||||
assert!(repo.root_path().join("next").exists());
|
||||
assert!(!repo.root_path().join("next").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1429,7 +1337,7 @@ fn test_alias_pid_signal_policy(repo: TestRepo, #[case] concurrent: bool, #[case
|
||||
#[cfg(unix)]
|
||||
fn test_alias_concurrent_receives_sigint(repo: TestRepo) {
|
||||
let labels = signal_alias(&repo, true, None);
|
||||
let mut job = AliasSignalJob::spawn(&repo);
|
||||
let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], Stdio::null());
|
||||
ready_alias_children(&repo, &labels, job.group());
|
||||
nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
@@ -1441,8 +1349,10 @@ fn test_alias_concurrent_receives_sigint(repo: TestRepo) {
|
||||
assert!(!repo.root_path().join("next").exists());
|
||||
}
|
||||
|
||||
/// Repeated group interrupts retain the child's disposition and status. One
|
||||
/// contrast per handler/key/cardinality covers both stream execution paths.
|
||||
/// Repeated group interrupts retain the child's disposition and never kill wt
|
||||
/// while the child runs, yet wt's receipt cancels the following step even after
|
||||
/// the child succeeds. One contrast per handler/key/cardinality covers both
|
||||
/// stream execution paths.
|
||||
#[rstest]
|
||||
#[case::single_caught_once(false, true, 1)]
|
||||
#[case::concurrent_caught_twice(true, true, 2)]
|
||||
@@ -1456,7 +1366,7 @@ fn test_alias_group_sigint_does_not_escalate(
|
||||
#[case] presses: usize,
|
||||
) {
|
||||
let labels = signal_alias(&repo, concurrent, Some(caught));
|
||||
let mut job = AliasSignalJob::spawn_traced(&repo, Stdio::null());
|
||||
let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], Stdio::null());
|
||||
let children = ready_alias_children(&repo, &labels, job.group());
|
||||
crate::common::wait_for_foreground_admission(&repo, &children);
|
||||
for press in 1..=presses {
|
||||
@@ -1484,11 +1394,13 @@ fn test_alias_group_sigint_does_not_escalate(
|
||||
ready_alias_children(&repo, &labels, job.group());
|
||||
}
|
||||
job.release();
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let status = job.wait();
|
||||
assert!(
|
||||
job.wait().success(),
|
||||
"caught/ignored interrupts must preserve child success"
|
||||
status.code() == Some(130) || status.signal() == Some(2),
|
||||
"caught/ignored interrupts must still cancel the alias: {status:?}"
|
||||
);
|
||||
assert!(repo.root_path().join("next").exists());
|
||||
assert!(!repo.root_path().join("next").exists());
|
||||
if caught {
|
||||
for label in &labels {
|
||||
assert_eq!(
|
||||
@@ -1502,6 +1414,20 @@ fn test_alias_group_sigint_does_not_escalate(
|
||||
}
|
||||
}
|
||||
|
||||
/// An alias is the whole command, so its last serial step owns Ctrl-C as input,
|
||||
/// like `--execute`: a child that handles the key and exits successfully keeps
|
||||
/// that status. Earlier steps cancel instead (`test_alias_group_sigint_does_not_escalate`).
|
||||
#[rstest]
|
||||
#[cfg(unix)]
|
||||
fn test_alias_last_step_keeps_status_after_caught_ctrl_c(repo: TestRepo) {
|
||||
repo.write_test_config(
|
||||
"[aliases]\nsignal-test = \"trap 'exit 0' INT; echo $$ > pid; while :; do sleep 0.1; done\"\n",
|
||||
);
|
||||
let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], Stdio::null());
|
||||
job.interrupt_admitted_child(&repo, &repo.root_path().join("pid"));
|
||||
assert!(job.wait().success());
|
||||
}
|
||||
|
||||
/// Non-UTF-8 bytes and CRLF line endings in child output must not stall the
|
||||
/// executor. Earlier code using `BufRead::lines()` returned `InvalidData` on
|
||||
/// the first invalid byte and terminated the iterator, leaving the child's
|
||||
@@ -1621,7 +1547,7 @@ good = "(sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"
|
||||
);
|
||||
let output_path = repo.root_path().join("output");
|
||||
let stderr = std::fs::File::create(&output_path).unwrap();
|
||||
let mut job = AliasSignalJob::spawn_with_stderr(&repo, stderr.into());
|
||||
let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], stderr.into());
|
||||
assert_eq!(job.wait().code(), Some(17));
|
||||
let output = std::fs::read_to_string(output_path).unwrap();
|
||||
assert!(
|
||||
@@ -1634,43 +1560,6 @@ good = "(sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"
|
||||
);
|
||||
}
|
||||
|
||||
/// Ctrl-C handled successfully by a direct child must not truncate its later
|
||||
/// descendant output or change the child's successful result.
|
||||
#[rstest]
|
||||
#[cfg(unix)]
|
||||
fn test_alias_caught_sigint_preserves_successful_descendant_output(repo: TestRepo) {
|
||||
// `two` ignores SIGINT: the group interrupt can land after it writes its
|
||||
// marker but before it exits, and a native SIGINT death there would
|
||||
// legitimately cancel the alias.
|
||||
repo.write_test_config(
|
||||
r#"[aliases.signal-test]
|
||||
one = "trap 'printf handled > caught' INT; echo $$ > worker-pid; printf ready > first-ready; while test ! -f caught; do :; done; (sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"
|
||||
two = "trap '' INT; echo $$ > second-pid; printf ready > second-ready"
|
||||
"#,
|
||||
);
|
||||
let output_path = repo.root_path().join("output");
|
||||
let stderr = std::fs::File::create(&output_path).unwrap();
|
||||
let mut job = AliasSignalJob::spawn_traced(&repo, stderr.into());
|
||||
for marker in ["first-ready", "second-ready"] {
|
||||
crate::common::wait_for_file_content(&repo.root_path().join(marker));
|
||||
}
|
||||
let worker = std::fs::read_to_string(repo.root_path().join("worker-pid")).unwrap();
|
||||
let worker = nix::unistd::Pid::from_raw(worker.trim().parse().unwrap());
|
||||
assert_eq!(nix::unistd::getpgid(Some(worker)).unwrap(), job.group());
|
||||
let second = std::fs::read_to_string(repo.root_path().join("second-pid")).unwrap();
|
||||
crate::common::wait_for_foreground_admission(
|
||||
&repo,
|
||||
&[worker.as_raw(), second.trim().parse().unwrap()],
|
||||
);
|
||||
nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();
|
||||
assert!(job.wait().success());
|
||||
let output = std::fs::read_to_string(output_path).unwrap();
|
||||
assert!(
|
||||
output.contains("EARLY_LATE_TAIL"),
|
||||
"caught key truncated output: {output}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Cancellation must finish even when an unowned descendant continuously
|
||||
/// refills an output pipe, retaining buffered bytes and the final diagnostic.
|
||||
#[rstest]
|
||||
@@ -1704,7 +1593,7 @@ good = "true"
|
||||
);
|
||||
let output_path = repo.root_path().join("output");
|
||||
let stderr = std::fs::File::create(&output_path).unwrap();
|
||||
let mut job = AliasSignalJob::spawn_with_stderr(&repo, stderr.into());
|
||||
let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], stderr.into());
|
||||
crate::common::wait_for_file_content(&repo.root_path().join("descendant-ready"));
|
||||
nix::sys::signal::kill(job.pid(), nix::sys::signal::Signal::SIGTERM).unwrap();
|
||||
let release = job.release.clone();
|
||||
|
||||
@@ -607,6 +607,32 @@ fn test_pre_merge_pipeline_aborts_on_signal_exit(repo: TestRepo) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Ctrl-C stops a Warn pipeline even when the step catches it and exits with an
|
||||
/// ordinary status: wt received the key itself, so the next step never starts.
|
||||
#[rstest]
|
||||
#[cfg(unix)]
|
||||
fn test_post_start_pipeline_stops_on_caught_ctrl_c(repo: TestRepo) {
|
||||
repo.write_project_config(
|
||||
r#"post-start = [
|
||||
"trap 'exit 130' INT; echo $$ > hook-pid; while :; do sleep 0.1; done",
|
||||
"echo after > after.log",
|
||||
]
|
||||
"#,
|
||||
);
|
||||
repo.commit("Add post-start pipeline");
|
||||
let mut job = crate::common::SignalJob::spawn(
|
||||
&repo,
|
||||
&["-vv", "hook", "post-start", "--yes", "--foreground"],
|
||||
std::process::Stdio::null(),
|
||||
);
|
||||
job.interrupt_admitted_child(&repo, &repo.root_path().join("hook-pid"));
|
||||
assert_eq!(crate::common::shell_exit_code(&job.wait()), Some(130));
|
||||
assert!(
|
||||
!repo.root_path().join("after.log").exists(),
|
||||
"the step after Ctrl-C must not run"
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// User Post-Merge Hook Tests
|
||||
// ============================================================================
|
||||
|
||||
Reference in New Issue
Block a user