Skip to content

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

Canonicalize benchmark fixtures and variants (#3761)

Maximilian Roos00ab0ffa2642
diff --git a/.github/workflows/benchmarks.yaml b/.github/workflows/benchmarks.yaml
index 33701fd8e..baec06ab4 100644
--- a/.github/workflows/benchmarks.yaml
+++ b/.github/workflows/benchmarks.yaml
@@ -56,13 +56,13 @@ jobs:
with:
version: '0.114.1'
- - name: πŸ’° Large-repository fixture cache
+ - name: πŸ’° Imported fixture cache
uses: actions/cache@v6
with:
# The fixture file pins the corpus revision. Including its hash keeps
# a prior corpus out of the cache after either constant changes.
path: target/wt-perf/bench-repos
- key: bench-repos-large-repository-${{ runner.os }}-${{ hashFiles('benches/large-repository-fixture') }}
+ key: bench-repos-imported-${{ runner.os }}-${{ hashFiles('benches/imported-fixture') }}
- name: πŸ“Š Run benchmarks
run: cargo bench
diff --git a/Cargo.toml b/Cargo.toml
index 02aac882a..e153be58a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -100,7 +100,7 @@ syntax-highlighting = ["dep:tree-sitter-bash", "dep:tree-sitter-highlight"]
# Includes: shell wrapper tests, PTY-based approval prompts, TUI select, progressive rendering
shell-integration-tests = []
# Enable benchmarks whose fixture is too large for hosted CI: the
-# large-repository prune fixture (~15 GiB of linked worktrees, cached under
+# large-repository prune fixture (multi-gigabyte linked worktrees, cached under
# target/wt-perf/bench-repos). The daily benchmarks workflow runs plain `cargo bench`
# and must never build it; opt in locally with
# `cargo bench --bench prune --features large-repository-benches`.
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index 9de3ae71d..4c92d6ac7 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -7,13 +7,13 @@ See `list.rs` and `time_to_first_output.rs` headers for benchmark groups and run
Criterion's CLI takes a positional `FILTER` (substring inclusion) and `--exact`. There's no `--skip`; pick a filter that *includes* what you want instead.
```bash
-# Fast iteration (one synthetic group, warm cache only)
+# Fast iteration (one generated group, warm cache only)
cargo bench --bench list skeleton/warm
# Run specific group (all variants)
cargo bench --bench list full
-# GH #461 scenario (50 branches at varying depths in the large-repository corpus)
+# GH #461 scenario (50 branches at varying depths in the imported corpus)
cargo bench --bench list large_repository
# All list benchmarks (~1 hour)
@@ -24,8 +24,8 @@ cargo bench --bench time_to_first_output # all commands
cargo bench --bench time_to_first_output remove # just remove
# wt step prune (scan + removal on the squash-merged fixture)
-cargo bench --bench prune # synthetic variants
-cargo bench --bench prune --features large-repository-benches prune_large_repository # large-repository scale (~15 GiB temporary fixture)
+cargo bench --bench prune # generated variants
+cargo bench --bench prune --features large-repository-benches prune_large_repository # multi-gigabyte temporary fixture
# Picker preview pre-compute (wt switch preview workload)
cargo bench --bench picker_preview # all variants
@@ -37,33 +37,32 @@ cargo bench --bench completion
## Fixtures and Benches
-Bench groups name measurements; fixture recipes are implementation details
-that construct repository states. Preserve the state dimensions needed for
-coverage and fidelity, not historical recipes or the ability to recreate an
-old setup. Consolidate or rename recipes whenever the resulting benchmarks
-still test the same performance claims. Prefer a few heterogeneous canonical
-states: a property does not need its own recipe merely because one benchmark
-studies it. Split a fixture only when a controlled contrast, destructive
-precondition, or disproportionate setup cost requires a different state. One
-recipe can feed several groups (`FixtureRecipe::Typical` backs five); for
-example, `full` is a benchmark and `Mixed` is its repository state.
-
-| Fixture recipe | `wt-perf setup` | Bench group(s) |
+Bench groups name measurements; fixture recipes name corpus provenance. Both
+bases produce ordinary Git repositories: `Generated` builds the corpus locally,
+while `Imported` copies a pinned upstream corpus. Preserve the state dimensions
+needed for coverage and fidelity, not historical recipes or the ability to
+recreate an old setup. A property does not get its own fixture identity merely
+because one benchmark studies it.
+Worktree, branch, and remote-ref counts are controlled population parameters;
+prune candidates are an overlay. Add another base only when the corpus itself
+cannot serve one of these roles.
+
+| Canonical base | `wt-perf setup` | Bench group(s) |
|---|---|---|
-| `Typical { total_worktrees: N }` | `setup typical N --path <path>` | `skeleton`, `worktree_scaling` (list.rs); `first_output` (time_to_first_output.rs); `picker_preview`; `remove_e2e` |
-| `Minimal { branchless_branches: B, linked_worktrees: W }` | `setup minimal B W --path <path>` | `dispatch` (alias.rs) |
-| `SyntheticDivergence` | `setup synthetic-divergence --path <path>` | `divergent_branches` (list.rs) |
-| `LargeRepository` | `setup large-repository --path <path>` | `large_repository` (list.rs) |
-| `Mixed { linked_worktrees: W, branchless_branches: B, remote_tracking_refs: R }` | `setup mixed W B R --path <path>` | `full` (list.rs); `completion_switch` (completion.rs) |
-| `Prune { candidate_pairs: M, backdrop_pairs: U }` | `setup prune M U --path <path>` | `prune_e2e` (prune.rs) |
-| `LargeRepositoryPrune { candidate_pairs: M, backdrop_pairs: U }` | `setup large-repository-prune M U --path <path>` | `prune_large_repository` (prune.rs) |
-
-`total_worktrees` includes the primary worktree. `linked_worktrees` excludes it.
-`branchless_branches` have no linked worktree. `remote_tracking_refs` excludes
-the `origin/main` and `origin/HEAD` pair every synthetic fixture has. Each prune
-count is a pair: one linked worktree and one branchless branch.
-The canonical large-repository fixture has eight worktrees and fifty branches
-spread across its most recent 5,000 commits.
+| `Generated { linked_worktrees: W, branchless_branches: B, remote_tracking_refs: R }` | `setup generated W B R --path <path>` | all generated benchmarks |
+| `Imported` | `setup imported --path <path>` | `large_repository` and `prune_large_repository` |
+
+`linked_worktrees` excludes the primary worktree. `branchless_branches` have
+no linked worktree. `remote_tracking_refs` excludes the `origin/main` and
+`origin/HEAD` pair every generated fixture has. The generated defaults are 7,
+50, and 0 respectively, giving ordinary benchmarks eight total worktrees plus
+branches spread across its history. The imported base always has the same
+eight total worktrees and fifty history-spread branches.
+
+Add prune state with `--prune-candidates M --prune-backdrop U`. Each count is
+a pair: one linked worktree and one branchless branch. The benchmark catalog
+applies it to generated and imported fixtures. This is an overlay on the
+canonical base, not a separate fixture recipe.
Every benchmark recipe returns `FixtureRepo`, the owner of the temporary root
plus the canonical primary/linked-worktree paths. Repo-bound benchmark
@@ -71,18 +70,18 @@ subprocesses start through `wt_command`, and warm/cold matrices use
`CacheState::WARM_AND_COLD`; keep lifecycle, environment isolation, and cache
labels in those shared APIs.
-## Large-repository corpus
+## Imported corpus
-`benches/large-repository-fixture` pins the corpus and commit.
+`benches/imported-fixture` pins the corpus and commit.
The first matching acquisition clones that revision; later runs reuse the
-revision-keyed source under `target/wt-perf/bench-repos/large-repository/`.
+revision-keyed source under `target/wt-perf/bench-repos/imported/`.
Source construction is locked across processes, built in a temporary sibling,
validated, then atomically renamed into place. Mutable benchmark fixtures are
always fresh and have no shared lock or repair state.
## Faster Iteration
-Criterion has no exclusion flag β€” narrow the run by picking a substring that matches only the variants you want. Benchmark IDs look like `<group>/<label>/<param>`, e.g. `skeleton/cold/4`, `worktree_scaling/warm/8`, `full/cold`, `large_repository/branches/warm`.
+Criterion has no exclusion flag β€” narrow the run by picking a substring that matches only the variants you want. Benchmark IDs look like `<group>/<label>/<param>`, e.g. `skeleton/cold/1`, `worktree_scaling/warm/8`, `full/cold`, `large_repository/branches/warm`.
**Pattern matching (positional `FILTER`):**
```bash
@@ -93,7 +92,7 @@ cargo bench --bench list full # Both cache states of the combined
cargo bench --bench list -- --exact full/cold # One exact ID
```
-To skip the slow large-repository and divergent groups, target the synthetic groups directly: `cargo bench --bench list skeleton`, `cargo bench --bench list worktree_scaling`, or `cargo bench --bench list full`. Run them sequentially if you want more than one.
+To skip the slow large-repository and divergent groups, target `skeleton`, `worktree_scaling`, or `full`. Run them sequentially if you want more than one.
The `full` group is the place to start when `wt list` regresses on a real mix of worktrees and branches: the cold/warm split says whether the cost is the persistent-cache fill (cold) or the per-process re-fork (warm). A `full` wall time can't be split by side (the git subprocesses overlap on the rayon pool), so to localize a regression, trace one invocation and read the profile's BY CONTEXT table ("Analyzing a trace" below); `worktree_scaling` and `divergent_branches` track the worktree side and branch side respectively at criterion cadence.
@@ -136,8 +135,8 @@ subcommand which populates these caches. Run ordinary warm/cold variants through
`wt_perf::bench_wt`, the one home of the shared strategy. Destructive variants
use `iter_custom`: each iteration builds a fresh fixture before starting the
timer, measures only the command, and checks the postcondition before returning
-the accumulated duration. `remove_e2e` prewarms its fresh fixture through the
-same integration probes to preserve its historical cache-warm scenario;
+the accumulated duration. `remove_e2e` uses warm/cold no-hooks neighbors for
+cache cost and a warm with-hooks neighbor for hook cost;
`prune_e2e/live` clears probe caches to preserve its probe-cold scenario.
`invalidate_caches_auto` clears:
@@ -146,7 +145,7 @@ same integration probes to preserve its historical cache-warm scenario;
- `.git/wt/cache/` (all sha_cache kinds + ci-status + summaries)
- `worktrunk.default-branch` (git config)
-`.git/packed-refs` is deliberately preserved: flat fixture setup runs `git gc`
+`.git/packed-refs` is deliberately preserved: fixture setup runs `git gc`
at the end, which packs every loose ref into `packed-refs`
and prunes the loose copies. Deleting that file post-gc leaves the repo with
no resolvable refs, so any bench that resolves a branch (e.g. the `with_vars`
@@ -174,30 +173,28 @@ stays warm.
| `wt switch` (picker) | Yes | Preview pre-compute writes `picker-preview/{log,branch-diff,upstream-diff}-…` entries. Exercised under `WORKTRUNK_PREVIEW_BENCH=1` / `WORKTRUNK_PICKER_DRY_RUN=1`. |
| `wt` (completion via `COMPLETE=$SHELL`) | No | Only `for-each-ref` + worktree list. |
-Default-branch cache contribution is ~17ms per iteration on a typical-8 synthetic repo
-(measured: 166ms with default-branch cached β†’ 183ms fully cold). Small enough that
-clearing it as part of the full invalidation is simpler than introducing a "warm
-default-branch" bench mode. (`invalidate_probe_caches` leaves it warm, like
-everything else outside `.git/wt/cache/`.)
+Clearing the default-branch cache as part of full invalidation is simpler than
+introducing a separate "warm default branch" mode.
+`invalidate_probe_caches` leaves it warm, like everything else outside
+`.git/wt/cache/`.
**Bench fixtures don't exercise the wire path.** `setup_fake_remote` writes
`refs/remotes/origin/HEAD` directly into every repo, so a cold-cache iteration
-falls through to the local `<r>/HEAD` lookup (~17 ms above), never to
-`git ls-remote` (100 ms–2 s in the wild). The cold cost we benchmark is the
-*configured-remote* cold cost, not the *fresh-clone* cold cost. A
+falls through to the local `<r>/HEAD` lookup, never to `git ls-remote`. The
+cold cost we benchmark is the *configured-remote* cold cost, not the
+*fresh-clone* cold cost. A
`cold_no_remote` mode (extending `invalidate_caches_auto` to also wipe
`refs/remotes/origin/HEAD`) would close the gap if the wire-path cost is
worth measuring at CI cadence.
-## Expected Performance
-
-**Modest repos** (500 commits, 100 files):
-- Cold cache penalty: ~5-16% slower
-- Scaling: Linear with worktree count
+## Expected relationships
-**Large repositories** (current corpus: rust-lang/rust):
-- Cold cache penalty: ~4x slower for single worktree
-- Scaling: Warm cache shows superlinear degradation, cold cache scales better
+- The 1- and 8-worktree rows track the endpoint cost of adding linked
+ worktrees under both cache modes.
+- Cold rows should be slower than their warm neighbors because they rebuild
+ the persistent caches named above.
+- Large-repository rows amplify history-walk and working-tree costs that generated
+ content cannot model faithfully.
## Recording `wt remove` / `wt step prune` staging
@@ -205,46 +202,38 @@ The removal commands interleave per-target work with parallel scans and
detached background processes; a single e2e number hides which phase moved.
Record them in two layers:
-**Criterion cadence** β€” `benches/remove.rs` and `benches/prune.rs`. Expected
-numbers on an M-series Mac (`Prune { candidate_pairs: 4, backdrop_pairs: 8 }`:
-4 squash-merged worktrees and 4 squash-merged branches as candidates, plus 8
-two-sided-diverged worktrees and 8 branches as backdrop, over 200 commits and
-100 files; `prune_large_repository` uses the pinned large-repository corpus
-with 12 candidate pairs and 24 backdrop pairs, i.e. 36 linked worktrees.
-The source clone is cached, but the mutable ~15 GiB fixture is built fresh for
-the benchmark process and removed when it exits. That group is opt-in β€”
-`cargo bench --bench prune --features large-repository-benches prune_large_repository` β€”
-because its ~15 GiB fixture must never build on a hosted CI runner):
-
-| Variant | Expected | What it measures |
-|---------|----------|------------------|
-| `prune_e2e/dry_run_probe_cold` | ~150 ms | full parallel scan, probes re-run (`.git/wt/cache/` cleared; git's own caches stay warm β€” the "first prune after fetching main" shape) |
-| `prune_e2e/dry_run_warm` | ~60 ms | steady-state re-scan, probes hit sha_cache |
-| `prune_e2e/live` | ~400 ms | probe-cold scan + parallel removal of the 8 candidates (worktree candidates ~145 ms each β€” mostly the fsmonitor-daemon stop β€” branch-only ~50 ms, concurrent on the removal worker pool under the scan lock's read side, reusing scan-time plans) |
-| `prune_large_repository/dry_run_warm` | ~0.25–0.8 s | steady-state scan of 72 items (36 worktrees + 36 branches) at 331k-commit scale |
-| `prune_large_repository/dry_run_probe_cold` | ~0.6–1 s | the same 72-item scan with probes re-running at real cost (statuses stay stat-warm) |
-| `first_output/remove` | ~86 ms | single-target validation up to first output (`benches/time_to_first_output.rs`) |
+**Criterion cadence** β€” `benches/remove.rs` and `benches/prune.rs`. The
+generated prune overlay adds 4 squash-merged worktrees and 4 squash-merged
+branches as candidates, plus 8 two-sided-diverged worktrees and 8 branches as
+backdrop. `prune_large_repository` layers 12 candidate pairs and 24 backdrop pairs
+onto the canonical imported base. Its source clone is cached, but the mutable
+multi-gigabyte fixture is built fresh for the benchmark process and removed
+when it exits. That group is opt-in via `--features large-repository-benches` and
+must never build on a hosted CI runner.
+
+| Variant | What it measures |
+|---------|------------------|
+| `prune_e2e/dry_run_probe_cold` | full parallel scan with `.git/wt/cache/` cleared; git's own caches stay warm, matching the first prune after fetching the default branch |
+| `prune_e2e/dry_run_warm` | steady-state re-scan with integration probes served from sha_cache |
+| `prune_e2e/dry_run_cold` | first scan with worktrunk caches, the default-branch cache, and git's commit graph cleared |
+| `prune_e2e/live` | probe-cold scan plus parallel removal of the 8 candidates |
+| `prune_large_repository/dry_run_warm` | steady-state scan at large-repository history and working-tree scale |
+| `prune_large_repository/dry_run_probe_cold` | the same scan with integration probes rerun; statuses stay stat-warm |
+| `remove_e2e/{warm,cold}/no_hooks` | full removal with and without persistent caches |
+| `remove_e2e/warm/with_hooks` | warm-cache neighbor isolating hook approval and spawning |
+| `first_output/remove` | single-target validation up to first output (`benches/time_to_first_output.rs`) |
Full-cold and live at large-repository scale are **one-shot timelines, not
criterion groups**. Full-cold adds commit-graph rebuilding; live consumes the
-candidates. The live one-shot on the large-repository fixture is:
-
-- **live ~0.6 s wall** β€” all 24 removals run concurrently on the removal
- worker pool inside the `prune-scan` window (read side of the scan lock):
- the 12 worktree candidates ~240–290 ms each, branch-only ~100–135 ms.
- Contention inflates the per-span numbers β€” run serially, a worktree
- candidate's chain is ~155–210 ms (fsmonitor-served status ~20 ms, daemon
- stop ~57 ms, metadata prune ~11 ms, fresh ref snapshot ~40 ms, CAS delete
- ~7 ms) β€” but the wall collapses to the scan plus the slowest straggler.
- When candidate branches are packed (post-`gc`), the CAS deletes serialize
- on `packed-refs.lock`, putting a floor under the branch-deletion tail
+candidates. Live removals run concurrently inside the `prune-scan` window,
+while packed candidate refs may serialize briefly on `packed-refs.lock`.
An actual first checkout can be slower because every worktree status is
stat-cold. The cache helpers preserve indexes because removing one changes
staged state; use a fresh fixture when investigating checkout-cold status.
-The synthetic fixture can't show it β€” its statuses are milliseconds β€” so
-scale-sensitive changes need a one-shot on a fresh large-repository
-fixture (or `wt-perf timeline -- -C <repo> step prune --dry-run` on a real
+The generated fixture can't show it β€” its statuses are milliseconds β€” so
+scale-sensitive changes need a one-shot on a fresh imported fixture (or
+`wt-perf timeline -- -C <repo> step prune --dry-run` on a real
repository) alongside the criterion cadence. All large-repository numbers are
I/O-bound and move with ambient machine load (sibling builds, Spotlight):
treat them as shape, not thresholds, and compare Criterion verdicts with
@@ -268,23 +257,23 @@ metadata-pruning β€” `removal_needs_write` in `src/commands/step/prune.rs`) also
wait for every in-flight check and removal to drain first.
```bash
-cargo run -p wt-perf -- setup prune 4 8 --path /tmp/prune-repo
+cargo run -p wt-perf -- setup generated 0 0 --prune-candidates 4 --prune-backdrop 8 --path target/wt-prune-generated
# A freshly built fixture is already probe-cold (empty sha_cache).
-cargo run -p wt-perf -- timeline -- -C /tmp/prune-repo step prune --dry-run --min-age 0s
-cargo run -p wt-perf -- timeline -- -C /tmp/prune-repo step prune --min-age 0s
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --dry-run --min-age 0s
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --min-age 0s
```
**Live prune at large-repository scale is a one-shot timeline, not a criterion group** β€”
-each live run consumes the candidates, and constructing the ~15 GiB fixture
+each live run consumes the candidates, and constructing the multi-gigabyte fixture
costs minutes. Give setup a new explicit path; it refuses to overwrite an
existing destination. The pinned source clone is reused, while the mutable
fixture has no cache state to validate or repair. The probe-cold timeline keeps
git metadata warm:
```bash
-cargo run -p wt-perf -- setup large-repository-prune 12 24 --path /tmp/prune-rust
-cargo run -p wt-perf -- timeline -- -C /tmp/prune-rust step prune --min-age 0s
-# For another run, remove /tmp/prune-rust explicitly or choose a new path.
+cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-imported step prune --min-age 0s
+# For another run, remove target/wt-prune-imported explicitly or choose a new path.
```
**The `wt remove` exit-delay is machine-dependent and invisible to benches.**
@@ -302,15 +291,15 @@ count.
## Output Locations
-Ephemeral synthetic fixtures use the system temporary directory. Manual
+Ephemeral generated fixtures use the system temporary directory. Manual
`wt-perf setup` fixtures live at the explicit `--path` and are never
-overwritten. The revision-keyed large-repository source and temporary
-large-prune runs live under `target/wt-perf/bench-repos/`; that directory is
+overwritten. The revision-keyed imported source and temporary
+imported runs live under `target/wt-perf/bench-repos/`; that directory is
per-worktree and reaped by `cargo clean`.
- Results: `target/criterion/`
-- Cached corpus source: `target/wt-perf/bench-repos/large-repository/source-<revision>/`
-- Temporary large-prune runs: `target/wt-perf/bench-repos/large-repository/runs/`
+- Cached corpus source: `target/wt-perf/bench-repos/imported/source-<revision>/`
+- Temporary imported runs: `target/wt-perf/bench-repos/imported/runs/`
- HTML reports: `target/criterion/*/report/index.html`
## Performance Investigation with wt-perf
@@ -320,15 +309,15 @@ Use `wt-perf` to set up benchmark repos and generate Chrome Trace Format for vis
### Setting up benchmark repos
```bash
-# Set up a repo with 8 worktrees. The destination must not exist.
-cargo run -p wt-perf -- setup typical 8 --path /tmp/wt-typical-8
+# Set up the default generated repo: 8 total worktrees and 50 branches.
+cargo run -p wt-perf -- setup generated --path target/wt-generated
# `wt-perf setup --help` lists every recipe and its semantic count names.
# Reproduce the completion fixture, including its remote-tracking-ref population:
-cargo run -p wt-perf -- setup mixed 80 80 1400 --path /tmp/wt-mixed
+cargo run -p wt-perf -- setup generated 24 120 1400 --path target/wt-generated-completion
-# Build a fresh large-repository prune fixture from the cached pinned source:
-cargo run -p wt-perf -- setup large-repository-prune 12 24 --path /tmp/prune-rust
+# Build a fresh imported prune fixture from the cached pinned source:
+cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
```
### Generating traces
@@ -343,7 +332,7 @@ Perfetto/chrome://tracing. `--cold` invalidates caches first.
cargo run -p wt-perf -- timeline -- list --progressive
# Cold-cache run (invalidates the traced repo β€” the `-C` arg, else cwd)
-cargo run -p wt-perf -- timeline --cold -- -C target/wt-perf/typical-8 list --progressive
+cargo run -p wt-perf -- timeline --cold -- -C target/wt-generated list --progressive
# Chrome Trace Format JSON for Perfetto
cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
@@ -426,24 +415,24 @@ Three questions drive `wt list` performance work:
### Generating traces from benchmark repos
```bash
-# Trace the canonical large-repository fixture
-cargo run -p wt-perf -- setup large-repository --path /tmp/wt-history-spread
-cargo run --release -q -- -vv -C /tmp/wt-history-spread list --progressive --branches
-cargo run -p wt-perf -- trace /tmp/wt-history-spread/.git/wt/logs/trace.jsonl > large-repository-trace.json
+# Trace the canonical imported fixture
+cargo run -p wt-perf -- setup imported --path target/wt-imported
+cargo run --release -q -- -vv -C target/wt-imported list --progressive --branches
+cargo run -p wt-perf -- trace target/wt-imported/.git/wt/logs/trace.jsonl > imported-trace.json
```
## Key Performance Insights
**`git for-each-ref %(ahead-behind:BASE)` is O(commits), not O(refs)**
-This command walks the commit graph to compute divergence. On rust-lang/rust:
-- Takes ~2s regardless of how many refs are queried
-- Its cost is driven primarily by history depth, not the number of rendered rows
+This command walks the commit graph to compute divergence. Its cost on the
+imported corpus is driven primarily by history depth, not the number of
+rendered rows.
**Branch-row costs** (rust-lang/rust with 50 branch-only rows):
-- First run (cold persistent cache): ~15-18s (expensive merge-base/merge-tree per branch)
-- Subsequent runs (warm persistent cache): ~2-3s (cache hits on merge-tree / integration probes / diff stats / ancestry)
-- Default rows only: ~600ms (the same ref capture, without branch-only integration and rendering tasks)
+- Cold rows pay merge-base/merge-tree work per branch.
+- Warm rows reuse merge-tree, integration-probe, diff-stat, and ancestry entries.
+- Default rows still capture refs but skip branch-only integration and rendering tasks.
The persistent SHA-keyed cache (`.git/wt/cache/`) amortizes the first-run cost across
subsequent invocations. Cache entries are eternally valid since they're keyed on commit
diff --git a/benches/alias.rs b/benches/alias.rs
index 43410f7ea..6fd1b43c3 100644
--- a/benches/alias.rs
+++ b/benches/alias.rs
@@ -6,27 +6,16 @@
// dramatically slower than the equivalent subcommand; these benchmarks give
// that cost a regression-free measurement harness.
//
-// One group (`dispatch`), nine variants:
+// One group (`dispatch`), five variants:
// - wt_version: `wt --version` startup floor (no repo discovery)
-// - warm/1, warm/100, cold/1, cold/100: stub alias at 1 and 100 worktrees,
-// warm and cold caches. Each worktree has its own branch, so 100
-// worktrees β‰ˆ 101 branches β€” this doubles as the regression guard for
-// the O(1) upstream lookup from 4f9bd575a. The cold/100 variant is
-// where a regression to the pre-fix bulk `for-each-ref` would hurt
-// most (packed-refs scan dominates).
-// - with_vars/{warm,cold}/{1,100}: same axes, but the alias body
-// references several template vars that drive expensive paths inside
-// `build_hook_context` (rev-parse for `commit`, `default_branch`
-// detection, `primary_worktree` lookup, upstream lookup). Pairs with
-// stub to bracket the dispatch curve once a future filter scopes
-// context build to referenced vars only β€” until then with_vars tracks
-// stub within noise, since context build is unconditional.
+// - stub/1, stub/100: cache-independent alias at the population endpoints.
+// - with_vars/{warm,cold}/100: neighbors that add rev-parse, default-branch
+// detection, and primary worktree lookup, then isolate their cache cost.
//
// Run examples (Criterion takes a positional substring FILTER; no --skip):
// cargo bench --bench alias # All variants
-// cargo bench --bench alias warm # Warm only (incl. with_vars/warm)
-// cargo bench --bench alias dispatch/warm # Stub-warm only (excludes with_vars)
-// cargo bench --bench alias dispatch/cold # Stub-cold only (excludes with_vars)
+// cargo bench --bench alias stub # Population endpoints
+// cargo bench --bench alias with_vars # Cache pair
// cargo bench --bench alias -- --sample-size 10 # Fast iteration
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
@@ -37,20 +26,17 @@ use wt_perf::{
CacheState, FixtureRecipe, bench_wt, run_and_check, standard_benchmark_profile, wt_command,
};
-/// Alias body is a shell builtin so the wall-clock is dominated by the
-/// parent's dispatch β€” not by running a real subcommand.
-const STUB_CONFIG: &str = "[aliases]\nstub = \": fixed fixed fixed fixed fixed fixed\"\n";
+const LARGE_WORKTREE_COUNT: usize = 100;
-/// Alias body references vars that drive the expensive paths in
-/// `build_hook_context`: `commit` / `short_commit` (`rev-parse <branch>`
-/// fork), `default_branch` (cold detection), `primary_worktree_path`
-/// (lookup). `branch` and `worktree_path` are nearly free but kept so a
-/// future filter sees them as "referenced". `upstream` is omitted because
-/// fixture branches have no configured upstream β€” adding one would change
-/// what the stub variant measures and break label continuity. Both aliases
-/// use the same no-output builtin and argument count.
-const WITH_VARS_CONFIG: &str = r#"[aliases]
-with_vars = ": {{ branch }} {{ default_branch }} {{ commit }} {{ short_commit }} {{ primary_worktree_path }} {{ worktree_path }}"
+/// Both alias bodies are shell builtins so the wall-clock is dominated by the
+/// parent's dispatch rather than by a real subcommand. `with_vars` references
+/// variables that drive the expensive paths in
+/// `build_hook_context`: `commit` (rev-parse), `default_branch` (cold
+/// detection), and `primary_worktree_path` (lookup). The aliases have the same
+/// no-output builtin and argument count.
+const ALIAS_CONFIG: &str = r#"[aliases]
+stub = ": fixed fixed fixed"
+with_vars = ": {{ default_branch }} {{ commit }} {{ primary_worktree_path }}"
"#;
/// Build an isolated `wt` invocation pointed at a fixture user config.
@@ -76,44 +62,35 @@ fn bench_dispatch(c: &mut Criterion) {
});
});
- for total_worktrees in [1usize, 100] {
- let fixture = FixtureRecipe::Minimal {
- branchless_branches: 0,
+ for total_worktrees in [1, LARGE_WORKTREE_COUNT] {
+ let fixture = FixtureRecipe::Generated {
linked_worktrees: total_worktrees - 1,
+ branchless_branches: 0,
+ remote_tracking_refs: 0,
}
.create();
- let stub_config = fixture.root().join("stub-config.toml");
- let vars_config = fixture.root().join("with-vars-config.toml");
- std::fs::write(&stub_config, STUB_CONFIG).unwrap();
- std::fs::write(&vars_config, WITH_VARS_CONFIG).unwrap();
+ let user_config = fixture.root().join("config.toml");
+ std::fs::write(&user_config, ALIAS_CONFIG).unwrap();
- // Stub variants keep their label structure (`dispatch/{warm,cold}/{1,100}`)
- // so nightly bench history stays continuous. with_vars sits under a
- // `with_vars/` prefix as new siblings.
- for (id_prefix, alias_name, user_config) in [
- (None, "stub", &stub_config),
- (Some("with_vars"), "with_vars", &vars_config),
- ] {
- for cache in CacheState::WARM_AND_COLD {
- let cache_label = cache.label();
- let id = match id_prefix {
- Some(prefix) => format!("{prefix}/{cache_label}"),
- None => cache_label.to_string(),
- };
+ let mut cases = vec![("stub", "stub", CacheState::Warm)];
+ // Template-variable and cache effects need one shared population.
+ if total_worktrees == LARGE_WORKTREE_COUNT {
+ cases.extend([
+ ("with_vars/warm", "with_vars", CacheState::Warm),
+ ("with_vars/cold", "with_vars", CacheState::Cold),
+ ]);
+ }
- group.bench_with_input(
- BenchmarkId::new(id, total_worktrees),
- &total_worktrees,
- |b, _| {
- // Cold matters here: `build_hook_context` resolves the
- // default branch, which writes `worktrunk.default-branch`
- // and would otherwise be a cache hit on iters 2-N.
- bench_wt(b, fixture.path(), cache, || {
- wt_cmd(binary, fixture.path(), user_config, &[alias_name])
- });
- },
- );
- }
+ for (id, alias_name, cache) in cases {
+ group.bench_with_input(
+ BenchmarkId::new(id, total_worktrees),
+ &total_worktrees,
+ |b, _| {
+ bench_wt(b, fixture.path(), cache, || {
+ wt_cmd(binary, fixture.path(), &user_config, &[alias_name])
+ });
+ },
+ );
}
}
diff --git a/benches/completion.rs b/benches/completion.rs
index 4572c4159..59558ccfe 100644
--- a/benches/completion.rs
+++ b/benches/completion.rs
@@ -6,7 +6,7 @@
//! `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
+//! **One benchmark, on the generated 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
@@ -16,20 +16,20 @@
//! benches/CLAUDE.md, and note that a `-vv` run skips prewarm's rev-parse
//! batch and so is not quite 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 benchmark uses the same 24 linked worktrees and 120 branchless branches
+//! as `full`, plus 1400 remote-tracking refs. It covers all three categories
+//! `BranchCompleter` distinguishes and runs both candidate slow calls
+//! (`for-each-ref refs/remotes/` and `worktree list --porcelain`) in one
+//! process at a size where each is expensive. Its 145 local candidates also
+//! exceed the completer's 100-entry threshold, where remote refs are scanned
+//! and then discarded as they are on a 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
+//! cargo run -p wt-perf -- setup generated 24 120 1400 --path target/wt-generated-completion
//! ```
use criterion::{Criterion, criterion_group, criterion_main};
@@ -74,15 +74,17 @@ fn assert_completion_candidates(binary: &Path, repo_path: &Path, expected: &BTre
fn bench_completion_switch(c: &mut Criterion) {
let mut group = c.benchmark_group("completion_switch");
let binary = Path::new(env!("CARGO_BIN_EXE_wt"));
+ let (linked_worktrees, branchless_branches) = (24, 120);
- group.bench_function("mixed", |b| {
- let fixture = FixtureRecipe::Mixed {
- linked_worktrees: 80,
- branchless_branches: 80,
+ group.bench_function("full_surface", |b| {
+ let fixture = FixtureRecipe::Generated {
+ linked_worktrees,
+ branchless_branches,
remote_tracking_refs: 1400,
}
.create();
- assert_completion_candidates(binary, fixture.path(), &expected_branches(80, 80));
+ let expected = expected_branches(branchless_branches, linked_worktrees);
+ assert_completion_candidates(binary, fixture.path(), &expected);
b.iter(|| run_completion(binary, fixture.path(), &["wt", "switch", ""]));
});
diff --git a/benches/large-repository-fixture b/benches/imported-fixture
similarity index 100%
rename from benches/large-repository-fixture
rename to benches/imported-fixture
diff --git a/benches/list.rs b/benches/list.rs
index 870c01edb..fcc7fdcf1 100644
--- a/benches/list.rs
+++ b/benches/list.rs
@@ -1,13 +1,13 @@
// Benchmarks for `wt list` command
//
// Benchmark groups:
-// - skeleton: Time until the skeleton paints (1, 4, 8 worktrees; warm + cold)
-// - worktree_scaling: Full execution, worktree-count scaling (1, 4, 8 worktrees; warm + cold)
+// - skeleton: Time until the skeleton paints (1 and 8 worktrees; warm + cold)
+// - worktree_scaling: Full execution at 1 and 8 worktrees (warm + cold)
// - full: One combined full-surface fixture β€” many worktrees AND many branches
// in varied states, with branch divergence spread across history depth.
// The realistic "everything at once" workload (warm + cold).
-// - divergent_branches: 200 branches Γ— 20 commits / GH #461 deep-divergence stress (warm + cold)
-// - large_repository: one pinned large corpus with 8 worktrees and 50 branches
+// - divergent_branches: 200 branches spread across history depth / GH #461 stress (warm + cold)
+// - large_repository: one pinned upstream corpus with 8 worktrees and 50 branches
// spread through history; default list (warm + cold) and --branches (warm)
//
// Attribution: a `full` wall time can't be split by side (worktree- and
@@ -21,7 +21,7 @@
// cargo bench --bench list # All benchmarks
// cargo bench --bench list skeleton # Progressive rendering
// cargo bench --bench list full # Combined full-surface fixture
-// cargo bench --bench list large_repository # Canonical large repo
+// cargo bench --bench list large_repository # Large-repository workload
// cargo bench --bench list warm # Warm-cache variants (every group's warm rows)
// cargo bench --bench list skeleton/warm # Skeleton group, warm only
@@ -32,7 +32,7 @@ use wt_perf::{
CacheState, FixtureRecipe, bench_wt, run_git, standard_benchmark_profile, wt_command,
};
-const WORKTREE_COUNTS: [usize; 3] = [1, 4, 8];
+const WORKTREE_COUNTS: [usize; 2] = [1, 8];
/// Run `wt` with `args` in `repo_path`, on a warm or cold cache.
///
@@ -66,7 +66,7 @@ fn bench_skeleton(c: &mut Criterion) {
BenchmarkId::new(cache.label(), total_worktrees),
&cache,
|b, &cache| {
- let fixture = FixtureRecipe::Typical { total_worktrees }.create();
+ let fixture = FixtureRecipe::generated(total_worktrees - 1).create();
run_benchmark(
b,
binary,
@@ -93,7 +93,7 @@ fn bench_worktree_scaling(c: &mut Criterion) {
BenchmarkId::new(cache.label(), total_worktrees),
&cache,
|b, &cache| {
- let fixture = FixtureRecipe::Typical { total_worktrees }.create();
+ let fixture = FixtureRecipe::generated(total_worktrees - 1).create();
run_git(fixture.path(), &["status"]);
run_benchmark(b, binary, fixture.path(), cache, &["list"], None);
},
@@ -136,7 +136,7 @@ fn bench_large_repository(c: &mut Criterion) {
&cache,
|b, &cache| {
let fixture = fixture.get_or_init(|| {
- let fixture = FixtureRecipe::LargeRepository.create();
+ let fixture = FixtureRecipe::Imported.create();
run_git(fixture.path(), &["status"]);
fixture
});
@@ -157,7 +157,12 @@ fn bench_divergent_branches(c: &mut Criterion) {
for cache in CacheState::WARM_AND_COLD {
group.bench_function(cache.label(), |b| {
- let fixture = FixtureRecipe::SyntheticDivergence.create();
+ let fixture = FixtureRecipe::Generated {
+ linked_worktrees: 0,
+ branchless_branches: 200,
+ remote_tracking_refs: 0,
+ }
+ .create();
run_git(fixture.path(), &["status"]);
run_benchmark(
b,
@@ -178,7 +183,7 @@ fn bench_divergent_branches(c: &mut Criterion) {
/// command exercised by one fixture instead of several narrow ones. This is the
/// realistic "lots of worktrees & branches, all in various states" workload.
///
-/// [`FixtureRecipe::Mixed`] builds the spread of `wt list` gates and tasks at once:
+/// The generated fixture builds the spread of `wt list` gates and tasks at once:
/// clean/dirty/staged working trees, merged/ahead/diverged branches, and the
/// GH #461 deep-divergence shape (branches forking at points spread across
/// history depth, so the `git for-each-ref %(ahead-behind)` walk has real
@@ -206,10 +211,10 @@ fn bench_divergent_branches(c: &mut Criterion) {
/// network-touching `ci` column that `--full` would add.
fn bench_full(c: &mut Criterion) {
let mut group = c.benchmark_group("full");
- // Heavy fixture (24 worktrees + 120 branches, deep history): the cold
- // variant runs well over the inherited 30-sample / 15s budget, so cap
- // samples at criterion's minimum and give a 20s window (β‰ˆ a few iters per
- // sample), matching the other heavy groups.
+ // Heavy fixture (24 linked worktrees + 120 branchless branches, deep
+ // history): the cold variant runs well over the inherited 30-sample / 15s
+ // budget. Cap samples at criterion's minimum and give a 20s window (β‰ˆ a
+ // few iters per sample), matching the other heavy groups.
group.measurement_time(std::time::Duration::from_secs(20));
group.sample_size(10);
@@ -218,7 +223,7 @@ fn bench_full(c: &mut Criterion) {
for cache in CacheState::WARM_AND_COLD {
group.bench_function(cache.label(), |b| {
- let fixture = FixtureRecipe::Mixed {
+ let fixture = FixtureRecipe::Generated {
linked_worktrees,
branchless_branches,
remote_tracking_refs: 0,
diff --git a/benches/picker_preview.rs b/benches/picker_preview.rs
index dedc4eb33..a58a077b3 100644
--- a/benches/picker_preview.rs
+++ b/benches/picker_preview.rs
@@ -29,13 +29,13 @@
// #2685 / #2704 actually pushes on.
//
// Benchmark variants:
-// - picker_preview/warm/typical-8
-// - picker_preview/cold/typical-8
+// - picker_preview/warm/8-worktrees
+// - picker_preview/cold/8-worktrees
//
// Run examples:
// cargo bench --bench picker_preview # all variants
// cargo bench --bench picker_preview warm # warm only
-// cargo bench --bench picker_preview -- --exact picker_preview/warm/typical-8
+// cargo bench --bench picker_preview -- --exact picker_preview/warm/8-worktrees
#[cfg(not(unix))]
fn main() {
@@ -52,12 +52,8 @@ use wt_perf::{CacheState, FixtureRecipe, bench_wt, wt_command};
#[cfg(unix)]
fn bench_picker_preview(c: &mut Criterion) {
let mut group = c.benchmark_group("picker_preview");
- // The picker workload runs a few hundred ms warm on typical-8 (the
- // ~1.4s median quoted in `src/commands/picker/mod.rs` is on a different
- // fixture; measured ~320ms / ~370ms warm/cold here on a 14-core M-series
- // box). Sticking with `sample_size(10)` per #2685's lead and budgeting
- // 35s gives Criterion enough headroom to fit 10 samples without the
- // "increase target time" warning under either cache mode.
+ // Use Criterion's minimum sample count and enough measurement time for the
+ // full preview workload under either cache mode.
group.sample_size(10);
group.measurement_time(std::time::Duration::from_secs(35));
@@ -66,10 +62,10 @@ fn bench_picker_preview(c: &mut Criterion) {
for cache in CacheState::WARM_AND_COLD {
group.bench_with_input(
- BenchmarkId::new(cache.label(), format!("typical-{total_worktrees}")),
+ BenchmarkId::new(cache.label(), format!("{total_worktrees}-worktrees")),
&cache,
|b, &cache| {
- let fixture = FixtureRecipe::Typical { total_worktrees }.create();
+ let fixture = FixtureRecipe::generated(total_worktrees - 1).create();
let make_cmd = || {
let mut cmd = wt_command(binary, fixture.path(), None);
diff --git a/benches/prune.rs b/benches/prune.rs
index 0f8b7649d..71dd45721 100644
--- a/benches/prune.rs
+++ b/benches/prune.rs
@@ -11,7 +11,7 @@
// delete) serially under the write side of the scan lock, reusing the
// removal plan its scan check computed.
//
-// The fixture is `wt_perf::FixtureRecipe::Prune`: squash-merged candidates
+// The generated base gets a prune overlay: squash-merged candidates
// (integrated by content β€” the expensive probe path, the post-PR-squash shape
// prune typically removes) against a two-sided-diverged backdrop of unmerged
// worktrees and branches (forked deep in history while main advanced) that
@@ -23,11 +23,12 @@
// new commits on main" shape; git's own caches
// stay warm, as after a real fetch)
// - prune_e2e/dry_run_warm β€” full scan, caches warm (steady-state re-run)
+// - prune_e2e/dry_run_cold β€” full scan, including cold git/default-branch state
// - prune_e2e/live β€” scan + removal of the squash-merged candidates
// from a fresh fixture per sample
// - prune_large_repository/ β€” the same probe-cold and warm dry-runs on a
-// dry_run_probe_cold, pinned large-repository corpus with both
-// dry_run_warm populations at "dozens of worktrees" scale (~15 GiB
+// dry_run_probe_cold, pinned imported corpus with both
+// dry_run_warm populations at "dozens of worktrees" scale (multi-gigabyte
// fixture; first-ever run clones, minutes).
// Opt-in via `--features large-repository-benches` so
// the daily CI benchmarks job never builds it;
@@ -35,12 +36,13 @@
// timelines, not criterion groups (see below)
//
// Run examples:
-// cargo bench --bench prune # Synthetic variants
+// cargo bench --bench prune # Ordinary-scale variants
// cargo bench --bench prune --features large-repository-benches prune_large_repository
//
// For phase attribution (scan vs per-candidate removal), trace one invocation
-// instead: `wt-perf setup prune 4 8 --path /tmp/prune-repo`, then
-// `wt-perf timeline -- -C /tmp/prune-repo step prune --dry-run --min-age 0s`
+// instead: `wt-perf setup generated 0 0 --prune-candidates 4
+// --prune-backdrop 8 --path target/wt-prune-generated`, then
+// `wt-perf timeline -- -C target/wt-prune-generated step prune --dry-run --min-age 0s`
// and read the `prune-gather` / `prune-scan` / `prune-check:*` /
// `prune-remove:*` spans.
@@ -51,8 +53,8 @@ use std::time::{Duration, Instant};
use criterion::{Criterion, criterion_group, criterion_main};
use wt_perf::{
- CacheState, FixtureRecipe, PRUNE_LARGE_REPOSITORY_BACKDROP_PAIRS,
- PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS, bench_wt, invalidate_probe_caches,
+ CacheState, FixtureRecipe, FixtureRepo, IMPORTED_PRUNE_BACKDROP_PAIRS,
+ IMPORTED_PRUNE_CANDIDATE_PAIRS, add_prune_populations, bench_wt, invalidate_probe_caches,
linked_worktree_path, run_and_check, run_git_ok, wt_command,
};
@@ -75,6 +77,20 @@ const DRY_RUN_ARGS: &[&str] = &[
];
const LIVE_ARGS: &[&str] = &["step", "prune", "--min-age", "0s", "--format", "json"];
+fn generated_prune_fixture() -> FixtureRepo {
+ // The prune overlay supplies its own exact candidate/backdrop populations.
+ // Ordinary generated behind/identical branches would be extra candidates,
+ // so this destructive scenario intentionally starts with zero of them.
+ let fixture = FixtureRecipe::Generated {
+ linked_worktrees: 0,
+ branchless_branches: 0,
+ remote_tracking_refs: 0,
+ }
+ .create();
+ add_prune_populations(fixture.path(), MERGED, UNMERGED);
+ fixture
+}
+
/// Build the `wt <args>` command for `repo`.
fn wt_cmd(repo: &Path, args: &[&str]) -> Command {
let mut cmd = wt_command(Path::new(env!("CARGO_BIN_EXE_wt")), repo, None);
@@ -128,8 +144,8 @@ fn assert_live_result(repo: &Path) {
assert_branch(repo, &branch, false);
}
for i in 0..UNMERGED {
- let worktree_branch = format!("feature-wt-{i}");
- let branch = format!("feature-{i:03}");
+ let worktree_branch = format!("unmerged-wt-{i}");
+ let branch = format!("unmerged-br-{i:03}");
assert!(
linked_worktree_path(repo, &worktree_branch).is_dir(),
"measured prune removed backdrop worktree {worktree_branch}"
@@ -144,18 +160,16 @@ fn bench_prune_e2e(c: &mut Criterion) {
// Dry-run repo: candidates present but never removed, so the fixture is
// reusable across iterations without re-setup.
- let dry_fixture = FixtureRecipe::Prune {
- candidate_pairs: MERGED,
- backdrop_pairs: UNMERGED,
- }
- .create();
+ let dry_fixture = generated_prune_fixture();
verify_candidates(dry_fixture.path(), MERGED * 2);
for (id, cache) in [
- // First prune after fetching the default branch.
- ("dry_run_probe_cold", CacheState::ProbeCold),
// Steady-state re-scan where every probe hits sha_cache.
("dry_run_warm", CacheState::Warm),
+ // First prune after fetching the default branch.
+ ("dry_run_probe_cold", CacheState::ProbeCold),
+ // First run against fresh equivalent repo state.
+ ("dry_run_cold", CacheState::Cold),
] {
group.bench_function(id, |b| {
bench_wt(b, dry_fixture.path(), cache, || {
@@ -171,11 +185,7 @@ fn bench_prune_e2e(c: &mut Criterion) {
b.iter_custom(|iterations| {
let mut measured = Duration::ZERO;
for _ in 0..iterations {
- let fixture = FixtureRecipe::Prune {
- candidate_pairs: MERGED,
- backdrop_pairs: UNMERGED,
- }
- .create();
+ let fixture = generated_prune_fixture();
verify_candidates(fixture.path(), MERGED * 2);
invalidate_probe_caches(fixture.path());
@@ -191,14 +201,13 @@ fn bench_prune_e2e(c: &mut Criterion) {
group.finish();
}
-/// Large-repository scan: a 331k-commit repo
+/// Imported scan: a 331k-commit repo
/// with 12 squash-merged candidate pairs against a two-sided-diverged
/// backdrop of 24 worktrees + 24 orphan branches forked across the last 5000
-/// commits β€” 36 linked worktrees, lots removable, more not. Scale is what
-/// moves every per-item cost β€” `merge-base --is-ancestor` ~40 ms, `merge-tree
-/// --write-tree` ~130 ms, `git status` over ~60k files β€” vs the synthetic
-/// fixture where probes bottom out at subprocess spawn. The pinned source is
-/// cached; each benchmark process builds one fresh ~36-worktree fixture.
+/// commits, layered onto the imported repo's existing state. Scale is what
+/// moves every per-item `merge-base`, `merge-tree`, and `git status` cost beyond
+/// the subprocess-spawn floor visible in the generated fixture. The pinned source is
+/// cached; each benchmark process builds one fresh fixture.
///
/// Dry-runs only, in two flavors: warm (steady-state re-scan) and probe-cold
/// (`.git/wt/cache/` cleared per iteration β€” the "first prune after fetching
@@ -206,9 +215,9 @@ fn bench_prune_e2e(c: &mut Criterion) {
/// stat-warm). A full-cold scan and live removal are one-shot timeline
/// workloads at this scale: the former adds commit-graph rebuilding to the
/// probe cost, while the latter consumes its fixture. Use `wt-perf setup
-/// large-repository-prune 12 24 --path <new-path>` for either.
+/// imported --prune-candidates 12 --prune-backdrop 24 --path <new-path>` for either.
fn bench_prune_large_repository(c: &mut Criterion) {
- // Opt-in only (`--features large-repository-benches`): the fixture is ~15 GiB β€”
+ // Opt-in only (`--features large-repository-benches`): the fixture is multi-gigabyte β€”
// bigger than a hosted CI runner's disk and the actions cache cap β€” so
// the daily benchmarks workflow (plain `cargo bench`) must never build
// it. `cfg!` keeps the body compiling either way.
@@ -226,14 +235,16 @@ fn bench_prune_large_repository(c: &mut Criterion) {
// (`cargo bench --bench prune prune_e2e`) from cloning the large
// corpus. Both variants share the fresh fixture when both match.
let fixture = fixture.get_or_init(|| {
- FixtureRecipe::LargeRepositoryPrune {
- candidate_pairs: PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS,
- backdrop_pairs: PRUNE_LARGE_REPOSITORY_BACKDROP_PAIRS,
- }
- .create()
+ let fixture = FixtureRecipe::Imported.create();
+ add_prune_populations(
+ fixture.path(),
+ IMPORTED_PRUNE_CANDIDATE_PAIRS,
+ IMPORTED_PRUNE_BACKDROP_PAIRS,
+ );
+ fixture
});
let repo = fixture.path();
- verify_candidates(repo, PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS * 2);
+ verify_candidates(repo, IMPORTED_PRUNE_CANDIDATE_PAIRS * 2);
bench_wt(b, repo, CacheState::Warm, || wt_cmd(repo, DRY_RUN_ARGS));
});
@@ -241,14 +252,16 @@ fn bench_prune_large_repository(c: &mut Criterion) {
// Built inside the closure for the same filter-matching reason as
// dry_run_warm above.
let fixture = fixture.get_or_init(|| {
- FixtureRecipe::LargeRepositoryPrune {
- candidate_pairs: PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS,
- backdrop_pairs: PRUNE_LARGE_REPOSITORY_BACKDROP_PAIRS,
- }
- .create()
+ let fixture = FixtureRecipe::Imported.create();
+ add_prune_populations(
+ fixture.path(),
+ IMPORTED_PRUNE_CANDIDATE_PAIRS,
+ IMPORTED_PRUNE_BACKDROP_PAIRS,
+ );
+ fixture
});
let repo = fixture.path();
- verify_candidates(repo, PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS * 2);
+ verify_candidates(repo, IMPORTED_PRUNE_CANDIDATE_PAIRS * 2);
bench_wt(b, repo, CacheState::ProbeCold, || {
wt_cmd(repo, DRY_RUN_ARGS)
});
diff --git a/benches/remove.rs b/benches/remove.rs
index a5453426d..47017eb23 100644
--- a/benches/remove.rs
+++ b/benches/remove.rs
@@ -4,9 +4,10 @@
// spawning, to complement `first_output/remove` in `time_to_first_output`,
// which exits before output.
//
-// Both variants use the same project and user hook configuration:
-// - remove_e2e/no_hooks β€” the hooks are bypassed with --no-hooks
-// - remove_e2e/with_hooks β€” the hooks are approved and spawned
+// Three single-factor variants use the same project and user hook configuration:
+// - remove_e2e/warm/no_hooks β€” steady-state removal with hooks bypassed
+// - remove_e2e/cold/no_hooks β€” fresh-state neighbor for the cache cost
+// - remove_e2e/warm/with_hooks β€” warm neighbor for the hook cost
//
// Run examples:
// cargo bench --bench remove # All variants
@@ -17,11 +18,12 @@ use std::time::{Duration, Instant};
use criterion::{Criterion, criterion_group, criterion_main};
use wt_perf::{
- FixtureRecipe, FixtureRepo, add_typical_linked_worktrees, linked_worktree_path, run_and_check,
- run_git, run_git_ok, setup_fake_remote, wt_command,
+ CacheState, FixtureRecipe, FixtureRepo, add_heterogeneous_linked_worktrees,
+ invalidate_caches_auto, invalidate_probe_caches, linked_worktree_path, run_and_check, run_git,
+ run_git_ok, setup_fake_remote, wt_command,
};
-const BRANCH: &str = "feature-wt-1";
+const BRANCH: &str = "wt-0000";
const UNTRACKED_FILES: usize = 3;
const BACKGROUND_TIMEOUT: Duration = Duration::from_secs(10);
const POLL_INTERVAL: Duration = Duration::from_millis(20);
@@ -36,8 +38,8 @@ struct RemoveFixture {
impl RemoveFixture {
/// Build one complete candidate outside the measured duration.
- fn create(binary: &Path) -> Self {
- let repo = FixtureRecipe::Typical { total_worktrees: 1 }.create();
+ fn create(binary: &Path, cache: CacheState) -> Self {
+ let repo = FixtureRecipe::generated(0).create();
let project_marker = repo.root().join("project-post-remove.marker");
let user_marker = repo.root().join("user-post-switch.marker");
@@ -54,8 +56,16 @@ impl RemoveFixture {
run_git(repo.path(), &["add", ".config/wt.toml"]);
run_git(repo.path(), &["commit", "-m", "Add benchmark hook"]);
- add_typical_linked_worktrees(repo.path(), 1);
+ add_heterogeneous_linked_worktrees(repo.path(), 1);
setup_fake_remote(repo.path());
+ let worktree = repo.worktree_path(BRANCH);
+ for i in 0..UNTRACKED_FILES {
+ std::fs::write(
+ worktree.join(format!("uncommitted_{i}.txt")),
+ "Uncommitted content\n",
+ )
+ .unwrap();
+ }
let worktree_admin_dir = linked_worktree_admin_dir(&repo.worktree_path(BRANCH));
let user_config = repo.root().join("config.toml");
@@ -85,6 +95,11 @@ impl RemoveFixture {
);
}
fixture.prewarm(binary);
+ match cache {
+ CacheState::Warm => {}
+ CacheState::Cold => invalidate_caches_auto(fixture.repo.path()),
+ CacheState::ProbeCold => invalidate_probe_caches(fixture.repo.path()),
+ }
fixture
}
@@ -92,9 +107,7 @@ impl RemoveFixture {
linked_worktree_path(self.repo.path(), BRANCH)
}
- /// Preserve the original cache-warm remove scenario without reusing a
- /// mutable fixture. Prune's dry-run uses the same integration probes and
- /// cannot consume the unmerged candidate.
+ /// Prewarm the integration probes without consuming the unmerged candidate.
fn prewarm(&self, binary: &Path) {
let mut cmd = wt_command(binary, self.repo.path(), Some(&self.user_config));
cmd.args([
@@ -179,6 +192,7 @@ fn bench_variant(
group: &mut criterion::BenchmarkGroup<'_, criterion::measurement::WallTime>,
name: &str,
expect_hooks: bool,
+ cache: CacheState,
) {
let binary = Path::new(env!("CARGO_BIN_EXE_wt"));
@@ -186,7 +200,7 @@ fn bench_variant(
b.iter_custom(|iterations| {
let mut measured = Duration::ZERO;
for _ in 0..iterations {
- let fixture = RemoveFixture::create(binary);
+ let fixture = RemoveFixture::create(binary, cache);
let worktree = fixture.worktree_path();
let mut cmd = wt_command(binary, &worktree, Some(&fixture.user_config));
cmd.args(["remove", "--yes", "--force"]);
@@ -207,8 +221,9 @@ fn bench_variant(
fn bench_remove_e2e(c: &mut Criterion) {
let mut group = c.benchmark_group("remove_e2e");
- bench_variant(&mut group, "no_hooks", false);
- bench_variant(&mut group, "with_hooks", true);
+ bench_variant(&mut group, "warm/no_hooks", false, CacheState::Warm);
+ bench_variant(&mut group, "cold/no_hooks", false, CacheState::Cold);
+ bench_variant(&mut group, "warm/with_hooks", true, CacheState::Warm);
group.finish();
}
diff --git a/benches/time_to_first_output.rs b/benches/time_to_first_output.rs
index 2e1d36243..6bddb4dcf 100644
--- a/benches/time_to_first_output.rs
+++ b/benches/time_to_first_output.rs
@@ -23,7 +23,7 @@ fn bench_first_output(c: &mut Criterion) {
let mut group = c.benchmark_group("first_output");
let binary = Path::new(env!("CARGO_BIN_EXE_wt"));
- let fixture = FixtureRecipe::Typical { total_worktrees: 4 }.create();
+ let fixture = FixtureRecipe::generated(3).create();
let make_cmd = |args: &[&str]| {
let mut cmd = wt_command(binary, fixture.path(), None);
@@ -41,14 +41,14 @@ fn bench_first_output(c: &mut Criterion) {
// timing would be warm cache, not the first-invocation TTFO a user sees.
group.bench_function("remove", |b| {
bench_wt(b, fixture.path(), CacheState::Cold, || {
- make_cmd(&["remove", "--yes", "--no-hooks", "--force", "feature-wt-1"])
+ make_cmd(&["remove", "--yes", "--no-hooks", "--force", "wt-0000"])
});
});
// switch: exits after execute_switch, before mismatch computation and output
group.bench_function("switch", |b| {
bench_wt(b, fixture.path(), CacheState::Warm, || {
- make_cmd(&["switch", "--yes", "--no-hooks", "feature-wt-1"])
+ make_cmd(&["switch", "--yes", "--no-hooks", "wt-0000"])
});
});
diff --git a/flake.nix b/flake.nix
index 38cbe3552..aa39462a5 100644
--- a/flake.nix
+++ b/flake.nix
@@ -54,7 +54,7 @@
|| (pkgs.lib.hasInfix "/dev/" p)
|| (baseNameOf (dirOf p) == "dev")
|| (baseNameOf p == "gemini-extension.json")
- || (baseNameOf p == "large-repository-fixture");
+ || (baseNameOf p == "imported-fixture");
};
# Common arguments for crane builds
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
index f2922cf94..ae7eff317 100644
--- a/src/commands/CLAUDE.md
+++ b/src/commands/CLAUDE.md
@@ -7,7 +7,7 @@ When debugging TUI commands like `wt switch` (interactive picker), use the `tmux
### 1. Create Test Environment
```bash
-cargo run -p wt-perf -- setup mixed 5 2 0 --path /tmp/wt-picker-test
+cargo run -p wt-perf -- setup generated 5 2 0 --path target/wt-picker-test
```
This creates a varied repository with linked worktrees and branch-only rows for
@@ -22,7 +22,7 @@ Load the `tmux-cli` skill, then use the `tmux-cli` tool. Install if needed: `uv
```bash
# Launch shell in test repo
pane=$(tmux-cli launch "zsh")
-tmux-cli send "cd /tmp/wt-picker-test" --pane=$pane
+tmux-cli send "cd target/wt-picker-test" --pane=$pane
tmux-cli wait_idle --pane=$pane
# Run with debug logging
@@ -44,7 +44,7 @@ MCP terminals use pseudo-TTY, not real terminals. If tests pass in MCP but users
```typescript
// Create terminal and navigate to test repo
mcp__node-terminal__terminal_create({ sessionId: "test" })
-mcp__node-terminal__terminal_write({ sessionId: "test", input: "cd /tmp/wt-picker-test" })
+mcp__node-terminal__terminal_write({ sessionId: "test", input: "cd target/wt-picker-test" })
mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
// Run with debug logging
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index c9b283c57..06e0047ab 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -68,7 +68,6 @@
//! 1. **Index (`.git/index`)** - Cached file metadata (mtime, size, mode)
//! - Speeds up `git status` by avoiding full file content comparisons
//! - Invalidated when files change or staging area updates
-//! - Cold: ~100ms per worktree, Warm: ~10ms per worktree (typical repo)
//!
//! 2. **Commit graph (`.git/objects/info/commit-graph`)** - Precomputed commit metadata
//! - Speeds up `git rev-list --count` by avoiding commit object parsing
@@ -103,11 +102,10 @@
//! ## Performance Characteristics
//!
//! Scaling (from benches/list.rs):
-//! - Linear with worktree count due to parallelization (Rayon thread pool)
-//! - Dominated by git command overhead, not Rust code
-//! - Cold caches: ~150-300ms per worktree (typical repo, 500 commits, 100 files)
-//! - Warm caches: ~20-50ms per worktree
-//! - Large-repository corpus (currently rust-lang/rust), 8 worktrees: ~400ms warm
+//! - Each worktree adds a `git status --porcelain`, parallelized on the Rayon pool
+//! - Git command overhead dominates the Rust code
+//! - Warm/cold 1-vs-8-worktree contrasts use the generated corpus
+//! - The imported corpus (currently rust-lang/rust) covers deep history and large trees
//!
//! Bottlenecks:
//! 1. `git status --porcelain` - Slowest when index is cold or many files changed
diff --git a/tests/helpers/wt-perf/src/lib.rs b/tests/helpers/wt-perf/src/lib.rs
index 6a115839a..086b0561d 100644
--- a/tests/helpers/wt-perf/src/lib.rs
+++ b/tests/helpers/wt-perf/src/lib.rs
@@ -11,8 +11,8 @@
//! ```rust,ignore
//! use wt_perf::{FixtureRecipe, invalidate_caches_auto};
//!
-//! // Create a typical repo with 8 total worktrees.
-//! let fixture = FixtureRecipe::Typical { total_worktrees: 8 }.create();
+//! // Create the generated repo with 8 total worktrees.
+//! let fixture = FixtureRecipe::generated(7).create();
//!
//! // Invalidate caches for cold benchmark
//! invalidate_caches_auto(fixture.path());
@@ -28,21 +28,20 @@ use std::process::{Command, Output};
use tempfile::TempDir;
use worktrunk::testing::{allow_network_transports, configure_git_cmd, isolate_subprocess_env};
-mod large_repository_fixture {
+mod imported_fixture {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
- "/../../../benches/large-repository-fixture"
+ "/../../../benches/imported-fixture"
));
}
-use large_repository_fixture::{
- CORPUS as LARGE_REPOSITORY_CORPUS, REVISION as LARGE_REPOSITORY_REVISION,
-};
-/// Worktrees in the canonical read-only large-repository fixture, including
+use imported_fixture::{CORPUS as IMPORTED_CORPUS, REVISION as IMPORTED_REVISION};
+/// Worktrees in the canonical imported fixture, including
/// the primary worktree.
-const LARGE_REPOSITORY_TOTAL_WORKTREES: usize = 8;
-/// Branches in the canonical read-only large-repository fixture, spread over
+const IMPORTED_TOTAL_WORKTREES: usize = 8;
+/// Branches in the canonical imported fixture, spread over
/// the most recent 5,000 commits.
-const LARGE_REPOSITORY_HISTORY_SPREAD_BRANCHES: usize = 50;
+const IMPORTED_HISTORY_SPREAD_BRANCHES: usize = 50;
+const GENERATED_DEFAULT_BRANCHES: usize = 50;
/// An owned temporary benchmark fixture.
///
@@ -113,21 +112,16 @@ pub fn linked_worktree_path(repo_path: &Path, branch: &str) -> PathBuf {
.join(format!("{repo_name}.{branch}"))
}
-/// Low-level parameters for the flat synthetic repository builder.
+/// Low-level parameters for the simple generated repository builder.
///
-/// Benchmark callers name a [`FixtureRecipe`]. Keeping this type private
-/// prevents arbitrary parameter combinations from becoming an accidental
-/// second fixture catalog.
-#[derive(Clone, Debug)]
-struct FlatRepoConfig {
+/// Unit tests use this private builder for focused repository states without
+/// adding them to the benchmark fixture catalog.
+#[cfg(test)]
+struct SimpleRepoConfig {
/// Number of commits on main branch
commits_on_main: usize,
/// Number of files in the repo
files: usize,
- /// Number of branches (without worktrees)
- branchless_branches: usize,
- /// Commits per branch
- commits_per_branch: usize,
/// Number of worktrees (including main)
total_worktrees: usize,
/// Commits ahead of main per worktree
@@ -136,118 +130,45 @@ struct FlatRepoConfig {
worktree_uncommitted_files: usize,
}
-impl FlatRepoConfig {
- /// Typical repo with worktrees (500 commits, 100 files).
- ///
- /// Good for skeleton rendering and general worktree benchmarks.
- const fn typical(total_worktrees: usize) -> Self {
- Self {
- commits_on_main: 500,
- files: 100,
- branchless_branches: 0,
- commits_per_branch: 0,
- total_worktrees,
- worktree_commits_ahead: 10,
- worktree_uncommitted_files: 3,
- }
- }
-
- /// Branch-focused config (minimal history, many branches).
- const fn minimal(
- branchless_branches: usize,
- linked_worktrees: usize,
- commits_per_branch: usize,
- ) -> Self {
- Self {
- commits_on_main: 1,
- files: 1,
- branchless_branches,
- commits_per_branch,
- total_worktrees: linked_worktrees + 1,
- worktree_commits_ahead: 0,
- worktree_uncommitted_files: 0,
- }
- }
-
- /// Many divergent branches (GH #461 scenario: 200 branches Γ— 20 commits).
- const fn synthetic_divergence() -> Self {
- Self {
- commits_on_main: 100,
- files: 50,
- branchless_branches: 200,
- commits_per_branch: 20,
- total_worktrees: 1,
- worktree_commits_ahead: 0,
- worktree_uncommitted_files: 0,
- }
- }
-}
-
/// The benchmark fixture catalog.
///
-/// Variants are sparse, named repository states rather than combinations of
-/// independent base, shape, and storage axes. Large-corpus recipes reuse the
-/// same pinned source while every mutable fixture remains caller-owned.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Subcommand)]
+/// Variants name corpus provenance. Both build ordinary Git repositories;
+/// worktree, branch, and remote-ref counts are population dimensions within a
+/// base, and prune candidates are added afterward.
+#[derive(Clone, Copy, Subcommand)]
pub enum FixtureRecipe {
- /// Standard synthetic history, files, and feature worktrees.
- Typical {
- /// Total worktrees, including the primary worktree.
- #[arg(value_parser = positive_usize)]
- total_worktrees: usize,
- },
- /// Minimal history and files with configurable branch/worktree populations.
- Minimal {
- /// Branches without linked worktrees.
- branchless_branches: usize,
- /// Linked worktrees, excluding the primary worktree.
- linked_worktrees: usize,
- },
- /// Fixed deep-divergence branch stress.
- SyntheticDivergence,
- /// Pinned large corpus with worktrees and branches spread across history.
- LargeRepository,
- /// Varied branch and worktree state rotation.
- Mixed {
+ /// Locally generated corpus with heterogeneous branch and worktree state.
+ Generated {
/// Linked worktrees, excluding the primary worktree.
+ #[arg(default_value_t = 7)]
linked_worktrees: usize,
/// Branches without linked worktrees.
+ #[arg(default_value_t = GENERATED_DEFAULT_BRANCHES)]
branchless_branches: usize,
/// Additional remote-tracking refs.
#[arg(default_value_t = 0)]
remote_tracking_refs: usize,
},
- /// Prune candidates and the unintegrated scan backdrop.
- Prune {
- /// Squash-merged worktree/branch pairs.
- candidate_pairs: usize,
- /// Unintegrated worktree/branch pairs.
- backdrop_pairs: usize,
- },
- /// Pinned large corpus with prune candidates and an unintegrated backdrop.
- LargeRepositoryPrune {
- /// Squash-merged worktree/branch pairs.
- candidate_pairs: usize,
- /// Unintegrated worktree/branch pairs.
- backdrop_pairs: usize,
- },
-}
-
-fn positive_usize(value: &str) -> Result<usize, String> {
- let value = value
- .parse::<usize>()
- .map_err(|_| "expected a positive integer".to_string())?;
- (value >= 1)
- .then_some(value)
- .ok_or_else(|| "expected a positive integer".to_string())
+ /// Pinned rust-lang/rust corpus with heterogeneous history-spread state.
+ Imported,
}
impl FixtureRecipe {
+ /// The standard generated state: history-spread branches remain constant
+ /// while a benchmark varies only the linked-worktree population.
+ pub const fn generated(linked_worktrees: usize) -> Self {
+ Self::Generated {
+ linked_worktrees,
+ branchless_branches: GENERATED_DEFAULT_BRANCHES,
+ remote_tracking_refs: 0,
+ }
+ }
+
/// Build an owned ephemeral fixture.
pub fn create(self) -> FixtureRepo {
let build = |repo: &Path| self.create_at(repo);
- if matches!(self, Self::LargeRepositoryPrune { .. }) {
- FixtureRepo::create_in(&large_repository_cache_dir().join("runs"), build)
+ if matches!(self, Self::Imported) {
+ FixtureRepo::create_in(&imported_cache_dir().join("runs"), build)
} else {
FixtureRepo::create(build)
}
@@ -256,63 +177,54 @@ impl FixtureRecipe {
/// Build an ephemeral fixture at a caller-chosen primary-worktree path.
pub fn create_at(self, base_path: &Path) {
match self {
- Self::Typical { total_worktrees } => {
- assert!(total_worktrees >= 1, "a fixture has a primary worktree");
- build_flat_repo_at(&FlatRepoConfig::typical(total_worktrees), base_path);
- }
- Self::Minimal {
- branchless_branches,
- linked_worktrees,
- } => {
- build_flat_repo_at(
- &FlatRepoConfig::minimal(branchless_branches, linked_worktrees, 0),
- base_path,
- );
- }
- Self::SyntheticDivergence => {
- let config = FlatRepoConfig::synthetic_divergence();
- build_flat_repo_at(&config, base_path);
- }
- Self::LargeRepository => {
- clone_large_repository_at(base_path);
- add_history_spread_branches(base_path, LARGE_REPOSITORY_HISTORY_SPREAD_BRANCHES);
- add_typical_linked_worktrees(base_path, LARGE_REPOSITORY_TOTAL_WORKTREES - 1);
- }
- Self::Mixed {
+ Self::Generated {
linked_worktrees,
branchless_branches,
remote_tracking_refs,
} => {
- build_mixed_repo_at(
+ build_generated_repo_at(
linked_worktrees,
branchless_branches,
remote_tracking_refs,
base_path,
);
}
- Self::Prune {
- candidate_pairs,
- backdrop_pairs,
- } => {
- build_prune_repo_at(candidate_pairs, backdrop_pairs, base_path);
- }
- Self::LargeRepositoryPrune {
- candidate_pairs,
- backdrop_pairs,
- } => {
- clone_large_repository_at(base_path);
- add_prune_populations(base_path, candidate_pairs, backdrop_pairs);
+ Self::Imported => {
+ clone_imported_at(base_path);
+ add_history_spread_branches(base_path, IMPORTED_HISTORY_SPREAD_BRANCHES);
+ add_imported_linked_worktrees(base_path, IMPORTED_TOTAL_WORKTREES - 1);
}
}
}
}
-/// Add the standard linked-worktree population to an existing typical fixture.
+/// Add the canonical heterogeneous linked-worktree rotation.
///
/// Destructive benchmarks use this after committing scenario-specific
/// configuration on the primary worktree but before recording a candidate.
-pub fn add_typical_linked_worktrees(repo_path: &Path, linked_worktrees: usize) {
- add_flat_worktrees(&FlatRepoConfig::typical(linked_worktrees + 1), repo_path);
+pub fn add_heterogeneous_linked_worktrees(repo_path: &Path, linked_worktrees: usize) {
+ let base_tip = head_sha(repo_path);
+ add_heterogeneous_worktrees(repo_path, linked_worktrees, &base_tip);
+}
+
+/// Add the heterogeneous imported worktree population without leaving a clean
+/// worktree integrated into the default branch. The generated corpus retains
+/// that state; the imported prune overlay needs its candidate count exact, so
+/// the clean base-tip worktrees get a commit of their own. The dirty base-tip
+/// states stay integrated by ref and are excluded from the count only because
+/// `wt step prune` skips worktrees with working-tree changes.
+fn add_imported_linked_worktrees(repo_path: &Path, linked_worktrees: usize) {
+ add_heterogeneous_linked_worktrees(repo_path, linked_worktrees);
+ for i in (3..linked_worktrees).step_by(4) {
+ let worktree = linked_worktree_path(repo_path, &format!("wt-{i:04}"));
+ let marker = format!("imported_wt_{i}.txt");
+ std::fs::write(worktree.join(&marker), format!("imported worktree {i}\n")).unwrap();
+ run_git(&worktree, &["add", &marker]);
+ run_git(
+ &worktree,
+ &["commit", "-m", &format!("Advance imported worktree {i}")],
+ );
+ }
}
/// Build a `git` command isolated from host context, with the host's
@@ -515,7 +427,8 @@ fn git_stdout(path: &Path, args: &[&str], index_file: &Path) -> String {
/// Uses worktrunk naming convention:
/// - Main worktree: `base_path`
/// - Feature worktrees: `base_path.feature-wt-N` (siblings in parent directory)
-fn build_flat_repo_at(config: &FlatRepoConfig, base_path: &Path) {
+#[cfg(test)]
+fn build_simple_repo_at(config: &SimpleRepoConfig, base_path: &Path) {
let repo_path = base_path.to_path_buf();
init_bench_repo(&repo_path);
@@ -554,34 +467,7 @@ fn build_flat_repo_at(config: &FlatRepoConfig, base_path: &Path) {
run_git(&repo_path, &["commit", "-m", &format!("Commit {i}")]);
}
- // Create branches (without worktrees)
- for i in 0..config.branchless_branches {
- let branch_name = format!("feature-{i:03}");
- run_git(&repo_path, &["checkout", "-b", &branch_name, "main"]);
-
- for j in 0..config.commits_per_branch {
- let feature_file = repo_path.join(format!("feature_{i:03}_{j}.rs"));
- std::fs::write(
- &feature_file,
- format!(
- "// Feature {i} file {j}\npub fn feature_{i}_func_{j}() -> i32 {{ {} }}\n",
- i * 100 + j
- ),
- )
- .unwrap();
- run_git(&repo_path, &["add", "."]);
- run_git(
- &repo_path,
- &["commit", "-m", &format!("Feature {branch_name} commit {j}")],
- );
- }
- }
-
- if config.branchless_branches > 0 {
- run_git(&repo_path, &["checkout", "main"]);
- }
-
- add_flat_worktrees(config, &repo_path);
+ add_simple_worktrees(config, &repo_path);
// Set up fake remote for default branch detection
setup_fake_remote(&repo_path);
@@ -600,7 +486,8 @@ fn build_flat_repo_at(config: &FlatRepoConfig, base_path: &Path) {
/// Creates `config.total_worktrees - 1` linked worktrees as siblings of `repo_path`
/// (e.g., `repo.feature-wt-1`), each with diverging commits and uncommitted files
/// controlled by `config.worktree_commits_ahead` and `config.worktree_uncommitted_files`.
-fn add_flat_worktrees(config: &FlatRepoConfig, repo_path: &Path) {
+#[cfg(test)]
+fn add_simple_worktrees(config: &SimpleRepoConfig, repo_path: &Path) {
for wt_num in 1..config.total_worktrees {
let branch = format!("feature-wt-{wt_num}");
let wt_path = linked_worktree_path(repo_path, &branch);
@@ -650,7 +537,7 @@ fn add_flat_worktrees(config: &FlatRepoConfig, repo_path: &Path) {
/// 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
-/// the mixed recipe's 200 commits, a four-digit ref count lands ~7 refs on
+/// the generated recipe'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
@@ -757,7 +644,7 @@ pub fn invalidate_caches_auto(repo_path: &Path) {
remove_file_if_exists(&git_dir.join("objects/info/commit-graph"));
remove_dir_if_exists(&git_dir.join("objects/info/commit-graphs"));
- // Note: `packed-refs` is intentionally NOT removed. After `build_flat_repo_at`
+ // Note: `packed-refs` is intentionally NOT removed. After fixture setup
// runs an explicit `git gc`, every loose ref under `refs/heads/`,
// `refs/remotes/`, etc. is packed into `packed-refs` and the loose files
// are pruned. Deleting `packed-refs` in that state leaves the repo with
@@ -870,10 +757,10 @@ fn resolve_git_common_dir(repo_path: &Path) -> Option<PathBuf> {
///
/// Living under `target/` means `cargo clean` reaps every fixture and each git
/// worktree keeps its own copy (worktrees don't share `target/`). That is cheap
-/// for the synthetic `setup` fixtures β€” rebuilt in seconds β€” but a deliberate
-/// cost for the ~15 GiB large-repository fixture under `bench-repos/`, which then re-clones
-/// per worktree and after every `cargo clean`. Relocate it with cargo's own
-/// `CARGO_TARGET_DIR` if that cost bites.
+/// for the generated `setup` fixtures β€” rebuilt in seconds β€” but a deliberate
+/// cost for the multi-gigabyte imported fixture under `bench-repos/`, which
+/// then re-clones per worktree and after every `cargo clean`. Relocate it with
+/// cargo's own `CARGO_TARGET_DIR` if that cost bites.
pub fn wt_perf_fixture_dir() -> PathBuf {
cargo_target_dir().join("wt-perf")
}
@@ -917,10 +804,8 @@ fn target_dir_from_exe(exe: &Path) -> Option<PathBuf> {
.map(Path::to_path_buf)
}
-fn large_repository_cache_dir() -> PathBuf {
- wt_perf_fixture_dir()
- .join("bench-repos")
- .join("large-repository")
+fn imported_cache_dir() -> PathBuf {
+ wt_perf_fixture_dir().join("bench-repos").join("imported")
}
fn acquire_exclusive_lock(path: &Path) -> File {
@@ -977,44 +862,41 @@ fn repository_is_on_main(repo: &Path) -> bool {
output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "main"
}
-fn large_repository_source_matches(repo: &Path) -> bool {
+fn imported_source_matches(repo: &Path) -> bool {
path_exists(repo)
- && repository_head(repo).as_deref() == Some(LARGE_REPOSITORY_REVISION)
+ && repository_head(repo).as_deref() == Some(IMPORTED_REVISION)
&& repository_is_on_main(repo)
&& run_git_ok(repo, &["fsck", "--connectivity-only", "--no-dangling"])
}
-/// Get or build the immutable source for large-repository benchmarks.
+/// Get or build the immutable source for imported benchmarks.
///
/// The revision is part of the cache path. Construction happens in a temporary
/// sibling and is atomically renamed into place after validation, so an
/// interrupted clone never looks like a usable cache entry.
-fn ensure_large_repository_source() -> PathBuf {
- let cache_dir = large_repository_cache_dir();
- let source = cache_dir.join(format!("source-{LARGE_REPOSITORY_REVISION}"));
- let staged_source = cache_dir.join(format!("source-{LARGE_REPOSITORY_REVISION}.building"));
+fn ensure_imported_source() -> PathBuf {
+ let cache_dir = imported_cache_dir();
+ let source = cache_dir.join(format!("source-{IMPORTED_REVISION}"));
+ let staged_source = cache_dir.join(format!("source-{IMPORTED_REVISION}.building"));
let _build_lock =
- acquire_exclusive_lock(&cache_dir.join(format!("source-{LARGE_REPOSITORY_REVISION}.lock")));
+ acquire_exclusive_lock(&cache_dir.join(format!("source-{IMPORTED_REVISION}.lock")));
if path_exists(&staged_source) {
remove_dir_if_exists(&staged_source);
}
- if large_repository_source_matches(&source) {
- eprintln!(
- "Using cached large-repository source at {}",
- source.display()
- );
+ if imported_source_matches(&source) {
+ eprintln!("Using cached imported source at {}", source.display());
return source;
}
if path_exists(&source) {
- eprintln!("Cached large-repository source is invalid; rebuilding");
+ eprintln!("Cached imported source is invalid; rebuilding");
remove_dir_if_exists(&source);
}
- let url = format!("https://github.com/{LARGE_REPOSITORY_CORPUS}.git");
+ let url = format!("https://github.com/{IMPORTED_CORPUS}.git");
eprintln!(
"Cloning {} at {} (this will take several minutes)...",
- LARGE_REPOSITORY_CORPUS, LARGE_REPOSITORY_REVISION
+ IMPORTED_CORPUS, IMPORTED_REVISION
);
let mut clone = git_command();
allow_network_transports(&mut clone);
@@ -1022,40 +904,34 @@ fn ensure_large_repository_source() -> PathBuf {
.args(["clone", "--no-checkout", &url])
.arg(&staged_source)
.output()
- .unwrap_or_else(|error| panic!("failed to spawn large-repository clone: {error}"));
+ .unwrap_or_else(|error| panic!("failed to spawn imported clone: {error}"));
assert!(
output.status.success(),
"failed to clone {}:\n{}",
- LARGE_REPOSITORY_CORPUS,
+ IMPORTED_CORPUS,
String::from_utf8_lossy(&output.stderr)
);
- run_git(
- &staged_source,
- &["checkout", "--detach", LARGE_REPOSITORY_REVISION],
- );
- run_git(
- &staged_source,
- &["branch", "-f", "main", LARGE_REPOSITORY_REVISION],
- );
+ run_git(&staged_source, &["checkout", "--detach", IMPORTED_REVISION]);
+ run_git(&staged_source, &["branch", "-f", "main", IMPORTED_REVISION]);
run_git(&staged_source, &["checkout", "main"]);
assert!(
- large_repository_source_matches(&staged_source),
- "large-repository source failed validation after checkout"
+ imported_source_matches(&staged_source),
+ "imported source failed validation after checkout"
);
std::fs::rename(&staged_source, &source).unwrap_or_else(|error| {
panic!(
- "failed to publish large-repository source {}: {error}",
+ "failed to publish imported source {}: {error}",
source.display()
)
});
- eprintln!("Large-repository source cloned successfully");
+ eprintln!("Imported source cloned successfully");
source
}
-/// Local-clone the pinned large-repository source to `dest` and configure a
+/// Local-clone the pinned imported source to `dest` and configure a
/// git user for fixture commits.
-fn clone_large_repository_at(dest: &Path) {
- let source = ensure_large_repository_source();
+fn clone_imported_at(dest: &Path) {
+ let source = ensure_imported_source();
let clone_output = git_command()
.args([
"clone",
@@ -1070,19 +946,19 @@ fn clone_large_repository_at(dest: &Path) {
.unwrap();
assert!(
clone_output.status.success(),
- "Failed to local-clone large-repository source: {}",
+ "Failed to local-clone imported source: {}",
String::from_utf8_lossy(&clone_output.stderr)
);
run_git(dest, &["config", "user.name", "Benchmark"]);
run_git(dest, &["config", "user.email", "[email protected]"]);
assert_eq!(
repository_head(dest).as_deref(),
- Some(LARGE_REPOSITORY_REVISION),
- "large-repository clone did not retain the pinned revision"
+ Some(IMPORTED_REVISION),
+ "imported clone did not retain the pinned revision"
);
assert!(
repository_is_on_main(dest),
- "large-repository clone must check out the pinned main branch"
+ "imported clone must check out the pinned main branch"
);
}
@@ -1101,7 +977,7 @@ fn history_spread_shas(repo_path: &Path, count: usize) -> Vec<String> {
.unwrap();
let log_str = String::from_utf8_lossy(&log_output.stdout);
// Step over the log we actually got, not the 5000 cap: on a short history
- // (the synthetic fixtures have a few hundred commits) dividing by the cap
+ // (the generated fixtures have a few hundred commits) dividing by the cap
// floors every sample onto the tip, collapsing the spread to one SHA.
// Guard the degenerate inputs: `count == 0` would divide by zero, and
// `count > len` would yield `step == 0`, which panics `step_by`. Both
@@ -1173,9 +1049,11 @@ fn add_branch_with_commits(repo_path: &Path, branch: &str, fork: &str, commits:
/// Create branches pointing at different depths in the repo's commit history.
///
/// Samples `count` commits via `history_spread_shas` and creates
-/// `feature-NNN` branches pointing at them. None carries its own commits, so
-/// every branch is an ancestor of the tip β€” behind it, except `feature-000`:
-/// the newest sample is the tip itself, so that one sits exactly on it.
+/// `feature-NNN` branches with one commit on top. Older samples are genuinely
+/// two-sided diverged from the default branch; `feature-000` is ahead from the
+/// current tip. If a later overlay advances the default branch, it becomes
+/// diverged too. This keeps the imported branches from turning into
+/// incidental prune candidates.
fn add_history_spread_branches(repo_path: &Path, branchless_branches: usize) {
let commits = history_spread_shas(repo_path, branchless_branches);
assert_eq!(
@@ -1184,12 +1062,12 @@ fn add_history_spread_branches(repo_path: &Path, branchless_branches: usize) {
"history-spread fixture needs at least {branchless_branches} commits"
);
for (i, commit) in commits.iter().enumerate() {
- add_branch_with_commits(repo_path, &format!("feature-{i:03}"), commit, 0);
+ add_branch_with_commits(repo_path, &format!("feature-{i:03}"), commit, 1);
}
}
-/// Add two-sided-diverged linked worktrees (`feature-wt-N`) and branchless
-/// branches (`feature-NNN`) to an existing repo.
+/// Add two-sided-diverged linked worktrees (`unmerged-wt-N`) and branchless
+/// branches (`unmerged-br-NNN`) to an existing repo.
///
/// Each forks at a `history_spread_shas` point and carries its own commits on
/// top. That is the shape of real long-lived feature work: `git merge-base`
@@ -1220,14 +1098,14 @@ fn add_diverged_backdrop(repo_path: &Path, linked_worktrees: usize, branchless_b
for i in 0..branchless_branches {
add_branch_with_commits(
repo_path,
- &format!("feature-{i:03}"),
+ &format!("unmerged-br-{i:03}"),
&forks[i % forks.len()],
3,
);
}
for i in 0..linked_worktrees {
- let wt_branch = format!("feature-wt-{i}");
+ let wt_branch = format!("unmerged-wt-{i}");
let wt_path = linked_worktree_path(repo_path, &wt_branch);
run_git(
repo_path,
@@ -1264,7 +1142,7 @@ fn head_sha(path: &Path) -> String {
}
/// Append a line to a tracked file (creating it if missing). Used to make
-/// working-tree edits in the mixed-state fixture.
+/// working-tree edits in the generated fixture.
fn append_line(path: &Path, rel: &str, line: &str) {
let file = path.join(rel);
let mut content = std::fs::read_to_string(&file).unwrap_or_default();
@@ -1273,17 +1151,15 @@ fn append_line(path: &Path, rel: &str, line: &str) {
std::fs::write(&file, content).unwrap();
}
-/// Create a repo with linked worktrees, branchless branches, and optional
-/// remote-tracking refs for the `full` list and shell-completion benchmarks.
+/// Create the generated corpus with controlled worktree, branch, and
+/// remote-ref populations.
///
-/// Unlike the flat recipes (every worktree/branch identical), this exercises the
-/// full spread of `wt list` gates and tasks at once β€” clean vs dirty working
-/// trees, merged vs ahead vs diverged branches, *and* divergence spread across
-/// history depth β€” the realistic shape of "a huge number of worktrees &
-/// branches, all in various states". Returns an owned fixture; the main
+/// This corpus exercises the full spread of `wt list` gates and tasks at once:
+/// clean vs dirty working trees, merged vs ahead vs
+/// diverged branches, and divergence spread across history depth. It models
+/// many worktrees and branches in varied states. The main
/// worktree is available through [`FixtureRepo::path`], and linked worktrees
-/// through [`FixtureRepo::worktree_path`]. Either dimension may be `0` (e.g.
-/// `mixed-W-0` for a worktrees-only repo).
+/// through [`FixtureRepo::worktree_path`]. Either dimension may be zero.
///
/// Worktree states cycle by index % 4:
/// 0. clean, several commits ahead of base
@@ -1301,7 +1177,7 @@ 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)
-fn build_mixed_repo_at(
+fn build_generated_repo_at(
linked_worktrees: usize,
branchless_branches: usize,
remote_tracking_refs: usize,
@@ -1309,9 +1185,7 @@ fn build_mixed_repo_at(
) {
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
- // staying far cheaper to build than the dedicated `divergent` stress
- // (`FixtureRecipe::SyntheticDivergence`, 200 branches Γ— 20 commits).
+ // `%(ahead-behind)` walk real commits to traverse (GH #461 shape).
const BASE_COMMITS: usize = 200;
// Record a checkpoint every few commits so behind/diverged branches fork
// at many distinct depths rather than a handful of fixed points.
@@ -1378,14 +1252,19 @@ fn build_mixed_repo_at(
add_remote_tracking_refs(remote_tracking_refs, &repo);
run_git(&repo, &["gc", "-q"]);
+ add_heterogeneous_worktrees(&repo, linked_worktrees, &base_tip);
+}
+
+/// Add linked worktrees in the canonical four-state rotation.
+fn add_heterogeneous_worktrees(repo: &Path, linked_worktrees: usize, base_tip: &str) {
// Linked worktrees are siblings named `<repo-dir>.<branch>` (worktrunk
// convention), derived from the repo's own directory name so the path is
// correct whether the repo is the tempdir's `repo` or a custom `setup` path.
for j in 0..linked_worktrees {
let branch = format!("wt-{j:04}");
- let wt = linked_worktree_path(&repo, &branch);
+ let wt = linked_worktree_path(repo, &branch);
run_git(
- &repo,
+ repo,
&[
"worktree",
"add",
@@ -1393,7 +1272,7 @@ fn build_mixed_repo_at(
"-b",
&branch,
wt.to_str().unwrap(),
- &base_tip,
+ base_tip,
],
);
match j % 4 {
@@ -1417,42 +1296,6 @@ fn build_mixed_repo_at(
}
}
-/// Create a repo shaped like a `wt step prune` workload at `base_path`.
-///
-/// `wt step prune` integration-checks every linked worktree and local branch,
-/// then removes the integrated ones. Two populations drive its cost:
-///
-/// - **Candidates** (`candidate_pairs`): squash-merged worktrees
-/// (`merged-wt-N`) and squash-merged orphan branches (`merged-br-N`). Each
-/// carries its own commits whose content also landed on main as a single
-/// squash commit, so it is integrated *by content* (the `merge-tree` probes),
-/// not by ancestry β€” the post-PR-squash shape prune typically removes.
-/// - **Backdrop** (`backdrop_pairs`): two-sided-diverged linked worktrees
-/// and orphan branches (`add_diverged_backdrop` β€” forked at points spread
-/// across history, with their own commits, while main advanced past them).
-/// Scanned on every run, never removed β€” the steady state that dominates
-/// scan cost, and the shape where merge-base walks and merge-tree
-/// three-ways do real work rather than short-circuiting at the tip.
-///
-/// The main history is mature (200 commits, 100 files) so `git status` and the
-/// integration probes pay realistic per-worktree costs.
-fn build_prune_repo_at(candidate_pairs: usize, backdrop_pairs: usize, base_path: &Path) {
- let config = FlatRepoConfig {
- commits_on_main: 200,
- files: 100,
- branchless_branches: 0,
- commits_per_branch: 0,
- total_worktrees: 1,
- worktree_commits_ahead: 0,
- worktree_uncommitted_files: 0,
- };
- build_flat_repo_at(&config, base_path);
- add_prune_populations(base_path, candidate_pairs, backdrop_pairs);
- // The squash commits advanced main past the fake remote ref written by
- // `build_flat_repo_at`; refresh so origin/main tracks the final tip.
- setup_fake_remote(base_path);
-}
-
/// Add `count` squash-merged worktrees (`merged-wt-N`) and `count`
/// squash-merged orphan branches (`merged-br-N`) to an existing repo.
///
@@ -1461,7 +1304,7 @@ fn build_prune_repo_at(candidate_pairs: usize, backdrop_pairs: usize, base_path:
/// `git merge --squash` commit β€” integrated by content, so `wt step prune`
/// detects it via the merge-tree probes and removes it.
///
-pub fn add_squash_merged(repo_path: &Path, count: usize) {
+fn add_squash_merged(repo_path: &Path, count: usize) {
let default_branch = capture_git(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]);
// Two commits in `dir`, each adding a branch-uniquified file. The add is
@@ -1520,20 +1363,20 @@ pub fn add_squash_merged(repo_path: &Path, count: usize) {
/// β€” the backdrop prune scans every run but never removes) and `candidate_pairs`
/// squash-merged candidate pairs (`add_squash_merged` β€” what prune removes).
///
-/// The base repo is the only thing the synthetic and large-repository prune
-/// recipes differ in. Both layer these populations on top.
-fn add_prune_populations(base_path: &Path, candidate_pairs: usize, backdrop_pairs: usize) {
+/// The corpus remains one of the two canonical bases; prune is an overlay.
+pub fn add_prune_populations(base_path: &Path, candidate_pairs: usize, backdrop_pairs: usize) {
add_diverged_backdrop(base_path, backdrop_pairs, backdrop_pairs);
add_squash_merged(base_path, candidate_pairs);
+ // Candidate squash commits advance the default branch. Keep the fake
+ // remote aligned so default-branch discovery sees the final state.
+ setup_fake_remote(base_path);
}
-/// Default populations for the large-repository prune fixture:
+/// Default populations for the imported prune overlay:
/// 12 squash-merged candidates of each kind + 24 unmerged worktrees and
-/// branches β†’ 36 linked worktrees, and a live prune that removes 24
-/// candidates while keeping 72 unmerged items β€” the "dozens of worktrees,
-/// lots removed, lots kept" shape where prune takes multiple seconds.
-pub const PRUNE_LARGE_REPOSITORY_CANDIDATE_PAIRS: usize = 12;
-pub const PRUNE_LARGE_REPOSITORY_BACKDROP_PAIRS: usize = 24;
+/// branches layered onto the canonical imported state.
+pub const IMPORTED_PRUNE_CANDIDATE_PAIRS: usize = 12;
+pub const IMPORTED_PRUNE_BACKDROP_PAIRS: usize = 24;
/// Canonicalize path without Windows `\\?\` prefix.
pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
@@ -1544,8 +1387,8 @@ pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
mod tests {
use super::*;
- fn create_flat(config: &FlatRepoConfig) -> FixtureRepo {
- FixtureRepo::create(|repo| build_flat_repo_at(config, repo))
+ fn create_simple(config: &SimpleRepoConfig) -> FixtureRepo {
+ FixtureRepo::create(|repo| build_simple_repo_at(config, repo))
}
/// Sorted `git status --porcelain` lines for a worktree.
@@ -1625,17 +1468,17 @@ mod tests {
}
#[test]
- fn large_repository_source_rejects_a_missing_pinned_commit_object() {
+ fn imported_source_rejects_a_missing_pinned_commit_object() {
let temp = tempfile::tempdir().unwrap();
init_bench_repo(temp.path());
std::fs::write(
temp.path().join(".git/refs/heads/main"),
- format!("{LARGE_REPOSITORY_REVISION}\n"),
+ format!("{IMPORTED_REVISION}\n"),
)
.unwrap();
assert!(
- !large_repository_source_matches(temp.path()),
+ !imported_source_matches(temp.path()),
"a textual ref without its commit object is not a usable clone source"
);
}
@@ -1648,11 +1491,9 @@ mod tests {
/// is primary storage rather than a disposable cache.
#[test]
fn invalidate_preserves_repository_state_and_clears_caches() {
- let fixture = create_flat(&FlatRepoConfig {
+ let fixture = create_simple(&SimpleRepoConfig {
commits_on_main: 2,
files: 2,
- branchless_branches: 0,
- commits_per_branch: 0,
total_worktrees: 2,
worktree_commits_ahead: 1,
worktree_uncommitted_files: 0,
@@ -1760,7 +1601,13 @@ mod tests {
#[test]
#[should_panic(expected = "failed to remove cache directory")]
fn invalidate_reports_cache_removal_errors() {
- let fixture = FixtureRecipe::Typical { total_worktrees: 1 }.create();
+ let fixture = create_simple(&SimpleRepoConfig {
+ commits_on_main: 1,
+ files: 1,
+ total_worktrees: 1,
+ worktree_commits_ahead: 0,
+ worktree_uncommitted_files: 0,
+ });
let git_dir = resolve_git_common_dir(fixture.path()).unwrap();
std::fs::create_dir_all(git_dir.join("wt")).unwrap();
std::fs::write(git_dir.join("wt/cache"), "not a directory\n").unwrap();
@@ -1768,7 +1615,7 @@ mod tests {
invalidate_probe_caches(fixture.path());
}
- /// The `full` fixture's contract: [`FixtureRecipe::Mixed`] promises a
+ /// The generated fixture's contract promises a
/// deterministic `index % 4` rotation of branch and worktree states, and
/// every `wt list` gate the `full` bench exercises hangs off that rotation.
/// Nothing else pins it β€” the bench measures one wall time, so a generator
@@ -1776,11 +1623,11 @@ mod tests {
/// green while silently measuring a different repo. Assert the states
/// directly, via `merge-base --is-ancestor` exit codes and porcelain status.
#[test]
- fn mixed_fixture_states_follow_the_documented_rotation() {
+ fn generated_fixture_states_follow_the_documented_rotation() {
// 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 = FixtureRecipe::Mixed {
+ let fixture = FixtureRecipe::Generated {
linked_worktrees: N,
branchless_branches: N,
remote_tracking_refs: 0,
@@ -1884,11 +1731,9 @@ mod tests {
/// prune benchmark stops removing anything.
#[test]
fn squash_merged_fixture_is_content_integrated() {
- let fixture = create_flat(&FlatRepoConfig {
+ let fixture = create_simple(&SimpleRepoConfig {
commits_on_main: 3,
files: 2,
- branchless_branches: 0,
- commits_per_branch: 0,
total_worktrees: 1,
worktree_commits_ahead: 0,
worktree_uncommitted_files: 0,
@@ -1920,11 +1765,9 @@ mod tests {
/// A zero-size spread is valid and must not divide by zero.
#[test]
fn history_spread_handles_zero_branches() {
- let fixture = create_flat(&FlatRepoConfig {
+ let fixture = create_simple(&SimpleRepoConfig {
commits_on_main: 3,
files: 1,
- branchless_branches: 0,
- commits_per_branch: 0,
total_worktrees: 1,
worktree_commits_ahead: 0,
worktree_uncommitted_files: 0,
@@ -1934,11 +1777,72 @@ mod tests {
add_history_spread_branches(&repo_path, 0);
}
- /// The `mixed` fixture's population contract. Either local dimension may
+ #[test]
+ fn imported_populations_do_not_become_prune_candidates() {
+ let fixture = create_simple(&SimpleRepoConfig {
+ commits_on_main: 12,
+ files: 2,
+ total_worktrees: 1,
+ worktree_commits_ahead: 0,
+ worktree_uncommitted_files: 0,
+ });
+ let repo = fixture.path().to_path_buf();
+ add_history_spread_branches(&repo, 4);
+ add_imported_linked_worktrees(&repo, 4);
+
+ let mut fork_depths = Vec::new();
+ for i in 0..4 {
+ let branch = format!("feature-{i:03}");
+ assert_eq!(
+ capture_git(&repo, &["rev-list", "--count", &format!("main..{branch}")]),
+ "1",
+ "{branch} must carry its own commit"
+ );
+ assert!(
+ !run_git_ok(&repo, &["merge-base", "--is-ancestor", &branch, "main"]),
+ "{branch} must not be integrated into main"
+ );
+ fork_depths.push(
+ capture_git(&repo, &["rev-list", "--count", &format!("{branch}..main")])
+ .parse::<usize>()
+ .unwrap(),
+ );
+ }
+ assert!(
+ fork_depths.windows(2).all(|depths| depths[0] < depths[1]),
+ "forks must spread down history: {fork_depths:?}"
+ );
+
+ add_prune_populations(&repo, 1, 1);
+ let main_tree = capture_git(&repo, &["rev-parse", "main^{tree}"]);
+ for i in 0..4 {
+ let branch = format!("feature-{i:03}");
+ assert!(
+ !run_git_ok(&repo, &["merge-base", "--is-ancestor", &branch, "main"]),
+ "{branch} became integrated after the prune overlay advanced main"
+ );
+ assert_ne!(
+ capture_git(&repo, &["merge-tree", "--write-tree", "main", &branch]),
+ main_tree,
+ "{branch} became content-integrated after the prune overlay"
+ );
+ }
+ assert!(
+ !run_git_ok(&repo, &["merge-base", "--is-ancestor", "wt-0003", "main"]),
+ "clean imported worktree became integrated after the prune overlay"
+ );
+ assert_ne!(
+ capture_git(&repo, &["merge-tree", "--write-tree", "main", "wt-0003"]),
+ main_tree,
+ "clean imported worktree became content-integrated after the prune overlay"
+ );
+ }
+
+ /// The generated fixture's population contract. Either local dimension may
/// be zero, and the requested remote-tracking refs are additive to the
- /// `origin/main` and `origin/HEAD` pair every synthetic fixture carries.
+ /// `origin/main` and `origin/HEAD` pair every generated fixture carries.
#[test]
- fn mixed_fixture_preserves_each_population() {
+ fn generated_fixture_preserves_each_population() {
let refs = |repo: &Path, glob: &str| {
capture_git(repo, &["for-each-ref", "--format=%(refname:short)", glob])
.lines()
@@ -1954,7 +1858,7 @@ mod tests {
};
// Cover each local zero once and add remote refs to one fixture.
- let fixture = FixtureRecipe::Mixed {
+ let fixture = FixtureRecipe::Generated {
linked_worktrees: 3,
branchless_branches: 0,
remote_tracking_refs: 5,
@@ -1966,7 +1870,7 @@ mod tests {
assert_eq!(refs(&repo, "refs/remotes/origin/remote-only-*"), 5);
assert_eq!(linked(&repo), 3);
- let fixture = FixtureRecipe::Mixed {
+ let fixture = FixtureRecipe::Generated {
linked_worktrees: 0,
branchless_branches: 3,
remote_tracking_refs: 0,
@@ -1991,11 +1895,9 @@ mod tests {
/// parameters is invisible there and would be caught only here.
#[test]
fn diverged_backdrop_is_unintegrated_and_spread_across_history() {
- let fixture = create_flat(&FlatRepoConfig {
+ let fixture = create_simple(&SimpleRepoConfig {
commits_on_main: 40,
files: 2,
- branchless_branches: 0,
- commits_per_branch: 0,
total_worktrees: 1,
worktree_commits_ahead: 0,
worktree_uncommitted_files: 0,
@@ -2020,7 +1922,7 @@ mod tests {
// Orphan branches: 4 of them, 3 own commits each.
let mut depths = Vec::new();
for i in 0..4 {
- let branch = format!("feature-{i:03}");
+ let branch = format!("unmerged-br-{i:03}");
let (behind, ahead) = counts(&branch);
assert_eq!(ahead, 3, "{branch} must carry its own commits");
assert!(
@@ -2042,7 +1944,7 @@ mod tests {
// untracked scratch β€” no staged or unstaged tracked changes, which is
// what keeps index-restoring helpers safe to run against them.
for i in 0..3 {
- let branch = format!("feature-wt-{i}");
+ let branch = format!("unmerged-wt-{i}");
let (_, ahead) = counts(&branch);
assert_eq!(ahead, 5, "{branch} must carry its own commits");
let wt = fixture.worktree_path(&branch);
@@ -2053,7 +1955,7 @@ mod tests {
);
}
assert!(
- !fixture.worktree_path("feature-wt-3").exists(),
+ !fixture.worktree_path("unmerged-wt-3").exists(),
"worktree count must not follow the branch count"
);
}
diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rs
index c0a9d797f..955e1c23e 100644
--- a/tests/helpers/wt-perf/src/main.rs
+++ b/tests/helpers/wt-perf/src/main.rs
@@ -8,7 +8,7 @@ use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use clap::{Parser, Subcommand};
-use wt_perf::{FixtureRecipe, canonicalize, invalidate_caches_auto};
+use wt_perf::{FixtureRecipe, add_prune_populations, canonicalize, invalidate_caches_auto};
#[derive(Parser)]
#[command(name = "wt-perf")]
@@ -28,6 +28,14 @@ enum Commands {
/// Primary worktree path; must not already exist
#[arg(long, global = true)]
path: Option<PathBuf>,
+
+ /// Squash-merged worktree/branch pairs to add for prune investigation
+ #[arg(long, global = true, default_value_t = 0)]
+ prune_candidates: usize,
+
+ /// Unintegrated worktree/branch pairs to add as prune scan backdrop
+ #[arg(long, global = true, default_value_t = 0)]
+ prune_backdrop: usize,
},
/// Parse a trace.jsonl and output Chrome Trace Format JSON
@@ -67,7 +75,7 @@ enum Commands {
wt-perf timeline --cold -- list
# Cold run against a specific repo (setup prints the exact path)
- wt-perf timeline --cold -- -C /tmp/wt-typical-1 list
+ wt-perf timeline --cold -- -C target/wt-generated list
# Chrome Trace Format JSON for Perfetto
wt-perf timeline --chrome -- list > trace.json
@@ -91,7 +99,12 @@ fn main() {
let cli = Cli::parse();
match cli.command {
- Commands::Setup { recipe, path } => {
+ Commands::Setup {
+ recipe,
+ path,
+ prune_candidates,
+ prune_backdrop,
+ } => {
let Some(path) = path else {
eprintln!("Missing required --path for benchmark fixture setup.");
std::process::exit(2);
@@ -128,12 +141,10 @@ fn main() {
eprintln!("Creating fixture at {}...", base_path.display());
recipe.create_at(&base_path);
+ add_prune_populations(&base_path, prune_candidates, prune_backdrop);
eprintln!("Created: main @ {}", base_path.display());
eprintln!();
- let example_args = if matches!(
- recipe,
- FixtureRecipe::Prune { .. } | FixtureRecipe::LargeRepositoryPrune { .. }
- ) {
+ let example_args = if prune_candidates > 0 || prune_backdrop > 0 {
"step prune --dry-run --min-age 0s"
} else {
"list --progressive"
diff --git a/tests/helpers/wt-perf/tests/cli.rs b/tests/helpers/wt-perf/tests/cli.rs
index 1be213037..35621e818 100644
--- a/tests/helpers/wt-perf/tests/cli.rs
+++ b/tests/helpers/wt-perf/tests/cli.rs
@@ -46,35 +46,32 @@ fn setup_help_exposes_the_semantic_fixture_catalog() {
"setup must require an explicit destination:\n{stdout}"
);
- for subcommand in [
- "typical",
- "minimal",
- "synthetic-divergence",
- "large-repository",
- "mixed",
- "prune",
- "large-repository-prune",
- ] {
- assert!(
- stdout.contains(subcommand),
- "setup help must list {subcommand}:\n{stdout}"
- );
- }
- for removed in [
- "large-repository-worktrees",
- "large-repository-history-spread",
- "picker-test",
- ] {
+ let commands = stdout
+ .split("Commands:\n")
+ .nth(1)
+ .unwrap()
+ .split("\n\nOptions:")
+ .next()
+ .unwrap()
+ .lines()
+ .filter_map(|line| {
+ line.strip_prefix(" ")
+ .filter(|line| !line.starts_with(' '))
+ })
+ .filter_map(|line| line.split_whitespace().next())
+ .collect::<Vec<_>>();
+ assert_eq!(commands, ["generated", "imported", "help"]);
+ for overlay in ["--prune-candidates", "--prune-backdrop"] {
assert!(
- !stdout.contains(removed),
- "setup help must not retain obsolete recipe {removed}:\n{stdout}"
+ stdout.contains(overlay),
+ "setup help must expose prune state as an overlay:\n{stdout}"
);
}
}
#[test]
-fn setup_validation_does_not_acquire_large_repository_fixtures() {
- let output = run_wt_perf(&["setup", "minimal", "0", "0"]);
+fn setup_validation_does_not_acquire_imported_fixture() {
+ let output = run_wt_perf(&["setup", "generated"]);
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr).contains("Missing required --path"),
@@ -85,8 +82,10 @@ fn setup_validation_does_not_acquire_large_repository_fixtures() {
let path = tempfile::tempdir().expect("Failed to create temp dir");
let output = run_wt_perf(&[
"setup",
- "large-repository-prune",
+ "imported",
+ "--prune-candidates",
"12",
+ "--prune-backdrop",
"24",
"--path",
path.path().to_str().unwrap(),
@@ -98,15 +97,8 @@ fn setup_validation_does_not_acquire_large_repository_fixtures() {
#[test]
fn setup_builds_a_semantic_recipe_at_an_explicit_path() {
let root = tempfile::tempdir().expect("Failed to create temp dir");
- let repo = root.path().join("minimal-fixture");
- let output = run_wt_perf(&[
- "setup",
- "minimal",
- "0",
- "0",
- "--path",
- repo.to_str().unwrap(),
- ]);
+ let repo = root.path().join("generated-fixture");
+ let output = run_wt_perf(&["setup", "generated", "--path", repo.to_str().unwrap()]);
assert!(
output.status.success(),
"setup failed:\n{}",
@@ -122,6 +114,27 @@ fn setup_builds_a_semantic_recipe_at_an_explicit_path() {
"setup must not advertise the removed standalone command:\n{stderr}"
);
assert!(repo.join(".git").is_dir(), "setup must create a git repo");
+}
+
+#[test]
+fn setup_layers_prune_state_onto_a_canonical_base() {
+ let root = tempfile::tempdir().expect("Failed to create temp dir");
+ let repo = root.path().join("prune-fixture");
+ let output = run_wt_perf(&[
+ "setup",
+ "generated",
+ "--prune-candidates",
+ "1",
+ "--prune-backdrop",
+ "1",
+ "--path",
+ repo.to_str().unwrap(),
+ ]);
+ assert!(
+ output.status.success(),
+ "setup failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
let branches = Command::new("git")
.args([
@@ -133,7 +146,19 @@ fn setup_builds_a_semantic_recipe_at_an_explicit_path() {
.output()
.expect("Failed to inspect built fixture");
assert!(branches.status.success());
- assert_eq!(String::from_utf8_lossy(&branches.stdout), "main\n");
+ let branches = String::from_utf8(branches.stdout).unwrap();
+ for branch in [
+ "main",
+ "merged-br-0",
+ "merged-wt-0",
+ "unmerged-br-000",
+ "unmerged-wt-0",
+ ] {
+ assert!(
+ branches.lines().any(|found| found == branch),
+ "missing {branch}:\n{branches}"
+ );
+ }
}
#[test]
@@ -148,14 +173,7 @@ fn setup_never_mutates_an_existing_destination() {
destination.clone(),
root.path().join("missing-parent/../existing"),
] {
- let output = run_wt_perf(&[
- "setup",
- "minimal",
- "0",
- "1",
- "--path",
- path.to_str().unwrap(),
- ]);
+ let output = run_wt_perf(&["setup", "generated", "--path", path.to_str().unwrap()]);
assert!(
!output.status.success(),
"setup unexpectedly accepted {path:?}"