Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(completion): overlap the git reads a Tab press waits on (#3664)
Maximilian Roosaba7bad089e4
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.mdindex 48907a2c8..d3c746949 100644--- a/benches/CLAUDE.md+++ b/benches/CLAUDE.md@@ -30,6 +30,9 @@ cargo bench --bench prune --features real-repo-benches prune_real_repo # rust s# Picker preview pre-compute (wt switch preview workload)cargo bench --bench picker_preview # all variantscargo bench --bench picker_preview warm # warm only++# Shell completion (COMPLETE=$SHELL wt -- wt switch <Tab>) — one variant, no filter+cargo bench --bench completion```## Fixtures and Benches@@ -44,9 +47,9 @@ it runs on.| Fixture (generator) | `wt-perf setup` handle | Bench group(s) ||---|---|---|| `RepoConfig::typical(N)` | `typical-N` | `skeleton`, `worktree_scaling` (list.rs); `first_output` (time_to_first_output.rs); `picker_preview`; `remove_e2e` |-| `RepoConfig::branches(N, M)` | `branches-N[-M]` | `completion_switch` (completion.rs) |+| `RepoConfig::branches(N, M)` | `branches-N[-M]` | — (branch-scaling investigation only) || `RepoConfig::many_divergent_branches()` | `divergent` | `divergent_branches` (list.rs) |-| `create_mixed_repo(W, B)` | `mixed-W-B` | `full` (list.rs) |+| `create_mixed_repo(W, B, R)` | `mixed-W-B[-R]` | `full` (list.rs); `completion_switch` (completion.rs) || `create_prune_repo(M, U)` | `prune-M-U` | `prune_e2e` (prune.rs) || `ensure_prune_real_repo(M, U)` | `prune-real[-M-U]` | `prune_real_repo` (prune.rs) || rust-lang/rust clone (`clone_rust_repo`) | — | `real_repo`, `real_repo_many_branches` (list.rs) |@@ -350,7 +353,8 @@ cargo run -p wt-perf -- setup typical-8# branches-N - N branches, 1 commit each# branches-N-M - N branches, M commits each# divergent - 200 branches × 20 commits (GH #461 scenario)-# mixed-W-B - W worktrees + B branches in varied states (the `full` fixture)+# mixed-W-B[-R] - W worktrees + B branches in varied states, plus R+# remote-tracking refs (the `full` and completion fixture)# prune-M-U - M squash-merged candidates + U two-sided-diverged# worktrees/branches (the `wt step prune` workload; see# benches/prune.rs)@@ -422,6 +426,28 @@ show — open the Chrome Trace JSON (`wt-perf timeline --chrome`, or `wt-perftrace` on an existing `trace.jsonl`) in <https://ui.perfetto.dev> orchrome://tracing.+**A traced run has no prewarm, so it is not the run users get.** At `-vv`,+`logging::init` opens the log sinks through `log_files::try_create`, which calls+`Repository::current()` and so resolves the git common dir. `Repository::prewarm`+treats a populated `GIT_COMMON_DIR_CACHE` as "prewarm already ran" and returns+without doing anything — so in every `-vv` run (and therefore every+`wt-perf timeline`), the rev-parse batch, the `git config --list -z` preload, and+the user-config preload never happen concurrently. Their work still gets done, one+serial on-demand fork at a time, which is what the trace shows.++The trace is still right about what ran; it is wrong about what production+overlaps. Two consequences when reading one:++- Don't conclude a phase is serial because the trace shows it serial. Read+ `prewarm` / `prewarm_rev_parse` / `prewarm_git_config` spans first: if they're+ absent, the trace is a no-prewarm run and the startup calls are ordered+ differently than in production.+- Don't measure a startup change by trace alone. Time the real binary+ (`hyperfine` on the shipped path) and, for a fork inventory that doesn't perturb+ the run, put a logging shim named `git` at the front of `PATH` — a two-line+ `sh` script that appends `"$*"` to a file and `exec`s the real git. That counts+ every spawn with no verbosity flag set.+### Performance questionsThree questions drive `wt list` performance work:diff --git a/benches/completion.rs b/benches/completion.rsindex f8420119b..66fbfecac 100644--- a/benches/completion.rs+++ b/benches/completion.rs@@ -1,6 +1,40 @@+//! Shell-completion latency (`COMPLETE=$SHELL wt -- wt switch <Tab>`).+//!+//! This is the one wt path a user waits on with their finger still on Tab, so+//! the number that matters is whole-process wall time. It runs the real binary+//! the way a shell does — the completion handler answers and returns before+//! `main` builds the rayon pool or parses a command, so nothing here shares+//! state with an ordinary `wt` invocation.+//!+//! **One benchmark, on the `mixed` fixture `full` already uses.** Completion+//! has no phases worth timing separately: it spawns, fills its caches on one+//! set of threads, scans refs and worktrees on another, prints, exits.+//! Splitting that into a variant per dimension re-measures the same startup+//! over a series of deliberately lopsided repos and still can't say which call+//! moved, because the calls within a wave overlap. Localizing a regression is a+//! trace's job here, exactly as it is for `full` — see "Analyzing a trace" in+//! benches/CLAUDE.md, and note that a `-vv` run has no prewarm and so is not+//! the run users get.+//!+//! `mixed-80-80-1400` is that one repo: 80 worktrees in four states, 80 more+//! branches forked across 200 commits of history, and 1400 remote-tracking+//! refs. It covers all three categories `BranchCompleter` distinguishes, puts+//! both candidate slow calls (`for-each-ref refs/remotes/` and `worktree list+//! --porcelain`) in the same process at a size where each is expensive, and+//! lands past the completer's 100-entry threshold — where the remote refs are+//! scanned and then discarded, as they are on a real long-lived clone.+//!+//! The remote-ref count is what this bench adds to the shared fixture; `full`+//! passes 0 and is unaffected.+//!+//! ```bash+//! cargo bench --bench completion+//! cargo run -p wt-perf -- setup mixed-80-80-1400 --path /tmp/clone # same repo, by hand+//! ```+use criterion::{Criterion, criterion_group, criterion_main};use std::path::Path;-use wt_perf::{RepoConfig, create_repo, run_and_check, wt_command};+use wt_perf::{create_mixed_repo, run_and_check, wt_command};fn run_completion(binary: &Path, repo_path: &Path, words: &[&str]) {let index = words.len().saturating_sub(1);@@ -18,20 +52,8 @@ fn bench_completion_switch(c: &mut Criterion) {let mut group = c.benchmark_group("completion_switch");let binary = Path::new(env!("CARGO_BIN_EXE_wt"));- // Without worktrees: all branches are candidates- group.bench_function("branches_only", |b| {- let config = RepoConfig::branches(50, 0);- let fixture = create_repo(&config);- b.iter(|| run_completion(binary, fixture.path(), &["wt", "switch", ""]));- });-- // With worktrees: filters out branches that already have worktrees- group.bench_function("with_worktrees", |b| {- let config = RepoConfig {- worktrees: 10,- ..RepoConfig::branches(50, 0)- };- let fixture = create_repo(&config);+ group.bench_function("mixed", |b| {+ let fixture = create_mixed_repo(80, 80, 1400);b.iter(|| run_completion(binary, fixture.path(), &["wt", "switch", ""]));});diff --git a/benches/list.rs b/benches/list.rsindex 45fd8dd16..ee3c790cc 100644--- a/benches/list.rs+++ b/benches/list.rs@@ -297,7 +297,7 @@ fn bench_full(c: &mut Criterion) {for cache in CacheState::WARM_AND_COLD {group.bench_function(cache.label(), |b| {- let fixture = create_mixed_repo(worktrees, branches);+ let fixture = create_mixed_repo(worktrees, branches, 0);run_benchmark(b,binary,diff --git a/src/completion.rs b/src/completion.rsindex bf653f5e9..c0af681f7 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -1,3 +1,34 @@+//! Shell completion (`COMPLETE=$SHELL wt -- <tokens>`).+//!+//! Every Tab press forks a whole `wt` process, and the user is waiting on it+//! with a finger still on the key — so this is the one path where wall-clock+//! latency is the feature. It is also the path with the least room to hide+//! work: there is no progressive rendering to paint behind, no cache to amortize+//! across invocations (the process exits, and no shell caches a dynamic+//! completion), and nothing the shell can show until the process is done.+//!+//! Two structural rules follow, both easy to undo by accident:+//!+//! - **Everything the completion needs is fetched concurrently.** The work is a+//! handful of independent git reads, each roughly one fork's latency, so+//! sequencing them costs their sum where the user waits for their max. The+//! process runs in two waves: [`Repository::prewarm`] fills the discovery,+//! git-config, and user-config caches on three threads, and then+//! `branches_for_completion` runs the ref and worktree scans on three more.+//! The second wave depends on the first only through `Repository::at`, which+//! needs the common dir the first wave resolved.+//! - **Nothing is scanned that cannot reach the user.** The completer decides+//! up front whether a remote-only branch could be offered from this argument+//! at all, and passes that down rather than filtering afterwards —+//! `refs/remotes/` is the most expensive read here, since a long-lived clone+//! carries far more remote-tracking refs than local branches.+//!+//! `main` returns here before it builds the rayon pool, which this path never+//! uses; see the call site. A change to any of this is measured against+//! `benches/completion.rs`, which runs one repo big enough in every dimension+//! to make the difference visible — and *not* against a `-vv` trace, which+//! silently disables prewarm (benches/CLAUDE.md, "Analyzing a trace").+use std::cell::RefCell;use std::ffi::{OsStr, OsString};use std::io::Write;@@ -65,6 +96,19 @@ pub(crate) fn maybe_handle_env_completion() -> bool {return true;}+ // Fill the git-discovery, git-config, and user-config caches on three+ // concurrent threads, exactly as `main` does before dispatching a command.+ // Completion answers and returns long before `main` reaches its own+ // `Repository::prewarm` call, so without this every one of those reads is+ // a separate fork taken serially, on the one path where the user is+ // waiting with a finger on Tab: `completion_command`'s alias injection+ // needs the configs, and the branch completers below need the discovery+ // caches. Placed after the registration-script return, which resolves no+ // repository at all, and after `suppress_warnings` above, since+ // `prewarm_user_config` loads `UserConfig` eagerly and its deprecation+ // warnings must not land above the user's prompt.+ Repository::prewarm();+// If the subcommand word matches a custom-subcommand binary, forward the// completion request to it (e.g., `wt sync --<tab>` → `wt-sync --<tab>`).// args[0] is the binary name ("wt"), args[1] is the subcommand ("sync").@@ -341,7 +385,15 @@ impl ValueCompleter for BranchCompleter {return Vec::new();}- let branches = match Repository::current().and_then(|repo| repo.branches_for_completion()) {+ // Whether a remote-only branch could reach the user from this argument+ // at all. It decides the scan as well as the filter: a completer that+ // answers "no" never runs `for-each-ref refs/remotes/`, which on a+ // fetched-into clone is the most expensive call on this path.+ let may_offer_remote_only = !self.exclude_remote_only && !self.worktree_only;++ let branches = match Repository::current()+ .and_then(|repo| repo.branches_for_completion(may_offer_remote_only))+ {Ok(b) => b,Err(_) => return Vec::new(),};@@ -350,16 +402,11 @@ impl ValueCompleter for BranchCompleter {return Vec::new();}- // If remote-only branches aren't already excluded, drop them when the total+ // Even where they're on offer, drop remote-only branches once the total// count is large. Shells like bash/zsh prompt "do you wish to see all N// possibilities?" which makes completion unusable in repos with many remotes.// Threshold of 100 aligns with bash's default `completion-query-items`.- let exclude_remote_only = self.exclude_remote_only- || (!self.worktree_only- && branches.len() > 100- && branches- .iter()- .any(|b| matches!(b.category, BranchCategory::Remote(_))));+ let exclude_remote_only = !may_offer_remote_only || branches.len() > 100;branches.into_iter()diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex 9efa6b004..aaf100f9f 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -249,7 +249,40 @@ impl Repository {////// For remote branches, returns the local name (e.g., "fix" not "origin/fix")/// since `git worktree add path fix` auto-creates a tracking branch.- pub fn branches_for_completion(&self) -> anyhow::Result<Vec<CompletionBranch>> {+ ///+ /// `include_remote_only` is the caller's answer to "could a remote-only+ /// branch reach the user from here?". A completer that can never offer one+ /// (`wt remove`, worktree-only arguments) passes `false` and the+ /// `refs/remotes/` scan — the most expensive of the three, since it reads a+ /// commit object per ref and a fetched-into clone has far more of those+ /// than local branches — never runs. Filtering the results afterwards+ /// instead would pay for the scan and then throw it away.+ pub fn branches_for_completion(+ &self,+ include_remote_only: bool,+ ) -> anyhow::Result<Vec<CompletionBranch>> {+ // The three scans are independent git calls that this function only+ // joins in memory, and completion is a process that does nothing else+ // — run in sequence the user waits for their sum, run concurrently for+ // their max. Best-effort, on the same contract as+ // `Repository::prewarm`: a thread that fails leaves its cache slot+ // empty, and the accessor below re-runs the call and surfaces the+ // error. `RepoCache`'s slots are separate thread-safe `OnceCell`s, so+ // the three fill independently.+ std::thread::scope(|scope| {+ scope.spawn(|| {+ let _ = self.list_worktrees();+ });+ scope.spawn(|| {+ let _ = self.local_branches();+ });+ if include_remote_only {+ scope.spawn(|| {+ let _ = self.remote_branches();+ });+ }+ });+let worktrees = self.list_worktrees()?;let worktree_branches: HashSet<String> = worktrees.iter()@@ -264,7 +297,12 @@ impl Repository {// (users should use the local one). Keeps the most recent timestamp// across remotes to preserve recency ordering.let mut branch_remotes: HashMap<String, (Vec<String>, i64)> = HashMap::new();- for remote in self.remote_branches()? {+ let remotes: &[RemoteBranch] = if include_remote_only {+ self.remote_branches()?+ } else {+ &[]+ };+ for remote in remotes {if local_names.contains(remote.local_name.as_str()) {continue;}@@ -283,7 +321,13 @@ impl Repository {(name, remotes, ts)}).collect();- remote_only.sort_by_key(|b| std::cmp::Reverse(b.2));+ // Recency first, then name. The name is not a cosmetic tiebreak: these+ // entries come out of a `HashMap`, whose iteration order varies per+ // process, and `sort_by_key` is stable — so on the timestamps that tie+ // (branches cut from one commit, a bulk import) sorting on recency+ // alone leaves the surviving order randomized, and the completion list+ // reshuffles between one Tab press and the next.+ remote_only.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.0.cmp(&b.0)));let mut result = Vec::with_capacity(locals.len() + remote_only.len() + worktrees.len());@@ -422,6 +466,68 @@ mod tests {assert_eq!(repo.default_branch_sha(), None);}+ /// Build `refs/remotes/origin/<name>` for each name, all at HEAD — so+ /// every one carries the same committer timestamp and the recency sort+ /// between them is a tie.+ fn add_remote_refs_at_head(test: &TestRepo, names: &[&str]) {+ let head = test.git_output(&["rev-parse", "HEAD"]);+ for name in names {+ test.run_git(&["update-ref", &format!("refs/remotes/origin/{name}"), &head]);+ }+ }++ #[test]+ fn branches_for_completion_omits_remote_only_when_not_requested() {+ // `include_remote_only` is what keeps a completer that can never+ // offer a remote-only branch (`wt remove`, worktree-only arguments)+ // from running the `refs/remotes/` scan at all. Filtering afterwards+ // would look the same from here but pay for the scan first, which on+ // a long-lived clone is the most expensive call on the path.+ let test = TestRepo::with_initial_commit();+ add_remote_refs_at_head(&test, &["only-on-remote"]);++ let repo = Repository::at(test.root_path()).unwrap();+ let with = repo.branches_for_completion(true).unwrap();+ assert!(+ with.iter()+ .any(|b| b.name == "only-on-remote"+ && matches!(b.category, BranchCategory::Remote(_))),+ "requested but absent: {with:?}",+ );++ // A separate Repository, so the first call's cached scan can't stand+ // in for the second's.+ let repo = Repository::at(test.root_path()).unwrap();+ let without = repo.branches_for_completion(false).unwrap();+ assert!(+ !without+ .iter()+ .any(|b| matches!(b.category, BranchCategory::Remote(_))),+ "not requested but present: {without:?}",+ );+ }++ #[test]+ fn branches_for_completion_orders_tied_remote_only_branches_by_name() {+ // Remote-only entries are collected through a `HashMap`, whose+ // iteration order differs per process, and the recency sort is+ // stable — so branches sharing a timestamp keep whatever random order+ // they were iterated in unless the sort breaks the tie itself. Left+ // unbroken, a user's completion list reshuffles between Tab presses.+ let test = TestRepo::with_initial_commit();+ add_remote_refs_at_head(&test, &["cherry", "apple", "banana"]);++ let repo = Repository::at(test.root_path()).unwrap();+ let remote_only: Vec<String> = repo+ .branches_for_completion(true)+ .unwrap()+ .into_iter()+ .filter(|b| matches!(b.category, BranchCategory::Remote(_)))+ .map(|b| b.name)+ .collect();+ assert_eq!(remote_only, vec!["apple", "banana", "cherry"]);+ }+#[test]fn branches_for_completion_includes_unborn_default_branch() {// Regression for #3094: on a fresh `git init -b main` with no@@ -433,7 +539,7 @@ mod tests {let test = TestRepo::new();let repo = Repository::at(test.root_path()).unwrap();- let branches = repo.branches_for_completion().unwrap();+ let branches = repo.branches_for_completion(true).unwrap();let names: Vec<&str> = branches.iter().map(|b| b.name.as_str()).collect();assert_eq!(names, vec!["main"], "completion candidates: {:?}", branches);assert!(@@ -460,7 +566,7 @@ mod tests {]);let repo = Repository::at(test.root_path()).unwrap();- let branches = repo.branches_for_completion().unwrap();+ let branches = repo.branches_for_completion(true).unwrap();let names: Vec<&str> = branches.iter().map(|b| b.name.as_str()).collect();assert!(names.contains(&"main") && names.contains(&"feature"),diff --git a/src/main.rs b/src/main.rsindex 930036670..e36f21ce1 100644--- a/src/main.rs+++ b/src/main.rs@@ -748,11 +748,7 @@ fn init_rayon_thread_pool() {.build_global();}-fn parse_cli() -> Option<Cli> {- if completion::maybe_handle_env_completion() {- return None;- }-+fn parse_cli() -> Cli {// Apply -C / --config before help handling so `wt -C other --help`// and `wt --config custom.toml step --help` resolve aliases against the// requested repo and user config (not the process cwd / default config).@@ -777,7 +773,7 @@ fn parse_cli() -> Option<Cli> {.unwrap_or_else(|e| {enhance_and_exit_error(e);});- Some(Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()))+ Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())}fn apply_global_options(@@ -1079,14 +1075,22 @@ fn main() {// wall-clock minus the sum of post-init spans.worktrunk::shell_exec::init_startup();+ // Shell completion answers and exits without running a command, and no+ // code it reaches uses rayon — so it returns before the pool below is+ // built rather than after. That pool is `available_parallelism() * 2`+ // OS threads (36 on an M-series Mac), spawned eagerly by `build_global`,+ // and a completion is the one wt invocation a user waits on with a+ // finger still on Tab.+ if completion::maybe_handle_env_completion() {+ return;+ }+init_rayon_thread_pool();// Tell crossterm to always emit ANSI sequencescrossterm::style::force_color_output(true);- let Some(cli) = parse_cli() else {- return;- };+ let cli = parse_cli();let Cli {directory,@@ -1098,7 +1102,7 @@ fn main() {} = cli;// `WORKTRUNK_VERBOSE` provides a baseline verbosity the `-v`/`-vv` flags// raise but never lower (`max`). It also drives shell completion, which- // exits in `parse_cli` before reaching here — see+ // answers and returns above, before `parse_cli` — see// `completion::maybe_handle_env_completion`.let verbose = verbose.max(logging::env_verbose_level());// Globals were already applied in `parse_cli` before help rendering;diff --git a/tests/helpers/wt-perf/src/lib.rs b/tests/helpers/wt-perf/src/lib.rsindex 42c7d8022..82dedce06 100644--- a/tests/helpers/wt-perf/src/lib.rs+++ b/tests/helpers/wt-perf/src/lib.rs@@ -160,8 +160,15 @@ impl RepoConfig {/// [`ensure_prune_real_repo`].)pub enum SetupConfig {Flat(RepoConfig),- Mixed { worktrees: usize, branches: usize },- Prune { merged: usize, unmerged: usize },+ Mixed {+ worktrees: usize,+ branches: usize,+ remote_refs: usize,+ },+ Prune {+ merged: usize,+ unmerged: usize,+ },}impl SetupConfig {@@ -175,8 +182,9 @@ impl SetupConfig {SetupConfig::Mixed {worktrees,branches,+ remote_refs,} => {- create_mixed_repo_at(*worktrees, *branches, base_path);+ create_mixed_repo_at(*worktrees, *branches, *remote_refs, base_path);(*worktrees, *branches)}SetupConfig::Prune { merged, unmerged } => {@@ -522,6 +530,73 @@ pub fn add_worktrees(config: &RepoConfig, repo_path: &Path) {}}+/// Create `count` remote-tracking refs under `refs/remotes/origin/`, on top of+/// the `origin/main` + `origin/HEAD` pair [`setup_fake_remote`] writes.+///+/// The refs are spread round-robin over the commits already on `main` rather+/// than all pointing at `HEAD`, which would leave `%(committerdate)` re-reading+/// one object and understate the scan. It does not reach one object per ref:+/// the round-robin can only spread over the history it has, so at+/// `create_mixed_repo`'s 200 commits a four-digit ref count lands ~7 refs on+/// each of ~200 distinct commits. Git parses a given object once and reuses it+/// for the rest of the `for-each-ref`, so the scan pays ~200 parses plus a+/// cheap iteration hit per ref, where a real long-lived clone — whose remote+/// tips are mostly distinct commits — would pay a parse per ref.+///+/// So this under-weights object reads relative to the clone it models, and+/// deliberately: closing the gap needs a history as deep as the ref count, and+/// `BASE_COMMITS` is shared with `full`, so deepening it would slow that+/// fixture and shift the repo `full` has been measured on for the sake of a+/// per-object parse this bench is not primarily about. The ref-count dimension+/// is what it exists to vary.+///+/// Timestamps are all `TEST_EPOCH` regardless — fixture commit dates are pinned+/// — so the sort is not what this measures.+///+/// Names are `remote-only-<i>`, which no fixture uses for a local branch, so+/// every one of them survives the "skip remotes shadowed by a local branch"+/// filter in `branches_for_completion` and reaches the candidate list.+///+/// One `update-ref --stdin` fork writes the whole batch; the per-ref+/// alternative costs a fork each and dominates fixture build time at the+/// four-digit counts this exists to model.+fn add_remote_refs(count: usize, repo_path: &Path) {+ if count == 0 {+ return;+ }++ let commits: Vec<String> = capture_git(repo_path, &["rev-list", "HEAD"])+ .lines()+ .map(str::to_string)+ .collect();+ assert!(+ !commits.is_empty(),+ "fixture has no commits to point refs at"+ );++ let mut stdin = String::new();+ for i in 0..count {+ let sha = &commits[i % commits.len()];+ stdin.push_str(&format!(+ "create refs/remotes/origin/remote-only-{i} {sha}\n"+ ));+ }++ let mut child = git_command()+ .args(["update-ref", "--stdin"])+ .current_dir(repo_path)+ .stdin(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ // Take the handle so it drops (closing the pipe) before the wait —+ // git reads to EOF, so holding it open here deadlocks.+ let mut pipe = child.stdin.take().unwrap();+ std::io::Write::write_all(&mut pipe, stdin.as_bytes()).unwrap();+ drop(pipe);+ let status = child.wait().unwrap();+ assert!(status.success(), "git update-ref --stdin failed: {status}");+}+/// Set up a fake remote for default branch detection.pub fn setup_fake_remote(repo_path: &Path) {let refs_dir = repo_path.join(".git/refs/remotes/origin");@@ -1032,14 +1107,14 @@ fn append_line(path: &Path, rel: &str, line: &str) {/// 2. diverged: a short own-commit chain forked from an older checkpoint/// while base advanced (deep two-sided divergence)/// 3. identical to the base tip (trees match — squash-merge shape)-pub fn create_mixed_repo(worktrees: usize, branches: usize) -> FixtureRepo {- FixtureRepo::create(|repo| create_mixed_repo_at(worktrees, branches, repo))+pub fn create_mixed_repo(worktrees: usize, branches: usize, remote_refs: usize) -> FixtureRepo {+ FixtureRepo::create(|repo| create_mixed_repo_at(worktrees, branches, remote_refs, repo))}/// [`create_mixed_repo`] at a caller-chosen path (used by `wt-perf setup/// mixed-W-B`). The main worktree is created at `repo`; linked worktrees are/// siblings.-fn create_mixed_repo_at(worktrees: usize, branches: usize, repo: &Path) {+fn create_mixed_repo_at(worktrees: usize, branches: usize, remote_refs: usize, repo: &Path) {const FILES: usize = 50;// Deep enough that fork points spread across history give the// `%(ahead-behind)` walk real commits to traverse (GH #461 shape), while@@ -1108,6 +1183,7 @@ fn create_mixed_repo_at(worktrees: usize, branches: usize, repo: &Path) {// loose refs and uncommitted state — realistic, and keeps gc away from the// dirty indexes below).setup_fake_remote(&repo);+ add_remote_refs(remote_refs, &repo);run_git(&repo, &["gc", "-q"]);// Linked worktrees are siblings named `<repo-dir>.<branch>` (worktrunk@@ -1467,7 +1543,7 @@ pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {/// - `branches-N` - N branches with 1 commit each/// - `branches-N-M` - N branches with M commits each/// - `divergent` - many divergent branches (GH #461)-/// - `mixed-W-B` - W worktrees + B branches in varied states+/// - `mixed-W-B[-R]` - W worktrees + B branches in varied states, plus R remote-tracking refs/// - `prune-M-U` - M squash-merged candidates + U unmerged (prune workload)/// - `picker-test` - config for wt switch interactive picker testingpub fn parse_config(s: &str) -> Option<SetupConfig> {@@ -1485,11 +1561,20 @@ pub fn parse_config(s: &str) -> Option<SetupConfig> {return Some(SetupConfig::Flat(config));}- if let Some((worktrees, branches)) = parse_pair(s, "mixed-") {- return Some(SetupConfig::Mixed {- worktrees,- branches,- });+ if let Some(rest) = s.strip_prefix("mixed-") {+ return match rest.split('-').collect::<Vec<_>>().as_slice() {+ [w, b] => Some(SetupConfig::Mixed {+ worktrees: w.parse().ok()?,+ branches: b.parse().ok()?,+ remote_refs: 0,+ }),+ [w, b, r] => Some(SetupConfig::Mixed {+ worktrees: w.parse().ok()?,+ branches: b.parse().ok()?,+ remote_refs: r.parse().ok()?,+ }),+ _ => None,+ };}if let Some((merged, unmerged)) = parse_pair(s, "prune-") {@@ -1622,7 +1707,7 @@ mod tests {// Two full rotations of each 4-state cycle, so a state that collapsed// into its neighbour fails on both of its indices rather than one.const N: usize = 8;- let fixture = create_mixed_repo(N, N);+ let fixture = create_mixed_repo(N, N, 0);let repo = fixture.path().to_path_buf();let main = capture_git(&repo, &["rev-parse", "main"]);@@ -1872,13 +1957,13 @@ mod tests {// The two dimensions share no state, so covering each zero once spans// the contract — a both-zero repo just skips both loops.- let fixture = create_mixed_repo(3, 0);+ let fixture = create_mixed_repo(3, 0, 0);let repo = fixture.path().to_path_buf();assert_eq!(refs(&repo, "refs/heads/br-*"), 0, "no branchless branches");assert_eq!(refs(&repo, "refs/heads/wt-*"), 3);assert_eq!(linked(&repo), 3);- let fixture = create_mixed_repo(0, 3);+ let fixture = create_mixed_repo(0, 3, 0);let repo = fixture.path().to_path_buf();assert_eq!(refs(&repo, "refs/heads/br-*"), 3);assert_eq!(refs(&repo, "refs/heads/wt-*"), 0, "no worktree branches");