Skip to content

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

fix(prune): serialize integration checks against branch -D (Windows .git/config race) (#2808)

Maximilian Roos6fd2b700947f
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index b043358ac..44b6473b8 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -3,6 +3,7 @@
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
+use std::sync::{Arc, RwLock};
use std::time::Duration;
use anyhow::Context;
@@ -133,6 +134,7 @@ fn prune_summary(candidates: &[Candidate]) -> String {
/// Try to remove a candidate immediately. Returns Ok(true) if removed,
/// Ok(false) if skipped (preparation error), Err on execution error.
+#[allow(clippy::too_many_arguments)]
fn try_remove(
candidate: &Candidate,
repo: &Repository,
@@ -141,7 +143,24 @@ fn try_remove(
run_hooks: bool,
worktrees: &[WorktreeInfo],
snapshot: &RefSnapshot,
+ check_lock: &RwLock<()>,
) -> anyhow::Result<bool> {
+ // Exclude all in-flight integration readers for the duration of the
+ // removal: the write guard blocks until every outstanding read guard
+ // (i.e. every running `integration_reason` git process) has dropped, and
+ // blocks new ones until removal completes — so no `.git/config` reader is
+ // alive while `git branch -D` rewrites it. Held over the whole body
+ // (rather than just the deep `branch -D` call site) keeps the lock
+ // confined to this file; the extra reader-exclusion during the fast
+ // rename/prune is harmless. See the `check_lock` rationale at the
+ // par_iter spawn for the Windows mechanism and its fast-path scope.
+ //
+ // The guard protects `()` — there is no shared state to corrupt, so a
+ // poisoned lock is meaningless here. Recover the guard rather than
+ // `.expect()`-ing: a panic elsewhere should surface as itself, not as a
+ // cascade of secondary poison panics on every later removal/reader.
+ let _write = check_lock.write().unwrap_or_else(|e| e.into_inner());
+
let target = match candidate.kind {
CandidateKind::Current => RemoveTarget::Current,
CandidateKind::BranchOnly => RemoveTarget::Branch(
@@ -496,6 +515,32 @@ pub fn step_prune(
// messages, and removing candidates immediately. This overlaps integration
// checking with removal — output appears as soon as the first check
// completes instead of waiting for all checks to finish.
+ //
+ // `check_lock` serializes the parallel `integration_reason` readers
+ // against the removal writer. Each `integration_reason` call (which fans
+ // out git subprocesses that *read* `.git/config`) is held under a read
+ // guard; `try_remove` is held under the write guard. On Windows the
+ // config rewrite in `git branch -D` (lockfile+rename) briefly holds
+ // `.git/config` with delete access, and a concurrent reader's `fopen` —
+ // which does not pass `FILE_SHARE_DELETE` and is not retried — fails with
+ // "Permission denied". The RwLock keeps no integration reader in flight
+ // while a removal runs, without serializing the (parallel) checks
+ // themselves. POSIX is unaffected but takes the same path.
+ //
+ // Scope of the guarantee: this closes the race on the instant-removal
+ // fast path, where `git branch -D` runs *synchronously* inside
+ // `try_remove` (after the worktree is renamed into trash) and is thus
+ // under the write guard — that is the path the observed Windows failure
+ // took. On the cross-filesystem / `.gitmodules` / Windows-file-lock
+ // fallback, `execute_instant_removal_or_fallback` *must* defer branch
+ // deletion into the detached `git worktree remove && git branch -D`
+ // command (the worktree still references the branch until it is removed,
+ // so an in-process `branch -D` would fail) — that deferred write runs
+ // after the guard drops and is NOT covered here. The fallback is rare for
+ // prune targets (integrated worktrees the user is done with; the
+ // lock-prone current worktree is deferred last, after the check thread
+ // has drained), so the residual exposure is small but non-zero.
+ let check_lock = Arc::new(RwLock::new(()));
let (tx, rx) = chan::unbounded();
let integration_refs: Vec<String> = check_items
.iter()
@@ -510,15 +555,21 @@ pub fn step_prune(
let target = integration_target.clone();
// Share by Arc — main thread keeps `snapshot_arc` for `try_remove`; the
// rayon worker takes a refcount-bump clone. No deep snapshot copy.
- let snapshot_arc = std::sync::Arc::new(snapshot);
- let snapshot_for_thread = std::sync::Arc::clone(&snapshot_arc);
+ let snapshot_arc = Arc::new(snapshot);
+ let snapshot_for_thread = Arc::clone(&snapshot_arc);
+ let lock_for_thread = Arc::clone(&check_lock);
std::thread::spawn(move || {
integration_refs
.into_par_iter()
.enumerate()
.for_each(|(idx, ref_name)| {
- let result =
- repo_clone.integration_reason(&snapshot_for_thread, &ref_name, &target);
+ // Hold the read guard only across `integration_reason` (all
+ // its child git readers), then drop it before `send` so a
+ // waiting writer is not blocked by channel backpressure.
+ let result = {
+ let _read = lock_for_thread.read().unwrap_or_else(|e| e.into_inner());
+ repo_clone.integration_reason(&snapshot_for_thread, &ref_name, &target)
+ };
let _ = tx.send((idx, result));
});
});
@@ -592,6 +643,7 @@ pub fn step_prune(
run_hooks,
worktrees,
&snapshot_arc,
+ &check_lock,
)
.with_context(|| candidate.removal_context())?
{
@@ -647,6 +699,7 @@ pub fn step_prune(
run_hooks,
worktrees,
&snapshot_arc,
+ &check_lock,
)
.with_context(|| candidate.removal_context())?
{
@@ -668,6 +721,7 @@ pub fn step_prune(
run_hooks,
worktrees,
&snapshot_arc,
+ &check_lock,
)
.with_context(|| current.removal_context())?
{
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index ed5e92f3e..e2d002875 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1065,3 +1065,99 @@ fn test_prune_runs_branch_local_pre_remove_hook(mut repo: TestRepo) {
assert_eq!(std::fs::read_to_string(&marker).unwrap().trim(), "ran");
assert!(!wt_path.exists(), "the merged worktree should be removed");
}
+
+/// Windows residual-race canary for the `wt step prune` fallback path.
+///
+/// B-prime (the `check_lock` RwLock in `src/commands/step/prune.rs`)
+/// serializes the parallel `integration_reason` `.git/config` readers against
+/// the *synchronous* fast-path `git branch -D` writer. The cross-filesystem /
+/// `.gitmodules` / Windows-file-lock fallback, however, defers branch
+/// deletion into a detached `git worktree remove && git branch -D` that runs
+/// *outside* the write guard (see the `check_lock` rationale comment for why
+/// it cannot be guarded there — the worktree still references the branch). A
+/// `git branch -D` of a branch with a `[branch "<name>"]` section rewrites
+/// `.git/config` via lockfile+rename.
+///
+/// This forces that fallback for one non-current integrated worktree (by
+/// pre-blocking its staged path, like
+/// `test_remove_background_fallback_on_rename_failure`) while several other
+/// integrated worktrees keep the parallel integration-check fan-out running,
+/// so the deferred config-rewriting `git branch -D` overlaps live
+/// `.git/config` readers.
+///
+/// On POSIX this is a deterministic fallback-path smoke test: a concurrent
+/// `.git/config` read and rename never collide, so it always passes. On
+/// Windows the same overlap can hit the documented residual gap — `git`
+/// failing with `unable to access '.git/config': Permission denied`,
+/// panicking prune. It is left in the normal suite (not a dedicated stress
+/// lane) deliberately: a Windows flake here is empirical proof the fallback
+/// path needs closing rather than the structurally-estimated "small" gap
+/// (issue #2801).
+#[rstest]
+fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
+ repo.commit("initial");
+
+ // Several integrated worktrees → a real parallel integration-check
+ // fan-out. `add_worktree` puts each branch at `main` HEAD, so all are
+ // same-commit integrated and will be pruned. Each branch gets a
+ // `[branch "<name>"]` section so its `git branch -D` rewrites
+ // `.git/config` — the racing write. (No remote needed: `git branch -D`
+ // removes the section regardless of whether `origin` resolves, and the
+ // same-commit local check yields "integrated" before upstream is
+ // consulted.)
+ let names: Vec<String> = (0..6).map(|i| format!("merged-canary-{i}")).collect();
+ for name in &names {
+ repo.add_worktree(name);
+ repo.run_git(&["config", &format!("branch.{name}.remote"), "origin"]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{name}.merge"),
+ &format!("refs/heads/{name}"),
+ ]);
+ }
+
+ // Force the fallback for one *non-current* worktree by pre-creating a
+ // file at its computed staged path so `std::fs::rename(worktree → trash)`
+ // fails. Pick one in the middle so integration checks for later refs are
+ // still in flight when its deferred `git branch -D` fires.
+ let blocked = names[3].clone();
+ let blocked_wt_path = repo.worktree_path(&blocked).to_path_buf();
+ let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");
+ std::fs::create_dir_all(&trash_dir).unwrap();
+ let staged_path = trash_dir.join(format!(
+ "{}-{}",
+ blocked_wt_path.file_name().unwrap().to_string_lossy(),
+ crate::common::TEST_EPOCH
+ ));
+ std::fs::write(&staged_path, "blocking file to force fallback").unwrap();
+
+ // Parallel fan-out is the point — do NOT pin RAYON_NUM_THREADS=1.
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--yes", "--min-age=0s"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ output.status.success(),
+ "prune should succeed; the documented Windows fallback-path race \
+ would fail it here with a `.git/config` permission error \
+ (issue #2801).\nstderr:\n{stderr}"
+ );
+ assert!(
+ !stderr.contains("unable to access '.git/config'"),
+ "residual fallback-path `.git/config` race fired — the fallback's \
+ deferred `git branch -D` collided with a live integration-check \
+ reader (issue #2801).\nstderr:\n{stderr}"
+ );
+
+ // Removal-completion is intentionally NOT polled here. The race signal is
+ // the prune exit + stderr above (immediate, deterministic on POSIX).
+ // Detached background cleanup completing is load-sensitive and already
+ // covered by `test_prune_multiple` and
+ // `test_remove_background_fallback_on_rename_failure`; re-polling it under
+ // this test's deliberately heavy fan-out would only add load-induced
+ // flakiness with no canary value.
+ let _ = std::fs::remove_file(&staged_path);
+}