Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(list): build the ref snapshot from the branch inventories (#4290)
Maximilian Roos4b8e6f9868cd
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 5d1459f25..fa8c0c6bc 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -25,7 +25,7 @@//! | 2 | `git config --list -z` (cwd = discovery path) | [`Repository::prewarm`] (`prewarm_git_config`) | Whole merged config (system + global + local) in one shot, NUL-delimited so values containing `\n` or `=` parse unambiguously. Stashed in `GIT_CONFIG_PRELOAD` keyed by discovery path; every later `config_last("…")` reads from memory. Parallel with #1. |//! | 3 | `git config --list -z` (cwd = `git_common_dir`) | [`Repository::prewarm`] post-pass (`prewarm_git_config_from_common_dir`) | **Conditional.** [`Repository::at`] consumes #2's preload into `cache.all_config`, so `all_config()` is a memory hit on a normal repo. In `extensions.worktreeConfig=true` repos, #2's read is declined — `--list` from a linked worktree misses the main-worktree `config.worktree` overrides (most importantly `core.bare = true` for the `myproject/.git + sibling worktrees` layout) — and prewarm re-forks from the common dir after its threads join, preloading the full merged set. [`Repository::all_config`] forks the same command on demand only when prewarm never ran for the path (a non-base `Repository::at`, tests). See `prewarm_git_config` for the full reasoning. |//! | 4 | `git worktree list --porcelain` | [`Repository::list_worktrees`] | Path, HEAD SHA, branch, and flags per worktree — the row source for the skeleton. The picker prelude triggers this once for `num_items_estimate`; collect's rayon scope then hits the cache. **Plus one `git rev-parse --git-dir` per detached worktree**, run inside the same cache initializer (`finalize_worktrees`): git lists a mid-rebase worktree only as detached, so each detached worktree's git dir is resolved and its `rebase-{merge,apply}/head-name` read to recover the branch. These are the one O(N) fork group before the skeleton — O(detached worktrees), forked together through `Cmd::run_concurrently`. |-//! | 5 | `git for-each-ref --format=… refs/heads/` | [`Repository::local_branches`] inside collect's `rayon::scope` | Local branch tips (name, SHA, committer date, upstream) for branch-only rows (`branches=true`) and for the stale-default-branch check. `remotes=true` adds a sibling `refs/remotes/` fork. Runs beside #4, which is the longer of the two on a repo with many worktrees. The post-skeleton ref snapshot scans `refs/heads/` again rather than reusing this inventory (see "Pipeline"). |+//! | 5 | `git for-each-ref --format=… refs/heads/` | [`Repository::local_branches`] inside collect's `rayon::scope` | Local branch tips (name, SHA, committer date, upstream) for branch-only rows (`branches=true`), the stale-default-branch check, and the post-skeleton ref snapshot. `remotes=true` adds a sibling `refs/remotes/` fork; otherwise the snapshot runs that scan after the skeleton. Runs beside #4, which is the longer of the two on a repo with many worktrees. |//! | 6 | `git log --no-walk --no-show-signature --format=… SHA₁ … SHA_N` | collect, after the scope | Batched commit metadata for every worktree HEAD + branch tip. See breakdown below. |//!//! Things that *look* like forks but aren't, on the steady-state path:@@ -159,16 +159,16 @@//! branch-only rows: default mode), then maybe_spawn_comments (its job//! resolves the forge, which may fork `git remote get-url`)//! J2 rayon::scope ───────────────────────┬─ switch_previous-//! (global pool) ├─ capture_refs[_with_ahead_behind]-//! │ for-each-ref refs/heads/ (again), then refs/remotes/+//! (global pool) ├─ inventory_snapshot J1's branch inventories+//! │ for-each-ref refs/remotes/ unless J1 ran it//! │ + ahead-behind/ cache reads; cold: %(ahead-behind) walk-//! │ └─ spawn prime_upstream_ahead_behind_cache-//! │ cold: one %(ahead-behind) walk per upstream+//! ├─ prime_upstream_ahead_behind_cache+//! │ cold: one %(ahead-behind) walk per upstream//! └─ prime_worktree_path_caches//! canonicalize + read .git × worktrees//! └─ spawn start_fsmonitor_daemon_at × worktrees//! socket connect; fork `start` on a miss-//! join ◄──────────────────────────────┘ (waits for the slowest: usually the snapshot)+//! join ◄──────────────────────────────┘ (waits for the slowest)//! integration_targets, prime_comparison_base, is_previous, commit fields CPU//! generate + sort work items CPU//! std::thread ─► J3 COLLECT_POOL.install(par_bridge) ── work items in queue order,@@ -180,9 +180,10 @@//! Nothing between J1's join and the skeleton overlaps with anything else://! the commit-details fork, row building, and (picker) the CI-cache reads run//! one after another on the collect thread. Nothing between the skeleton and-//! J3 overlaps with the task pool either: the pool opens only after J2 joins,-//! and J2 joins on the ref snapshot, whose two `for-each-ref` scans run one-//! after the other and repeat J1's `refs/heads/` scan.+//! J3 overlaps with the task pool either: the pool opens only after J2 joins.+//! The snapshot reuses J1's inventories, so on a warm ahead-behind cache it+//! forks at most the `refs/remotes/` scan J1 skipped (none in the picker,+//! whose prelude already ran it); cold, it adds an `%(ahead-behind)` walk.//!//! ### Picker prelude//!@@ -194,7 +195,7 @@//! remotes shown, `local_branches` / `remote_branches`. The estimate only//! counts rows, so it does not need the backfill, but it pays for it on the//! main thread before skim starts. The speculative preview resolves its-//! comparison base through `capture_refs`, which fills the same+//! comparison base through `inventory_snapshot`, which reads the same//! `local_branches` / `remote_branches` cells, so the estimate may block on a//! cell that preview job is initializing. `collect()`'s J1 then finds every//! inventory cached.@@ -915,26 +916,10 @@ pub fn collect(let render_table = matches!(render_target, RenderTarget::Table { .. });worktrunk::trace::instant("List collect started");- // Determine what to fetch speculatively in the parallel phase.- //- // For Resolved: respect the caller's flags (fetch only what's requested).- // For DeferredToParallel: always fetch local branches speculatively (~7ms,- // hidden by parallelism) since config resolution happens after. Remote- // branches are only fetched if the CLI flag is set (can be expensive).- let (fetch_branches, fetch_remotes) = match &show_config {- ShowConfig::Resolved {- show_branches,- show_remotes,- ..- } => (*show_branches, *show_remotes),- ShowConfig::DeferredToParallel { cli_remotes, .. } => {- // Always fetch local branches: ~7ms hidden by parallelism, needed if- // config says branches=true (which we won't know until after this phase).- // Only fetch remotes when CLI-requested (can be expensive, rarely config-only).- let fetch_branches = true;- let fetch_remotes = *cli_remotes;- (fetch_branches, fetch_remotes)- }+ // Remote rows requested up front; config can still add them after phase 1.+ let fetch_remotes = match &show_config {+ ShowConfig::Resolved { show_remotes, .. } => *show_remotes,+ ShowConfig::DeferredToParallel { cli_remotes, .. } => *cli_remotes,};// Phase 1: Parallel fetch of ALL independent git data@@ -948,10 +933,14 @@ pub fn collect(// - url_template: independent (loads project config via show-toplevel)// - project_identifier: independent (git config for remote URL; warms cache// for is_worktree_at_expected_path and config resolution)- // - local_branches: independent (one `for-each-ref refs/heads/`; cached on- // `RepoCache` so later consumers read it without re-scanning)- // - remote_branches: independent (one `for-each-ref refs/remotes/`; cached- // on `RepoCache`)+ // - local_branches: independent (one `for-each-ref refs/heads/`, cached on+ // `RepoCache`). Fetched whatever the row flags say: config may turn on+ // branch rows, and the post-skeleton ref snapshot is built from it.+ // - remote_branches: independent (one `for-each-ref refs/remotes/`, cached+ // on `RepoCache`). Fetched here only when remote rows are requested, so+ // the skeleton never waits on a scan it doesn't render: a repo with many+ // remote branches and few worktrees would otherwise paint later. The+ // snapshot scans it after the skeleton when this didn't.//// After this scope completes, we have all raw data and can do CPU-only work.let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();@@ -980,15 +969,12 @@ pub fn collect(let _ = repo.config();});s.spawn(|_| {- if fetch_branches {- // Prime the local-branch inventory on `RepoCache`; consumers- // below read it through `repo.local_branches()`.- let _ = repo.local_branches();- }+ // Prime the branch inventories on `RepoCache`; consumers below+ // read them through `repo.local_branches()` / `remote_branches()`.+ let _ = repo.local_branches();});s.spawn(|_| {if fetch_remotes {- // Prime the remote-branch inventory on `RepoCache`.let _ = repo.remote_branches();}});@@ -1069,11 +1055,11 @@ pub fn collect(// the persisted value, now trusted without validation on the hot path.// Cross-check against the enumerated branch set and surface a warning// if it's been deleted externally. When `show_branches` is off but a- // persisted default is set and isn't a worktree branch, scan the local- // branch inventory anyway (one `for-each-ref` fork, cached afterwards)- // so the warning fires on plain `wt list` too — otherwise downstream- // tasks resolve against the stale ref and emit a cascade of "ambiguous- // argument" noise instead of one clean warning.+ // persisted default is set and isn't a worktree branch, check the local+ // branch inventory anyway (scanned above) so the warning fires on plain+ // `wt list` too — otherwise downstream tasks resolve against the stale+ // ref and emit a cascade of "ambiguous argument" noise instead of one+ // clean warning.let worktree_branches = worktree_branch_set(worktrees);let needs_stale_check = default_branch.as_deref()@@ -1669,83 +1655,63 @@ pub fn collect(let _ = previous_branch_cell.set(repo.switch_previous());});- // Capture ref state: `for-each-ref refs/heads/ refs/remotes/`,- // plus — when default_branch is known and the per-base- // ahead-behind cache doesn't already cover the branches — one- // `for-each-ref %(ahead-behind:BASE)` walk (scoped to the cold- // subset; warm runs do neither). Tasks consume the snapshot by- // SHA, dodging ref→SHA cache staleness.- //- // After the snapshot is built, an inner spawn primes the- // `Remote⇅` cache off its already-scanned inventories — see the- // nested `s.spawn` below for the rationale.+ // Build the ref snapshot from the branch inventories (J1 scanned the+ // locals, and the remotes when rows show them), so tasks resolve+ // refs to the same SHAs the rows were built from. When+ // default_branch is known and the per-base ahead-behind cache+ // doesn't already cover the branches, add one `for-each-ref+ // %(ahead-behind:BASE)` walk (scoped to the cold subset; warm runs+ // do neither).//// TODO(ahead-behind-pool): the `%(ahead-behind)` walk that runs// here on a cold cache is serial — it blocks this scope, and the// big task pool can't open until it returns. Nothing downstream of// work-item generation actually needs the ahead/behind *counts*// (only the per-row ahead/behind task reads them, and it has a- // per-SHA fallback) — only the cheap `for-each-ref refs/heads/- // refs/remotes/` ref scan gates work-item generation. So the walk- // could become a single work item in the pool, overlapping the- // other ~N workers, instead of a serial prelude. That needs an- // inter-task dependency (the per-row tasks would wait on it, or it- // would emit their results directly) — the work-item model has- // none today.- s.spawn(|s| {- let snap = match default_branch.as_deref() {- Some(db) => repo.capture_refs_with_ahead_behind(db).ok(),- None => repo.capture_refs().ok(),- }- .map(std::sync::Arc::new);-- // Prime the `ahead-behind/` SHA-cache for the `Remote⇅`- // column, pairing each local branch with its configured- // upstream. Mirrors the `main↕` priming inside- // `capture_refs_with_ahead_behind`, but per-upstream-group- // instead of single-base: one serial `for-each-ref- // %(ahead-behind:UPSTREAM_SHA)` walk per unique upstream- // that's both cold and above the same threshold.- //- // Nested inside this spawn (rather than a sibling) so it can- // read the snapshot's already-scanned local/remote- // inventories — a sibling spawn would race the snapshot's- // own scans and (when `--remotes` is off) fire a redundant- // `for-each-ref refs/remotes/`. The primer still runs in- // parallel with downstream scope work (fsmonitor, etc.); it- // just gates on its data dependency.- //- // Scope to branches that will actually render an- // Upstream-task row: with `--branches` that's every local;- // without it that's just the worktree-attached subset.- // Otherwise plain `wt list` on a repo with many stale- // tracking branches would block the worker pool on a serial- // batch for rows nobody sees.- if let Some(snap_arc) = snap.as_ref() {- let snap_for_primer = std::sync::Arc::clone(snap_arc);- s.spawn(move |_| {- let all_locals = snap_for_primer.local_branches();- let filtered_locals: Vec<LocalBranch>;- let candidates: &[LocalBranch] = if show_branches {- all_locals- } else {- filtered_locals = all_locals- .iter()- .filter(|b| worktree_branches.contains(b.name.as_str()))- .cloned()- .collect();- &filtered_locals- };- repo.prime_upstream_ahead_behind_cache(- candidates,- snap_for_primer.remote_branches(),- );- });- }-+ // per-SHA fallback) — work-item generation needs only the ref+ // SHAs from the inventories. So the walk could become a single+ // work item in the pool, overlapping the other ~N workers, instead+ // of a serial prelude. That needs an inter-task dependency (the+ // per-row tasks would wait on it, or it would emit their results+ // directly) — the work-item model has none today.+ s.spawn(|_| {+ let snap = repo+ .inventory_snapshot(default_branch.as_deref())+ .ok()+ .map(std::sync::Arc::new);let _ = snapshot_cell.set(snap);});+ // Prime the `ahead-behind/` SHA-cache for the `Remote⇅` column,+ // pairing each local branch with its configured upstream. Mirrors+ // the `main↕` priming inside `inventory_snapshot`, but+ // per-upstream-group instead of single-base: one serial+ // `for-each-ref %(ahead-behind:UPSTREAM_SHA)` walk per unique+ // upstream that's both cold and above the same threshold. It reads+ // the same inventories as the snapshot, so it runs beside it.+ //+ // Scope to branches that will actually render an Upstream-task+ // row: with `--branches` that's every local; without it that's+ // just the worktree-attached subset. Otherwise plain `wt list` on a+ // repo with many stale tracking branches would block the worker+ // pool on a serial batch for rows nobody sees.+ s.spawn(|_| {+ if let (Ok(all_locals), Ok(remotes)) = (repo.local_branches(), repo.remote_branches()) {+ let filtered_locals: Vec<LocalBranch>;+ let candidates: &[LocalBranch] = if show_branches {+ all_locals+ } else {+ filtered_locals = all_locals+ .iter()+ .filter(|b| worktree_branches.contains(b.name.as_str()))+ .cloned()+ .collect();+ &filtered_locals+ };+ repo.prime_upstream_ahead_behind_cache(candidates, remotes);+ }+ });+// Seed root/git-dir for every worktree from the list we already// fetched, so the per-worktree tasks don't each fork `git rev-parse// --show-toplevel` / `--git-dir`. Post-skeleton, because only thediff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex 643489c27..4c6520f59 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -110,8 +110,9 @@ impl Repository {/// this `Repository` instance (shared across clones via `Arc`).////// `commit_sha` on each entry is a snapshot at scan time. Code that- /// needs a current SHA for a ref must resolve through a `RefSnapshot`- /// captured at the moment of read, not through this inventory. The+ /// needs a current SHA for a ref must resolve through+ /// [`Repository::capture_refs`] at the moment of read, not through this+ /// inventory or a snapshot built from it. The/// inventory itself is used for branch listing and upstream-tracking/// metadata, stable for the duration of a command that runs no hook./// A hook runs inside the command, so one that touches refs leaves the@@ -194,8 +195,8 @@ impl Repository {/// (first-scan-wins cell vs. fresh snapshot).////// `commit_sha` is a snapshot at scan time — callers that need a- /// current SHA must resolve through a [`crate::git::RefSnapshot`]- /// captured at the moment of the read, not through this list.+ /// current SHA must resolve through [`Repository::capture_refs`] at the+ /// moment of the read, not through this list.pub(super) fn scan_local_branch_records(&self) -> anyhow::Result<Vec<LocalBranch>> {let output = self.run_command(&["for-each-ref", LOCAL_BRANCH_FORMAT, "refs/heads/"])?;let mut branches: Vec<LocalBranch> =diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex f2ca3d2e2..57ba4de70 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -616,9 +616,10 @@ impl Repository {/// Selects the base via the shared [`select_comparison_base`] rule/// ([`IntegrationTargets::primary`] else the raw local default), so the/// preview panes and the `wt list` columns can't pick different bases.- /// Captures a [`RefSnapshot`] on first call unless already primed via- /// [`Self::prime_comparison_base`]; safe in the read-only preview contexts- /// that use it (wt doesn't move refs there). Fully local — no network.+ /// Builds a [`RefSnapshot`] from the branch inventories on first call+ /// unless already primed via [`Self::prime_comparison_base`]; safe in the+ /// read-only preview contexts that use it (wt doesn't move refs there).+ /// Fully local — no network.fn comparison_base(&self) -> Option<&ComparisonBase> {self.cache.comparison_base@@ -641,12 +642,12 @@ impl Repository {fn resolve_comparison_base(&self) -> Option<ComparisonBase> {// No default branch → no comparison base; skip the ref scan entirely.self.default_branch()?;- let snapshot = self.capture_refs().ok()?;+ let snapshot = self.inventory_snapshot(None).ok()?;self.comparison_base_from(&snapshot)}/// Resolve the comparison base from a captured snapshot. The shared core of- /// the lazy [`Self::resolve_comparison_base`] (captures its own snapshot)+ /// the lazy [`Self::resolve_comparison_base`] (builds its own snapshot)/// and [`Self::prime_comparison_base`] (reuses the collector's), so both/// select the base by the same [`select_comparison_base`] rule.fn comparison_base_from(&self, snapshot: &RefSnapshot) -> Option<ComparisonBase> {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex eca8505a3..d4b58093f 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -252,7 +252,8 @@ pub(super) struct RepoCache {pub(super) default_branch: OnceCell<Option<String>>,/// Upstream-aware comparison base for the diff/summary preview panes —/// [`integration::IntegrationTargets::primary`], resolved once. Repo-wide- /// like `default_branch`; captures a [`RefSnapshot`] on first access via+ /// like `default_branch`; builds a [`RefSnapshot`] from the branch+ /// inventories on first access via/// [`Repository::branch_diff_spec`]. `None` when no default branch resolves.pub(super) comparison_base: OnceCell<Option<integration::ComparisonBase>>,/// Project identifier derived from remote URL@@ -315,8 +316,9 @@ pub(super) struct RepoCache {/// [`Repository::local_branches`].////// **The `commit_sha` field on each entry is a snapshot at scan time.**- /// Code that needs a current SHA must resolve through a [`RefSnapshot`]- /// captured at the moment the read happens — not through this inventory.+ /// Code that needs a current SHA must resolve through+ /// [`Repository::capture_refs`] at the moment the read happens — not+ /// through this inventory or a snapshot built from it./// Everything else the inventory holds goes stale the same way once the/// command runs a hook; [`Repository::local_branches`] owns that contract.pub(super) local_branches: OnceCell<branches::LocalBranchInventory>,diff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rsindex 07ee3996c..ff0cb6830 100644--- a/src/git/repository/ref_snapshot.rs+++ b/src/git/repository/ref_snapshot.rs@@ -1,19 +1,23 @@//! `RefSnapshot` — a captured, immutable view of repository ref state.//!//! A `RefSnapshot` is an explicit, named, point-in-time value: callers-//! capture it once and thread it through. Unlike an ambient ref-name → SHA-//! cache, it cannot go stale invisibly when wt updates a ref mid-command —-//! `wt merge`'s `git update-ref refs/heads/main` is the canonical example.-//! After a ref-mutating write, the caller captures a new snapshot and uses-//! it for downstream reads — the old snapshot remains valid as a pre-write-//! view, but cannot masquerade as current state.+//! capture it once and thread it through. Which point in time depends on+//! the constructor. [`Repository::capture_refs`] scans at the call, so after+//! a ref-mutating write (`wt merge`'s `git update-ref refs/heads/main` is the+//! canonical example) the caller captures a new snapshot for downstream+//! reads — the old one remains valid as a pre-write view, but cannot+//! masquerade as current state. [`Repository::inventory_snapshot`] is as of+//! the repository's cached branch inventories, for read-only commands whose+//! rows come from those same inventories.//!//! # Construction//!//! [`Repository::capture_refs`] runs one `git for-each-ref refs/heads/`//! plus one `git for-each-ref refs/remotes/` and parses both into a-//! single `RefSnapshot`. [`Repository::capture_refs_with_ahead_behind`]-//! additionally populates ahead/behind counts: it reads them from the+//! single `RefSnapshot`. [`Repository::inventory_snapshot`] instead builds+//! it from the repository's cached branch inventories, which a read-only+//! command like `wt list` has already scanned for its rows, and optionally+//! populates ahead/behind counts: it reads them from the//! persistent SHA-keyed cache (`ahead-behind/` — content-addressed, so//! never stale) and only falls back to a `for-each-ref ...//! %(ahead-behind:BASE)` batch walk (git ≥ 2.36) when the cache is cold@@ -24,11 +28,9 @@//!//! # Lifetime//!-//! The snapshot is a value, not a cache field. There is no `OnceCell`,-//! no `Arc<DashMap>`, no shared mutable state. Two `capture_refs()`-//! calls within one command produce two distinct snapshots; neither-//! invalidates the other. This is intentional — it removes the-//! "invisible refresh" surface that ambient caching introduces.+//! The snapshot is a value, not a cache field: nothing refreshes it after+//! construction. Two `capture_refs()` calls within one command produce two+//! distinct snapshots; neither invalidates the other.use std::collections::HashMap;@@ -58,7 +60,7 @@ pub struct RefSnapshot {/// Ahead/behind counts keyed by `(base, head)` ref names./// Populated only when constructed via- /// [`Repository::capture_refs_with_ahead_behind`], and even then it+ /// [`Repository::inventory_snapshot`] with a base, and even then it/// may be partial: a branch that moved since its last cache write is/// omitted (the per-branch task recomputes it by SHA). On git < 2.36/// a cold base yields an empty map. Callers that need ahead/behind for@@ -129,7 +131,16 @@ impl Repository {Ok(build(locals, remotes, HashMap::new()))}- /// Capture current ref state plus ahead/behind counts vs `base`.+ /// Build a [`RefSnapshot`] from this repository's branch inventories+ /// ([`Self::local_branches`], [`Self::remote_branches`]), plus+ /// ahead/behind counts vs `base` when one is given.+ ///+ /// Unlike [`Self::capture_refs`], this forks no `for-each-ref` for an+ /// inventory that is already cached, so the snapshot is as of that+ /// inventory's first scan in this `Repository`'s lifetime. That suits a+ /// read-only command that built its rows from the same inventories, like+ /// `wt list`: rows and snapshot then agree on every SHA. A command that+ /// moves a ref and then reads it uses `capture_refs`.////// Ahead/behind for `(base, branch)` is content-addressed — a pure/// function of the two commit SHAs — so the snapshot map is built from@@ -152,10 +163,12 @@ impl Repository {/// normalized to `(0, 0)`, matching `compute_ahead_behind`. On git </// 2.36 the `%(ahead-behind)` walk yields nothing and the affected/// keys stay absent — callers fall back to per-pair queries.- pub fn capture_refs_with_ahead_behind(&self, base: &str) -> anyhow::Result<RefSnapshot> {- let locals = scan_locals(self)?;- let remotes = scan_remotes(self)?;- let ahead_behind = self.capture_ahead_behind(base, &locals, &remotes);+ pub fn inventory_snapshot(&self, base: Option<&str>) -> anyhow::Result<RefSnapshot> {+ let locals = self.local_branches()?.to_vec();+ let remotes = self.remote_branches()?.to_vec();+ let ahead_behind = base.map_or_else(HashMap::new, |base| {+ self.capture_ahead_behind(base, &locals, &remotes)+ });Ok(build(locals, remotes, ahead_behind))}@@ -163,7 +176,7 @@ impl Repository {/// local branches, preferring the persistent SHA-keyed cache and/// reaching for a `for-each-ref %(ahead-behind)` walk only for the/// branches the cache doesn't cover. See- /// [`Self::capture_refs_with_ahead_behind`].+ /// [`Self::inventory_snapshot`].fn capture_ahead_behind(&self,base: &str,@@ -173,7 +186,7 @@ impl Repository {let full_ref = |b: &LocalBranch| format!("refs/heads/{}", b.name);// The cache is SHA-keyed; we need base's SHA, and it's a branch —- // so it's among the refs we just scanned. If somehow it isn't, the+ // so it's among the inventoried refs. If somehow it isn't, the// cache is unreachable for this run: run the batch against the// refname (git resolves it), key the snapshot map by refname, and// cache nothing.@@ -281,11 +294,11 @@ impl Repository {/// upstream and, for the ones the cache doesn't already cover, runs/// one `for-each-ref %(ahead-behind:UPSTREAM_SHA)` walk per unique/// upstream SHA — the same shared-graph-traversal win that- /// [`Self::capture_refs_with_ahead_behind`] uses for the `main↕`+ /// [`Self::inventory_snapshot`] uses for the `main↕`/// column, scoped to branches sharing one base.////// Mirrors the cache-correctness defenses applied in- /// [`Self::capture_refs_with_ahead_behind`]:+ /// [`Self::inventory_snapshot`]:/// `%(ahead-behind:UPSTREAM_SHA)` (not `:UPSTREAM_REFNAME`) so git/// counts against the SHA the cache will be keyed by — a tag/// shadowing the remote-tracking branch can't poison the entry; the@@ -306,7 +319,7 @@ impl Repository {/// `capture_ahead_behind` uses for the cold-subset batch is also/// skipped — the per-row upstream task will recompute those by SHA/// in the parallel pool, which beats blocking the pool on a small- /// serial batch. Unlike [`Self::capture_refs_with_ahead_behind`]+ /// serial batch. Unlike [`Self::inventory_snapshot`]/// there is no "all cold → unscoped walk" shortcut: each upstream/// group's refs are already the maximal set of branches that track/// it.@@ -629,7 +642,7 @@ mod tests {test.run_git(&["checkout", "main"]);let repo = Repository::at(test.root_path()).unwrap();- let snap = repo.capture_refs_with_ahead_behind("main").unwrap();+ let snap = repo.inventory_snapshot(Some("main")).unwrap();// The plain capture leaves ahead_behind empty.let plain = repo.capture_refs().unwrap();@@ -654,7 +667,7 @@ mod tests {// First capture: cold base → runs the batch walk, seeds the cache.let repo = Repository::at(test.root_path()).unwrap();- let first = repo.capture_refs_with_ahead_behind("main").unwrap();+ let first = repo.inventory_snapshot(Some("main")).unwrap();// Skip on git < 2.36 where the batch silently yields nothing.let Some((1, 0)) = first.ahead_behind("main", "refs/heads/feature") else {return;@@ -680,7 +693,7 @@ mod tests {// Second capture (fresh repo): every entry is cached → no batch// walk → the map reflects the tampered value.let repo2 = Repository::at(test.root_path()).unwrap();- let second = repo2.capture_refs_with_ahead_behind("main").unwrap();+ let second = repo2.inventory_snapshot(Some("main")).unwrap();assert_eq!(second.ahead_behind("main", "refs/heads/feature"),Some((7, 3)),@@ -698,7 +711,7 @@ mod tests {test.run_git(&["checkout", "main"]);let repo = Repository::at(test.root_path()).unwrap();- let first = repo.capture_refs_with_ahead_behind("main").unwrap();+ let first = repo.inventory_snapshot(Some("main")).unwrap();// Skip on git < 2.36.if first.ahead_behind("main", "refs/heads/feature").is_none() {return;@@ -713,7 +726,7 @@ mod tests {test.run_git(&["checkout", "main"]);let repo2 = Repository::at(test.root_path()).unwrap();- let snap = repo2.capture_refs_with_ahead_behind("main").unwrap();+ let snap = repo2.inventory_snapshot(Some("main")).unwrap();// Partial-warm path: feature moved → omitted from the snapshot map// (its per-branch task recomputes by SHA); main is still present.assert_eq!(snap.ahead_behind("main", "refs/heads/feature"), None);@@ -733,7 +746,7 @@ mod tests {// First capture: everything cold → unscoped batch seeds the cache.let repo = Repository::at(test.root_path()).unwrap();- let first = repo.capture_refs_with_ahead_behind("main").unwrap();+ let first = repo.inventory_snapshot(Some("main")).unwrap();if first.ahead_behind("main", "refs/heads/feat0").is_none() {return; // git < 2.36 — %(ahead-behind) unsupported}@@ -749,7 +762,7 @@ mod tests {test.run_git(&["checkout", "main"]);let repo2 = Repository::at(test.root_path()).unwrap();- let snap = repo2.capture_refs_with_ahead_behind("main").unwrap();+ let snap = repo2.inventory_snapshot(Some("main")).unwrap();for i in 0..10 {assert_eq!(snap.ahead_behind("main", &format!("refs/heads/feat{i}")),@@ -773,7 +786,7 @@ mod tests {test.run_git(&["checkout", "main"]);let repo = Repository::at(test.root_path()).unwrap();- let snap = repo.capture_refs_with_ahead_behind("main").unwrap();+ let snap = repo.inventory_snapshot(Some("main")).unwrap();// git < 2.36 — %(ahead-behind) unsupported, nothing seeded.if snap.ahead_behind("main", "refs/heads/main").is_none() {return;@@ -813,7 +826,7 @@ mod tests {test.run_git(&["commit", "-m", "feat"]);let repo = Repository::at(test.root_path()).unwrap();- let snap = repo.capture_refs_with_ahead_behind("origin/trunk").unwrap();+ let snap = repo.inventory_snapshot(Some("origin/trunk")).unwrap();let Some((1, 0)) = snap.ahead_behind("origin/trunk", "refs/heads/feature") else {// git < 2.36: batch silently empty; the cache is unreachable// for it, but resolve-via-remote still ran without panicking.@@ -836,7 +849,7 @@ mod tests {// cache, and the `for-each-ref %(ahead-behind:...)` walk fails too.// The snapshot is still valid, just without ahead/behind.let snap = repo- .capture_refs_with_ahead_behind("definitely-not-a-ref")+ .inventory_snapshot(Some("definitely-not-a-ref")).unwrap();assert_eq!(snap.ahead_behind("definitely-not-a-ref", "refs/heads/main"),@@ -930,6 +943,28 @@ mod tests {assert_eq!(snap.resolve("main"), Some(main_after.as_str()));}+ #[test]+ fn inventory_snapshot_reuses_cached_inventories() {+ // The counterpart of the test above: `wt list` builds its rows from+ // the inventories, then its snapshot, and the two must agree, so+ // `inventory_snapshot` reads the cached scans rather than rescanning.+ let test = TestRepo::with_initial_commit();+ let main_before = test.git_output(&["rev-parse", "main"]);+ test.run_git(&["update-ref", "refs/remotes/origin/main", &main_before]);+ let repo = Repository::at(test.root_path()).unwrap();+ repo.local_branches().unwrap();+ repo.remote_branches().unwrap();++ std::fs::write(test.root_path().join("a.txt"), "x\n").unwrap();+ test.run_git(&["add", "a.txt"]);+ test.run_git(&["commit", "-m", "advance main"]);+ test.run_git(&["update-ref", "refs/remotes/origin/main", "main"]);++ let snap = repo.inventory_snapshot(None).unwrap();+ assert_eq!(snap.resolve("main"), Some(main_before.as_str()));+ assert_eq!(snap.resolve("origin/main"), Some(main_before.as_str()));+ }+#[test]fn capture_refs_populates_remote_branch_cache() {// Mirrors `capture_refs_populates_local_branch_cache`: the