Skip to content

refactor(repo): consolidate branch-enumeration scans into a single inventory - #2368

Merged
max-sixty merged 2 commits into
mainfrom
branch-inventory
Apr 22, 2026
Merged

max-sixty merged 2 commits into
mainfrom
branch-inventory

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Summary

src/git/repository/branches.rs had five overlapping for-each-ref accessors, each with a subtly different format string: all_branches, list_local_branches, list_remote_branches, list_tracked_upstreams, fetch_all_upstreams. On wt list --branches --remotes at least three of them fired in one invocation. Branch also exposed both upstream() (bulk scan, lazy) and upstream_single() (one-off) — two paths to the same answer.

Replaces the whole surface with two scans cached on RepoCache:

  • refs/heads/ → LocalBranchInventory (Vec<LocalBranch> + name → index map for O(1) lookups). Carries upstream info + SHA so no follow-up scan is needed.
  • refs/remotes/ → Vec<RemoteBranch>.

Public accessors: Repository::local_branches() -> &[LocalBranch], Repository::remote_branches() -> &[RemoteBranch]. Branch::upstream() is now a single canonical lookup through the inventory; upstream_single is gone.

Navigating the diff

  • src/git/repository/branches.rs — new inventory types, scan functions, and the surviving public accessors (all_branches, available_branches, branches_for_completion).
  • src/git/repository/branch.rs — Branch::upstream now reads from the inventory via Repository::local_branch(name).
  • src/git/mod.rs — new LocalBranch / RemoteBranch public types.
  • src/git/repository/mod.rs — two new OnceCells on RepoCache (replaces the old upstreams cell).
  • src/commands/list/collect/mod.rs — parallel phase primes the inventory; later consumers read from the cache. The old list_untracked_remote_branches helper is inlined at its sole caller.
  • src/commands/picker/mod.rs, src/commands/worktree/switch.rs, src/commands/command_executor.rs, src/git/repository/integration.rs — callers updated to the canonical upstream() / inventory accessors.

Results

  • Subprocess count on wt list --branches --remotes drops from ≥3 for-each-ref scans of refs/heads/ + 1 of refs/remotes/ down to exactly 2 (one per ref namespace).
  • skeleton/warm/8 benchmark: ~89ms on main → ~27ms here, well under the 60ms target.
  • Format string uses %00 as the field separator so NUL-containing args never hit Command::arg (Rust rejects them before exec).

Test plan

  • `cargo run -- hook pre-merge --yes` (3325 tests pass, all lints clean)
  • Subprocess count verified by RUST_LOG=worktrunk=debug wt list --branches --remotes — exactly 2 inventory for-each-ref calls (plus the unrelated ahead-behind batch that already existed).
  • Skeleton benchmark checked against main.

This was written by Claude Code on behalf of @max-sixty

max-sixty and others added 2 commits April 21, 2026 18:07
…ventory

`src/git/repository/branches.rs` had five overlapping `for-each-ref`
accessors, each with a subtly different format string: `all_branches`,
`list_local_branches`, `list_remote_branches`, `list_tracked_upstreams`,
`fetch_all_upstreams`. On `wt list --branches --remotes` at least three
of them fired in one invocation. And `Branch` exposed both
`upstream()` (bulk scan, lazy) and `upstream_single()` (one-off) to let
callers pick between them — two paths to the same answer.

Replaces the whole surface with two scans cached on `RepoCache`:

  - `refs/heads/` → `LocalBranchInventory` (Vec<LocalBranch> + name→index
    map for O(1) lookups). Carries upstream info + SHA so no follow-up
    scan is needed.
  - `refs/remotes/` → `Vec<RemoteBranch>`.

Public accessors: `Repository::local_branches() -> &[LocalBranch]`,
`Repository::remote_branches() -> &[RemoteBranch]`. `Branch::upstream()`
is now a single canonical lookup through the inventory; `upstream_single`
is gone.

`collect/mod.rs` primes the two cells in the existing parallel phase;
downstream consumers read from the cache. The picker estimate, plain
`all_branches`, `available_branches`, and `branches_for_completion` all
route through the inventory.

Subprocess count on `wt list --branches --remotes` drops from ≥3
`for-each-ref` scans of `refs/heads/` (list_local_branches,
list_tracked_upstreams, fetch_all_upstreams) + 1 of `refs/remotes/` down
to exactly 2. Skeleton benchmark (`skeleton/warm/8`) drops from ~89ms on
main to ~27ms here, well under the <60ms target.

Format string uses `%00` as the field separator so NUL-containing args
never hit `Command::arg` (Rust rejects them before exec).

> _This was written by Claude Code on behalf of @max-sixty_

