Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(list): deduplicate concurrent ahead/behind counts (#4663)
Worktrunk Botd5a9e4f48d26
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 185ff0ed7..ec99cfc5f 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -512,11 +512,13 @@ impl Repository {/// SHA-keyed ahead/behind counts.///- /// Inputs are commit SHAs. Backed by the persistent SHA-keyed cache- /// (`ahead-behind/{base_sha}-{head_sha}.json`) — content-addressed, so- /// the entry is never stale. `wt list` populates this per branch (and- /// in bulk from a `for-each-ref %(ahead-behind)` batch when most- /// entries are cold); subsequent runs are pure cache reads. Returns+ /// Inputs are commit SHAs. An in-memory cache coalesces concurrent+ /// requests; a persistent SHA-keyed cache+ /// (`ahead-behind/{base_sha}-{head_sha}.json`) serves later runs. Both+ /// are content-addressed, so entries are never stale. `wt list`+ /// populates this per branch (and in bulk from a `for-each-ref+ /// %(ahead-behind)` batch when most entries are cold); subsequent runs+ /// are pure cache reads. Returns/// `(ahead, behind)` where ahead is commits in head not in base;/// orphan branches (no common ancestor) yield `(0, 0)` — caller should/// distinguish via [`Self::merge_base_by_sha`].@@ -525,12 +527,18 @@ impl Repository {base_sha: &str,head_sha: &str,) -> anyhow::Result<(usize, usize)> {- if let Some(cached) = super::sha_cache::ahead_behind(self, base_sha, head_sha) {- return Ok(cached);+ let key = (base_sha.to_string(), head_sha.to_string());+ match self.cache.ahead_behind.entry(key) {+ Entry::Occupied(e) => Ok(*e.get()),+ Entry::Vacant(e) => {+ if let Some(cached) = super::sha_cache::ahead_behind(self, base_sha, head_sha) {+ return Ok(*e.insert(cached));+ }+ let result = self.compute_ahead_behind(base_sha, head_sha)?;+ super::sha_cache::put_ahead_behind(self, base_sha, head_sha, result);+ Ok(*e.insert(result))+ }}- let result = self.compute_ahead_behind(base_sha, head_sha)?;- super::sha_cache::put_ahead_behind(self, base_sha, head_sha, result);- Ok(result)}fn compute_ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4179984a7..ea3b273bc 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -288,6 +288,10 @@ pub(super) struct RepoCache {/// front over the persistent `merge-base/` [`sha_cache`] back; see/// [`Repository::merge_base_by_sha`].pub(super) merge_base: DashMap<(String, String), Option<String>>,+ /// Ahead/behind counts keyed by the ordered (base, head) SHA pair. The+ /// entry lock coalesces concurrent misses from list's parallel tasks.+ /// The persistent `ahead-behind/` cache serves later processes.+ pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,/// Commit→tree cache: commit_sha -> tree_sha. Keys are commit SHAs by/// contract; a commit's tree is immutable, so the mapping is never stale/// within a process. Dedups the `wt list` integration probe, where everydiff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rsindex 1357288fe..d7c579659 100644--- a/tests/integration_tests/statusline.rs+++ b/tests/integration_tests/statusline.rs@@ -67,6 +67,61 @@ fn run_statusline(repo: &TestRepo, args: &[&str], stdin_json: Option<&str>) -> Srun_statusline_from_dir(repo, args, stdin_json, repo.root_path())}+#[rstest]+fn test_statusline_deduplicates_ahead_behind_for_main_upstream(repo: TestRepo) {+ use worktrunk::trace::{TraceEntryKind, parse_lines};++ // Local main trails its upstream, so the mainline and upstream tasks ask+ // for the same SHA pair on a cold cache.+ std::fs::write(repo.root_path().join("next.txt"), "next\n").unwrap();+ repo.run_git(&["add", "next.txt"]);+ repo.run_git(&["commit", "-m", "Next"]);+ let upstream_sha = repo.git_output(&["rev-parse", "HEAD"]);+ repo.run_git(&["update-ref", "refs/remotes/origin/main", &upstream_sha]);+ repo.run_git(&["reset", "--hard", "HEAD~1"]);+ repo.run_git(&["config", "branch.main.remote", "origin"]);+ repo.run_git(&["config", "branch.main.merge", "refs/heads/main"]);+ let main_sha = repo.git_output(&["rev-parse", "HEAD"]);++ let input = serde_json::json!({+ "hook_event_name": "Status",+ "workspace": {"current_dir": repo.root_path()},+ "model": {"display_name": "Opus"},+ "context_window": {"used_percentage": 42.0}+ })+ .to_string();+ let mut cmd = repo.wt_command();+ cmd.args(["-vv", "list", "statusline", "--format=claude-code"]);+ cmd.stdin(Stdio::piped());+ cmd.stdout(Stdio::piped());+ cmd.stderr(Stdio::piped());+ let mut child = cmd.spawn().unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(input.as_bytes())+ .unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "statusline failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let trace = std::fs::read_to_string(repo.root_path().join(".git/wt/logs/trace.jsonl"))+ .expect("-vv should write trace.jsonl");+ let range = format!("{main_sha}..{upstream_sha}");+ let count = parse_lines(&trace)+ .into_iter()+ .filter(|entry| {+ matches!(&entry.kind, TraceEntryKind::Command { command, .. }+ if command.contains("rev-list --count") && command.contains(&range))+ })+ .count();+ assert_eq!(count, 1, "expected one count of {range}; trace:\n{trace}");+}+// --- Test Setup Helpers ---fn add_uncommitted_changes(repo: &TestRepo) {