Skip to content

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

perf: cache integration target and reason in RepoCache (#1966)

Maximilian Rooseeef0fe1e0aa
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 7fb993c7e..0d37a5fbe 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -311,32 +311,38 @@ impl Repository {
/// Used by both `wt list` and `wt remove` to ensure consistent integration detection.
///
pub fn effective_integration_target(&self, local_target: &str) -> String {
- // Get the upstream ref for the local target (e.g., origin/main for main)
- let upstream = match self.branch(local_target).upstream() {
- Ok(Some(upstream)) => upstream,
- _ => return local_target.to_string(),
- };
-
- // If local and upstream are the same commit, prefer local for clearer messaging
- if self.same_commit(local_target, &upstream).unwrap_or(false) {
- return local_target.to_string();
- }
+ self.cache
+ .effective_integration_targets
+ .entry(local_target.to_string())
+ .or_insert_with(|| {
+ // Get the upstream ref for the local target (e.g., origin/main for main)
+ let upstream = match self.branch(local_target).upstream() {
+ Ok(Some(upstream)) => upstream,
+ _ => return local_target.to_string(),
+ };
+
+ // If local and upstream are the same commit, prefer local for clearer messaging
+ if self.same_commit(local_target, &upstream).unwrap_or(false) {
+ return local_target.to_string();
+ }
- // If upstream contains commits not present in local, prefer upstream so
- // remotely merged branches still count as integrated after a fetch.
- if self.is_ancestor(local_target, &upstream).unwrap_or(false) {
- return upstream;
- }
+ // If upstream contains commits not present in local, prefer upstream so
+ // remotely merged branches still count as integrated after a fetch.
+ if self.is_ancestor(local_target, &upstream).unwrap_or(false) {
+ return upstream;
+ }
- // If upstream is strictly behind local, local is more complete.
- if self.is_ancestor(&upstream, local_target).unwrap_or(false) {
- return local_target.to_string();
- }
+ // If upstream is strictly behind local, local is more complete.
+ if self.is_ancestor(&upstream, local_target).unwrap_or(false) {
+ return local_target.to_string();
+ }
- // Local and upstream have diverged (neither is ancestor of the other).
- // Prefer upstream so remote merges are still visible to integration
- // checks even while local has extra commits.
- upstream
+ // Local and upstream have diverged (neither is ancestor of the other).
+ // Prefer upstream so remote merges are still visible to integration
+ // checks even while local has extra commits.
+ upstream
+ })
+ .clone()
}
/// Get the cached integration target for this repository.
@@ -400,8 +406,19 @@ impl Repository {
branch: &str,
target: &str,
) -> anyhow::Result<(String, Option<IntegrationReason>)> {
- let effective_target = self.effective_integration_target(target);
- let signals = compute_integration_lazy(self, branch, &effective_target)?;
- Ok((effective_target, check_integration(&signals)))
+ use dashmap::mapref::entry::Entry;
+ match self
+ .cache
+ .integration_reasons
+ .entry((branch.to_string(), target.to_string()))
+ {
+ Entry::Occupied(e) => Ok(e.get().clone()),
+ Entry::Vacant(e) => {
+ let effective_target = self.effective_integration_target(target);
+ let signals = compute_integration_lazy(self, branch, &effective_target)?;
+ let result = (effective_target, check_integration(&signals));
+ Ok(e.insert(result).clone())
+ }
+ }
}
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 760bca78a..ad71013d7 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -37,7 +37,7 @@ use dunce::canonicalize;
use crate::config::{ProjectConfig, ResolvedConfig, UserConfig};
// Import types from parent module
-use super::{DefaultBranchName, GitError, LineDiff, WorktreeInfo};
+use super::{DefaultBranchName, GitError, IntegrationReason, LineDiff, WorktreeInfo};
// Re-export types needed by submodules
pub(super) use super::{BranchCategory, CompletionBranch, DiffStats, GitRemoteUrl};
@@ -186,6 +186,20 @@ pub(super) struct RepoCache {
/// Resolved refs: unresolved ref (e.g., "main") -> resolved form (e.g., "refs/heads/main")
/// or original if not a local branch. Populated by `resolve_preferring_branch()`.
pub(super) resolved_refs: DashMap<String, String>,
+ /// Effective integration targets: local_target -> effective ref (may be upstream).
+ /// Cached because `integration_reason()` calls `effective_integration_target()` for
+ /// every branch, but the result depends only on the target ref's relationship with
+ /// its upstream — stable for the duration of a command.
+ pub(super) effective_integration_targets: DashMap<String, String>,
+ /// Integration reason cache: (branch, target) -> (effective_target, reason).
+ /// Populated by `integration_reason()`, avoids redundant `compute_integration_lazy()`
+ /// calls when the same branch is checked multiple times (e.g., step_prune Phase 1
+ /// followed by prepare_worktree_removal).
+ ///
+ /// TODO: `handle_branch_only_output` creates a fresh `Repository::current()` for
+ /// branch-only removals, bypassing this cache. Thread the pre-computed reason
+ /// through `RemoveResult::BranchOnly` to eliminate that redundant check.
+ pub(super) integration_reasons: DashMap<(String, String), (String, Option<IntegrationReason>)>,
/// Tree SHA cache: tree spec (e.g., "refs/heads/main^{tree}") -> SHA.
/// The tree SHA for a given ref doesn't change during a command.
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 98178d9a7..54ef6f8c3 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -194,7 +194,12 @@ fn test_prune_removes_integrated_detached(mut repo: TestRepo) {
repo.add_worktree("detached-integrated");
repo.detach_head_in_worktree("detached-integrated");
- let mut cmd = make_snapshot_cmd(&repo, "step", &["prune", "--yes", "--min-age=0s"], None);
+ let mut cmd = make_snapshot_cmd(
+ &repo,
+ "step",
+ &["prune", "--yes", "--min-age=0s", "--foreground"],
+ None,
+ );
cmd.env("RAYON_NUM_THREADS", "1"); // deterministic output order
assert_cmd_snapshot!(cmd);
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap
index 846f6e62a..91c80430f 100644
--- a/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap
@@ -7,6 +7,7 @@ info:
- prune
- "--yes"
- "--min-age=0s"
+ - "--foreground"
env:
APPDATA: "[TEST_CONFIG_HOME]"
CLICOLOR_FORCE: "1"
@@ -25,6 +26,7 @@ info:
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
PATH: "[PATH]"
PSModulePath: ""
+ RAYON_NUM_THREADS: "1"
RUST_LOG: warn
SHELL: ""
TERM: alacritty
@@ -46,6 +48,7 @@ exit_code: 0
----- stdout -----
----- stderr -----
-◎ Removing worktree @ _REPO_.detached-integrated in background (detached HEAD, no branch to delete)
+◎ Removing worktree @ _REPO_.detached-integrated... (detached HEAD, no branch to delete)
+✓ Removed worktree @ _REPO_.detached-integrated (detached HEAD, no branch to delete)
✓ Removed branch detached-integrated (same commit as main, _)
✓ Pruned 1 worktree, 1 branch