Skip to content

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

fix(list): let merge-tree probes finish when the picker cancels background work (#4274)

Worktrunk Bot05d1315d02f7
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 1cc1292c1..b86fd4ba4 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -309,7 +309,18 @@ impl Repository {
// unresolvable args — callers pass pre-resolved commit SHAs, see
// `run_merge_tree`), anything else = error (corrupt repo, bad usage)
let args = ["merge-tree", "--write-tree", a, b];
- let output = self.run_command_output(&args)?;
+ // Not signalled on picker exit: a merge driver interrupted mid-run
+ // strands `.merge_file_*` temp files in the worktree (#4273).
+ let output = self
+ .with_object_store_env(
+ Cmd::new("git")
+ .args(args)
+ .current_dir(&self.discovery_path)
+ .context(self.logging_context())
+ .finish_once_started(),
+ )
+ .run()
+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
if output.status.code() == Some(1) {
return Ok(MergeTreeOutcome::Conflict);
@@ -1380,6 +1391,74 @@ mod merge_tree_cache_tests {
"the shared entry must be keyed (target, branch)"
);
}
+
+ /// A merge-tree probe mid-merge-driver must not be signalled when the
+ /// picker cancels background work: git removes the driver's
+ /// `.merge_file_*` temp files only on a normal return, so a SIGTERM strands
+ /// them in the worktree (#4273). The driver records its parent — the
+ /// running `git merge-tree` — so the test can check that PID isn't
+ /// registered for cancellation while the driver runs.
+ #[cfg(unix)]
+ #[test]
+ fn merge_tree_probe_is_not_signalled_on_cancel() {
+ let test = TestRepo::with_initial_commit();
+ let root = test.root_path().to_path_buf();
+ std::fs::write(root.join("f.txt"), "a\nb\nc\n").unwrap();
+ test.run_git(&["add", "f.txt"]);
+ test.run_git(&["commit", "-m", "base"]);
+ test.run_git(&["checkout", "-b", "feature"]);
+ std::fs::write(root.join("f.txt"), "a\nFEAT\nc\n").unwrap();
+ test.run_git(&["commit", "-am", "feature"]);
+ test.run_git(&["checkout", "main"]);
+ std::fs::write(root.join("f.txt"), "a\nMAIN\nc\n").unwrap();
+ test.run_git(&["commit", "-am", "main"]);
+ let main_sha = test.git_output(&["rev-parse", "main"]);
+ let feature_sha = test.git_output(&["rev-parse", "feature"]);
+
+ let dir = crate::testing::test_tempdir();
+ let marker = dir.path().join("driver-parent");
+ let release = dir.path().join("release");
+ let driver = format!(
+ "echo $PPID > '{}'; while [ ! -e '{}' ]; do sleep 0.05; done; exit 1",
+ marker.display(),
+ release.display()
+ );
+ test.run_git(&["config", "merge.slow.driver", &driver]);
+ let git_dir = test.git_output(&["rev-parse", "--absolute-git-dir"]);
+ std::fs::create_dir_all(std::path::Path::new(&git_dir).join("info")).unwrap();
+ std::fs::write(
+ std::path::Path::new(&git_dir).join("info/attributes"),
+ "* merge=slow\n",
+ )
+ .unwrap();
+
+ let repo = Repository::at(&root).unwrap();
+ std::thread::scope(|s| {
+ let probe = s.spawn(|| repo.merge_tree_outcome(&main_sha, &feature_sha));
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ let pid = loop {
+ if let Some(pid) = std::fs::read_to_string(&marker)
+ .ok()
+ .and_then(|s| s.trim().parse::<u32>().ok())
+ {
+ break pid;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "merge driver never ran"
+ );
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ };
+ let cancellable = crate::shell_exec::is_cancellable_pid(pid);
+ std::fs::write(&release, "").unwrap();
+ let outcome = probe.join().unwrap().unwrap();
+ assert!(
+ !cancellable,
+ "a running merge-tree must not be a cancellation target"
+ );
+ assert!(matches!(outcome, MergeTreeOutcome::Conflict));
+ });
+ }
}
#[cfg(test)]
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 61d054e7f..6999ed985 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -129,7 +129,8 @@ fn is_foreground_thread() -> bool {
/// foreground thread is the one that cancels, and is never itself inside a
/// tracked command while doing so, so the work the user is actually waiting
/// on is never a target; an [`uninterruptible`] thread finishes what it
-/// started.
+/// started. A command marked [`Cmd::finish_once_started`] doesn't register
+/// either, so it runs to completion once spawned.
static BACKGROUND_PIDS: Mutex<BTreeSet<u32>> = Mutex::new(BTreeSet::new());
/// Deregisters a background command's PID however the command finishes.
@@ -205,6 +206,12 @@ fn track_if_cancellable(pid: u32) -> Option<BackgroundPid> {
})
}
+/// Whether a cancellation would signal `pid` right now.
+#[cfg(all(test, unix))]
+pub(crate) fn is_cancellable_pid(pid: u32) -> bool {
+ BACKGROUND_PIDS.lock().unwrap().contains(&pid)
+}
+
/// Set once the foreground thread has cancelled background work, so commands
/// that haven't spawned yet never do.
///
@@ -225,7 +232,8 @@ fn cancelled_error() -> std::io::Error {
}
/// Abandon background work: nothing further spawns, and whatever is already
-/// running is signalled rather than left to finish as an orphan.
+/// running is signalled rather than left to finish as an orphan — except
+/// commands marked [`Cmd::finish_once_started`], which run to completion.
///
/// Callers see either as an ordinary command failure, which every background
/// caller already treats as "no result".
@@ -938,6 +946,7 @@ fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {
fn run_with_timeout_impl(
cmd: &mut Command,
timeout: std::time::Duration,
+ cancellable: bool,
) -> std::io::Result<std::process::Output> {
#[cfg(unix)]
{
@@ -950,7 +959,9 @@ fn run_with_timeout_impl(
.stdout(Stdio::piped())
.stderr(Stdio::piped()),
)?;
- let _tracked = track_if_cancellable(child.id());
+ let _tracked = cancellable
+ .then(|| track_if_cancellable(child.id()))
+ .flatten();
let mut child_stdout = child.take_stdout();
let mut child_stderr = child.take_stderr();
@@ -1115,6 +1126,9 @@ pub struct Cmd {
/// shell bodies may emit cd directives (the file holds a raw path, no shell
/// injection surface).
directive_cd_file: Option<std::path::PathBuf>,
+ /// If true, cancellation stops this command from spawning but never
+ /// signals it once running. Set via [`Cmd::finish_once_started`].
+ finish_once_started: bool,
}
struct ExternalCommandLog {
@@ -1280,6 +1294,7 @@ impl Cmd {
ignore_sigpipe: true,
external_label: None,
directive_cd_file: None,
+ finish_once_started: false,
}
}
@@ -1435,6 +1450,28 @@ impl Cmd {
self
}
+ /// Let this command run to completion once spawned, even if background
+ /// work is cancelled meanwhile ([`cancel_background_commands`]). A
+ /// cancelled command that hasn't spawned yet still never does.
+ ///
+ /// For commands whose interruption leaves debris SIGTERM doesn't clean:
+ /// `git merge-tree` writes its external merge driver's inputs as
+ /// `.merge_file_XXXXXX` files in its cwd and removes them only on a normal
+ /// return, so a signal mid-driver strands them in the user's worktree.
+ ///
+ /// Only affects `.run()`.
+ pub fn finish_once_started(mut self) -> Self {
+ self.finish_once_started = true;
+ self
+ }
+
+ /// [`track_if_cancellable`], unless [`Cmd::finish_once_started`] opted out.
+ fn track_if_cancellable(&self, pid: u32) -> Option<BackgroundPid> {
+ (!self.finish_once_started)
+ .then(|| track_if_cancellable(pid))
+ .flatten()
+ }
+
/// Set an environment variable.
///
/// Accepts the same types as [`Command::env`]: string literals, `String`,
@@ -1638,7 +1675,7 @@ impl Cmd {
match cmd.spawn() {
Ok(mut child) => {
- let _tracked = track_if_cancellable(child.id());
+ let _tracked = self.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
@@ -1656,7 +1693,7 @@ impl Cmd {
}
} else if let Some(timeout_duration) = self.timeout {
// Timeout handling uses the existing impl
- run_with_timeout_impl(&mut cmd, timeout_duration)
+ run_with_timeout_impl(&mut cmd, timeout_duration, !self.finish_once_started)
} else {
// Simple case: run and capture output. Spawned explicitly rather
// than via `cmd.output()` — which matches these stdio defaults —
@@ -1668,7 +1705,7 @@ impl Cmd {
.stderr(Stdio::piped());
match cmd.spawn() {
Ok(child) => {
- let _tracked = track_if_cancellable(child.id());
+ let _tracked = self.track_if_cancellable(child.id());
child.wait_with_output()
}
Err(e) => Err(e),