Skip to content

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

fix: background removal blocks for 1s due to shell parsing bug (#1858)

Maximilian Roosbd87f2a14682
diff --git a/Cargo.toml b/Cargo.toml
index f1e80ba23..b31986ffb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -166,6 +166,10 @@ harness = false
name = "time_to_first_output"
harness = false
+[[bench]]
+name = "remove"
+harness = false
+
[lints.rust]
unsafe_code = "forbid"
diff --git a/benches/remove.rs b/benches/remove.rs
new file mode 100644
index 000000000..b5e47b290
--- /dev/null
+++ b/benches/remove.rs
@@ -0,0 +1,218 @@
+// Benchmarks for `wt remove` end-to-end performance
+//
+// Measures the full remove command including output rendering and hook spawning,
+// to complement `time_to_first_output` which exits before output.
+//
+// Benchmark variants:
+// - remove_e2e/no_hooks — remove with --no-verify (no hook loading)
+// - remove_e2e/with_hooks — remove with hooks configured (user + project)
+// - remove_e2e/first_output — baseline: exits before output (same as time_to_first_output)
+//
+// Run examples:
+// cargo bench --bench remove # All variants
+// cargo bench --bench remove -- no_hooks # Just no-hooks variant
+
+use criterion::{Criterion, criterion_group, criterion_main};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use wt_perf::{RepoConfig, run_git, setup_fake_remote};
+
+fn release_binary() -> &'static Path {
+ Path::new(env!("CARGO_BIN_EXE_wt"))
+}
+
+/// Isolate a command from host environment (mirrors test configure_cli_command).
+fn isolate_cmd(cmd: &mut Command, user_config_path: &Path) {
+ // Remove host GIT_* and WORKTRUNK_* vars
+ for (key, _) in std::env::vars() {
+ if key.starts_with("GIT_") || key.starts_with("WORKTRUNK_") {
+ cmd.env_remove(&key);
+ }
+ }
+ cmd.env_remove("NO_COLOR");
+ cmd.env("WORKTRUNK_CONFIG_PATH", user_config_path);
+ cmd.env(
+ "WORKTRUNK_SYSTEM_CONFIG_PATH",
+ "/nonexistent/bench/system-config.toml",
+ );
+ cmd.env(
+ "WORKTRUNK_APPROVALS_PATH",
+ "/nonexistent/bench/approvals.toml",
+ );
+ cmd.env_remove("SHELL");
+}
+
+/// Create a benchmark repo at a specific path with optional hooks.
+fn create_bench_repo(base_path: &Path, with_hooks: bool) -> PathBuf {
+ let config = RepoConfig::typical(2); // main + 1 feature worktree
+ wt_perf::create_repo_at(&config, base_path);
+ setup_fake_remote(base_path);
+
+ if with_hooks {
+ // Project config with post-remove hook
+ let config_dir = base_path.join(".config");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(
+ config_dir.join("wt.toml"),
+ "[post-remove]\ndocs = \"echo post-remove-done\"\n",
+ )
+ .unwrap();
+ run_git(base_path, &["add", "."]);
+ run_git(base_path, &["commit", "-m", "Add project config"]);
+ }
+
+ base_path.to_path_buf()
+}
+
+/// Recreate the feature worktree after it was removed.
+fn recreate_worktree(repo_path: &Path) {
+ let wt_path = repo_path.parent().unwrap().join(format!(
+ "{}.feature-wt-1",
+ repo_path.file_name().unwrap().to_str().unwrap()
+ ));
+
+ // Wait briefly for background removal to finish (sleep 1 + rm -rf in detached process).
+ // Without this, the background rmdir/rm-rf races with worktree recreation.
+ std::thread::sleep(std::time::Duration::from_millis(1200));
+
+ // Clean up any leftover directory (placeholder or staged trash)
+ let _ = std::fs::remove_dir_all(&wt_path);
+
+ // Clean up trash directory from staged removals
+ let trash_dir = repo_path.join(".git/wt/trash");
+ if trash_dir.exists() {
+ let _ = std::fs::remove_dir_all(&trash_dir);
+ }
+
+ // Prune stale worktree metadata
+ let _ = run_git_ok(repo_path, &["worktree", "prune"]);
+
+ // Delete branch if it exists (may or may not have been deleted by removal)
+ let _ = run_git_ok(repo_path, &["branch", "-D", "feature-wt-1"]);
+
+ // Recreate branch + worktree
+ run_git(
+ repo_path,
+ &[
+ "worktree",
+ "add",
+ "-b",
+ "feature-wt-1",
+ wt_path.to_str().unwrap(),
+ "HEAD",
+ ],
+ );
+}
+
+/// Run git, returning true if successful.
+fn run_git_ok(path: &Path, args: &[&str]) -> bool {
+ use worktrunk::shell_exec::Cmd;
+ Cmd::new("git")
+ .args(args.iter().copied())
+ .current_dir(path)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .run()
+ .is_ok_and(|o| o.status.success())
+}
+
+fn bench_remove_e2e(c: &mut Criterion) {
+ let mut group = c.benchmark_group("remove_e2e");
+ let binary = release_binary();
+
+ // Persistent temp dirs (kept alive for the benchmark group)
+ let temp_no_hooks = tempfile::tempdir().unwrap();
+ let temp_with_hooks = tempfile::tempdir().unwrap();
+
+ let repo_no_hooks = create_bench_repo(&temp_no_hooks.path().join("repo"), false);
+ let repo_with_hooks = create_bench_repo(&temp_with_hooks.path().join("repo"), true);
+
+ // User config with post-switch hook (written beside repo)
+ let user_config_no_hooks = temp_no_hooks.path().join("config.toml");
+ std::fs::write(&user_config_no_hooks, "").unwrap();
+
+ let user_config_with_hooks = temp_with_hooks.path().join("config.toml");
+ std::fs::write(
+ &user_config_with_hooks,
+ "[hooks.post-switch]\nzellij-tab = \"echo post-switch-done\"\n",
+ )
+ .unwrap();
+
+ let wt_name = |repo: &Path| -> PathBuf {
+ repo.parent().unwrap().join(format!(
+ "{}.feature-wt-1",
+ repo.file_name().unwrap().to_str().unwrap()
+ ))
+ };
+
+ // Baseline: first_output (exits before output rendering)
+ group.bench_function("first_output", |b| {
+ b.iter(|| {
+ let mut cmd = Command::new(binary);
+ cmd.args(["remove", "--yes", "--no-verify", "--force", "feature-wt-1"]);
+ cmd.current_dir(&repo_no_hooks);
+ isolate_cmd(&mut cmd, &user_config_no_hooks);
+ cmd.env("WORKTRUNK_FIRST_OUTPUT", "1");
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "first_output failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ });
+ });
+
+ // No hooks: --no-verify (skip hook loading), run from feature worktree
+ group.bench_function("no_hooks", |b| {
+ b.iter_batched(
+ || recreate_worktree(&repo_no_hooks),
+ |()| {
+ let wt_path = wt_name(&repo_no_hooks);
+ let mut cmd = Command::new(binary);
+ cmd.args(["remove", "--yes", "--no-verify", "--force"]);
+ cmd.current_dir(&wt_path);
+ isolate_cmd(&mut cmd, &user_config_no_hooks);
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "no_hooks failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ },
+ criterion::BatchSize::PerIteration,
+ );
+ });
+
+ // With hooks: user post-switch + project post-remove
+ group.bench_function("with_hooks", |b| {
+ b.iter_batched(
+ || recreate_worktree(&repo_with_hooks),
+ |()| {
+ let wt_path = wt_name(&repo_with_hooks);
+ let mut cmd = Command::new(binary);
+ cmd.args(["remove", "--yes", "--force"]);
+ cmd.current_dir(&wt_path);
+ isolate_cmd(&mut cmd, &user_config_with_hooks);
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "with_hooks failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ },
+ criterion::BatchSize::PerIteration,
+ );
+ });
+
+ group.finish();
+}
+
+criterion_group! {
+ name = benches;
+ config = Criterion::default()
+ .sample_size(20)
+ .measurement_time(std::time::Duration::from_secs(20))
+ .warm_up_time(std::time::Duration::from_secs(3));
+ targets = bench_remove_e2e
+}
+criterion_main!(benches);
diff --git a/src/commands/process.rs b/src/commands/process.rs
index fd4106cc6..3e7b36a06 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -272,7 +272,15 @@ fn spawn_detached_unix(
None => command.to_string(),
};
- let shell_cmd = format!("{} &", full_command);
+ // Wrap in braces so `&` backgrounds the entire compound command.
+ // Without braces, `cmd1 && cmd2; cmd3 &` parses as two statements:
+ // `cmd1 && cmd2` (foreground) then `cmd3 &` (background) — the semicolon
+ // has lower precedence than `&`, so only the last segment is backgrounded.
+ let shell_cmd = format!(
+ "{{ {}{} }} &",
+ full_command,
+ posix_command_separator(&full_command)
+ );
// Detachment via process_group(0): puts the spawned shell in its own process group.
// When the controlling PTY closes, SIGHUP is sent to the foreground process group.
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index a1b88a704..7a49095a1 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -3114,6 +3114,25 @@ fn exponential_sleep(attempt: u32) {
ExponentialBackoff::default().sleep(attempt);
}
+/// Assert that a worktree's contents have been removed.
+///
+/// After background removal, the path may briefly exist as an empty placeholder
+/// directory (for shell PWD validity). This asserts the contents are gone —
+/// either the path doesn't exist, or it's an empty directory.
+pub fn assert_worktree_removed(path: &Path) {
+ // Use read_dir as the single check to avoid a TOCTOU race where the
+ // background process removes the placeholder between exists() and read_dir().
+ let is_empty_or_gone = match path.read_dir() {
+ Ok(mut entries) => entries.next().is_none(), // empty placeholder
+ Err(_) => true, // already gone (NotFound or other)
+ };
+ assert!(
+ is_empty_or_gone,
+ "Worktree contents should be removed (empty placeholder OK): {}",
+ path.display()
+ );
+}
+
/// Wait for a file to exist, polling with exponential backoff.
/// Use this instead of fixed sleeps for background commands to avoid flaky tests.
pub fn wait_for_file(path: &Path) {
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 6142835b0..30d379496 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2171,16 +2171,9 @@ fn test_remove_background_path_gone_immediately(mut repo: TestRepo) {
String::from_utf8_lossy(&output.stderr)
);
- // The original worktree path should be gone IMMEDIATELY (before background rm completes)
- // This is the key behavior of the move-then-delete optimization
- assert!(
- !worktree_path.exists(),
- "Worktree path should be gone immediately after wt remove returns"
- );
-
- // Note: The staging directory in .git/wt/trash/ might already be deleted by the
- // background process, or it might still exist. Both are valid outcomes.
- // The key assertion above is that the original path is gone immediately.
+ // The worktree contents should be gone IMMEDIATELY (moved to .git/wt/trash/).
+ // An empty placeholder directory may remain briefly (for shell PWD validity).
+ crate::common::assert_worktree_removed(&worktree_path);
}
/// Background removal should prune git worktree metadata synchronously.
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 187dea65c..946e74ac7 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -73,7 +73,7 @@ fn test_prune_removes_merged(mut repo: TestRepo) {
.parent()
.unwrap()
.join("repo.merged-branch");
- assert!(!worktree_path.exists(), "Merged worktree should be removed");
+ crate::common::assert_worktree_removed(&worktree_path);
}
/// Prune skips worktrees with unique commits (not merged)
@@ -96,7 +96,7 @@ fn test_prune_skips_unmerged(mut repo: TestRepo) {
// Merged worktree removed
let merged_path = repo.root_path().parent().unwrap().join("repo.merged-one");
- assert!(!merged_path.exists(), "Merged worktree should be removed");
+ crate::common::assert_worktree_removed(&merged_path);
// Unmerged worktree still exists
let unmerged_path = repo.root_path().parent().unwrap().join("repo.unmerged");
@@ -146,9 +146,9 @@ fn test_prune_multiple(mut repo: TestRepo) {
// All merged worktrees removed
let parent = repo.root_path().parent().unwrap();
- assert!(!parent.join("repo.merged-a").exists());
- assert!(!parent.join("repo.merged-b").exists());
- assert!(!parent.join("repo.merged-c").exists());
+ crate::common::assert_worktree_removed(&parent.join("repo.merged-a"));
+ crate::common::assert_worktree_removed(&parent.join("repo.merged-b"));
+ crate::common::assert_worktree_removed(&parent.join("repo.merged-c"));
}
/// Prune skips unmerged detached HEAD worktrees
@@ -194,10 +194,7 @@ fn test_prune_removes_integrated_detached(mut repo: TestRepo) {
// Worktree was removed
let parent = repo.root_path().parent().unwrap();
- assert!(
- !parent.join("repo.detached-integrated").exists(),
- "Integrated detached worktree should be removed"
- );
+ crate::common::assert_worktree_removed(&parent.join("repo.detached-integrated"));
}
/// Prune removes multiple integrated detached HEAD worktrees (exercises plural "worktrees")
@@ -219,8 +216,8 @@ fn test_prune_removes_multiple_detached(mut repo: TestRepo) {
));
let parent = repo.root_path().parent().unwrap();
- assert!(!parent.join("repo.detached-a").exists());
- assert!(!parent.join("repo.detached-b").exists());
+ crate::common::assert_worktree_removed(&parent.join("repo.detached-a"));
+ crate::common::assert_worktree_removed(&parent.join("repo.detached-b"));
}
/// Prune skips locked worktrees
@@ -244,7 +241,7 @@ fn test_prune_skips_locked(mut repo: TestRepo) {
// Merged removed, locked remains
let parent = repo.root_path().parent().unwrap();
- assert!(!parent.join("repo.merged-branch").exists());
+ crate::common::assert_worktree_removed(&parent.join("repo.merged-branch"));
assert!(
parent.join("repo.locked-branch").exists(),
"Locked worktree should be skipped"
@@ -312,10 +309,7 @@ fn test_prune_mixed_worktree_and_orphan_branch(mut repo: TestRepo) {
));
let parent = repo.root_path().parent().unwrap();
- assert!(
- !parent.join("repo.merged-mixed").exists(),
- "Merged worktree should be removed"
- );
+ crate::common::assert_worktree_removed(&parent.join("repo.merged-mixed"));
}
/// Prune from a merged worktree removes it last (CandidateKind::Current).
@@ -338,10 +332,7 @@ fn test_prune_current_worktree(mut repo: TestRepo) {
));
// Current worktree was removed
- assert!(
- !wt_path.exists(),
- "Current merged worktree should be removed"
- );
+ crate::common::assert_worktree_removed(&wt_path);
}
/// Prune handles stale/prunable worktrees (directory deleted but git metadata remains)
@@ -403,10 +394,7 @@ fn test_prune_skips_dirty(mut repo: TestRepo) {
// Clean worktree removed
let clean_path = repo.root_path().parent().unwrap().join("repo.clean-merged");
- assert!(
- !clean_path.exists(),
- "Clean merged worktree should be removed"
- );
+ crate::common::assert_worktree_removed(&clean_path);
}
/// Dry-run with mixed worktrees + orphan branches shows both counts.
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 089ac22fb..7f893994c 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1230,9 +1230,9 @@ fn test_standalone_hook_post_create(repo: TestRepo) {
"wt hook post-create should succeed"
);
- // Hook should have run
+ // Hook runs in background — wait for it to write the marker file
let marker = repo.root_path().join("hook_ran.txt");
- assert!(marker.exists(), "post-create hook should have run");
+ crate::common::wait_for_file_content(&marker);
let content = fs::read_to_string(&marker).unwrap();
assert!(content.contains("STANDALONE_POST_CREATE"));
}
@@ -1341,9 +1341,9 @@ fn test_standalone_hook_post_merge(repo: TestRepo) {
let output = cmd.output().unwrap();
assert!(output.status.success(), "wt hook post-merge should succeed");
- // Hook should have run
+ // Hook runs in background — wait for it to write the marker file
let marker = repo.root_path().join("hook_ran.txt");
- assert!(marker.exists(), "post-merge hook should have run");
+ crate::common::wait_for_file_content(&marker);
let content = fs::read_to_string(&marker).unwrap();
assert!(content.contains("STANDALONE_POST_MERGE"));
}