Co-authored-by: Claude <noreply@anthropic.com>
@max-sixty
max-sixty merged commit 5fe9393 into main Apr 22, 2026
26 checks passed
@max-sixty
max-sixty deleted the branch-inventory branch April 22, 2026 01:22
max-sixty added a commit that referenced this pull request Apr 22, 2026
…h inventory (#2371)

Drops the per-call `git for-each-ref refs/remotes/*/<name>` subprocess
in `Branch::remotes()` and replaces it with an in-memory filter over
`Repository::remote_branches()`. The inventory was introduced in #2368;
this is follow-up #1 — the one accessor left outside the consolidation.

On `wt switch <branch>` for a remote-only branch, the old code spawned a
duplicate `refs/remotes/` scan after the inventory scan had already run.
After this change there is one canonical `for-each-ref refs/remotes/`
per Repository, shared by every caller.

### Behavioral note

When multiple remotes have the same branch, `remotes()[0]` now reflects
the inventory's committer-timestamp-desc order rather than git's
alphabetical default. The only affected sites are informational — the
remote name shown in a warning at `switch.rs:417` and the
`RemoteOnlyBranch` error at `repository_ext.rs:156`. No correctness
impact, and nearly all users have a single remote.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
max-sixty added a commit that referenced this pull request Apr 22, 2026
…cesses (#2372)

`Repository::strip_remote_prefix` ran `git rev-parse --verify
refs/remotes/<ref>` followed by `git remote` every call — two
subprocesses to satisfy `wt switch origin/<branch>` in the picker path.
The remote-branch inventory from #2368 already splits each ref into
`short_name`/`remote_name`/`local_name`, so the lookup collapses to a
direct search in the cached slice. The adjacent TODO that was explicitly
waiting on this inventory shape is satisfied and removed.

Behavioral equivalence holds on every realistic input: local branch
names and SHAs still return `None` (not in the inventory), and
non-existent refs under an existing remote prefix still return `None`.
The one subtle change is that `origin/HEAD` now returns `None` instead
of `Some("HEAD")` — `parse_remote_branch_line` drops the symref. The
switch call site would have mishandled `"HEAD"` as a branch name anyway,
so this is a correctness improvement.

Co-authored-by: Claude <noreply@anthropic.com>
max-sixty added a commit that referenced this pull request Apr 22, 2026
`wt switch` (picker mode) was firing `git worktree list --porcelain`
twice sequentially on the critical path to skeleton — once on the main
thread for `num_items_estimate` (which sizes skim's preview window),
once on the background thread inside `collect::collect`. The picker
already shares an `Arc<RepoCache>` between the two calls, so lifting the
scan into a `OnceCell<Vec<WorktreeInfo>>` there makes the second call a
cache hit. On the worktrunk dev repo the pre-skeleton subprocess count
for this cluster goes 2 → 1.

The invariant follows the same rule PR #2368 established for branch
inventories: no caller reads through the cache after its own worktree
mutation. I audited every `list_worktrees` caller and its internal
helpers (`worktree_for_branch`, `worktree_at_path`,
`current_worktree_info`, `resolve_worktree`, `available_branches`,
`branches_for_completion`) — mutating paths either snapshot once up
front and thread the slice through (`validate_remove_targets`,
`step_prune`), skip re-reading post-mutation (`handle_switch`,
`handle_promote`, `step_for_each`, `relocate`), or rebuild a fresh
`Repository::at(...)` on a background thread
(`PickerCollector::do_removal`). The `execute_switch` post-create
`worktree_for_branch(base)` at `switch.rs:892` reads the unchanged base
branch's worktree, not the newly-created one.

The `-> anyhow::Result<Vec<WorktreeInfo>>` signature stays — clones from
the cache on each call — rather than migrating to `&[WorktreeInfo]` like
`local_branches` / `remote_branches`. That keeps ~20 callers untouched;
the clone cost (~7 `WorktreeInfo` per call) is microseconds vs. the
5–10ms subprocess it replaces. Future parity work is tracked informally.

Updated the `# Caching` module docstring to move `list_worktrees` out of
the "NOT cached" list and document the invariant. Closes the
`TODO(picker-perf)` at `src/commands/picker/mod.rs:81-88`.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude <noreply@anthropic.com>
max-sixty added a commit that referenced this pull request May 9, 2026
## Summary

The TODO in `src/commands/picker/mod.rs` asking to "dedupe
`list_worktrees` calls between `num_items_estimate` and
`collect::collect`" has already been resolved.

`Repository::list_worktrees` has been cached on `RepoCache` since
2114fda (#2375), and the picker shares that cache across its main
thread and the bg `picker-collect` thread via `Arc<RepoCache>` —
`repo.clone()` shares the `OnceCell<Vec<WorktreeInfo>>`, so the second
call is a memory hit.

The `RepoCache::worktrees` docstring already states the contract: *"The
picker warms this on the main thread (for its preview-window sizing
estimate) so the background `collect::collect` pass hits memory instead
of respawning the subprocess on the critical path to skeleton."*

The TODO was originally added in #2250 and partially walked back in
#2368 (the parenthetical noting the branch-inventory cache), but the
body was never updated when #2375 closed the worktree half.

## Verification

`RUST_LOG=worktrunk=debug WORKTRUNK_PICKER_DRY_RUN=1 wt -C <picker-test>
switch` against the `wt-perf setup picker-test` repo shows exactly one
`git worktree list --porcelain` subprocess per invocation (1 `wt-trace`
record, 1 spawn debug line).

No behavior change — pure doc-comment deletion (9 lines).

## Test plan

- [x] `pre-commit run --files src/commands/picker/mod.rs` — passes
- [x] `cargo check` — passes
- [x] Empirical: 1 `git worktree list --porcelain` subprocess per `wt
switch`

> _This was written by Claude Code on behalf of Maximilian Roos_

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants